Java 类java.util.logging.Handler 实例源码

项目:incubator-netbeans    文件:LogFormatterTest.java   
public void testUnknownLevels() throws IOException {
    TestLevel level = new TestLevel("WARN", 233);
    LogRecord r = new LogRecord(level, "Custom level test");
    Formatter formatter = new LogFormatter();
    String s = formatter.format(r);
    cleanKnownLevels();
    final LogRecord[] rPtr = new LogRecord[] { null };
    Handler h = new Handler() {
        @Override
        public void publish(LogRecord record) {
            rPtr[0] = record;
        }
        @Override
        public void flush() {}
        @Override
        public void close() throws SecurityException {}
    };
    LogRecords.scan(new ReaderInputStream(new StringReader(s)), h);
    assertEquals("level", r.getLevel(), rPtr[0].getLevel());
}
项目:Suji    文件:LogHelper.java   
private LogHelper() {
    try {
        logger = Logger.getLogger(LogHelper.class.getName());

        if ( DEBUG )
            logger.setLevel(Level.ALL);
        else
            logger.setLevel(Level.WARNING);

        Handler handler = new FileHandler("%t/suji.log", 0, 1, false);
        logger.addHandler(handler);
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}
项目:aceql-http    文件:DefaultDatabaseConfigurator.java   
/**
 * Creates a static {@code Logger} instance.
 * 
 * @return a static {@code Logger} with properties:
 *         <ul>
 *         <li>Name: {@code "DefaultDatabaseConfigurator"}.</li>
 *         <li>Output file pattern:
 *         {@code user.home/.kawansoft/log/AceQL.log}.</li>
 *         <li>Formatter: {@code SimpleFormatter}.</li>
 *         <li>Limit: 200Mb.</li>
 *         <li>Count (number of files to use): 2.</li>
 *         </ul>
 */
@Override
public Logger getLogger() throws IOException {
    if (ACEQL_LOGGER != null) {
        return ACEQL_LOGGER;
    }

    File logDir = new File(SystemUtils.USER_HOME + File.separator + ".kawansoft" + File.separator + "log");
    logDir.mkdirs();

    String pattern = logDir.toString() + File.separator + "AceQL.log";

    ACEQL_LOGGER = Logger.getLogger(DefaultDatabaseConfigurator.class.getName());
    Handler fh = new FileHandler(pattern, 200 * 1024 * 1024, 2, true);
    fh.setFormatter(new SimpleFormatter());
    ACEQL_LOGGER.addHandler(fh);
    return ACEQL_LOGGER;

}
项目:alvisnlp    文件:AbstractAlvisNLP.java   
private void setHandlers(Logger logger, File file) throws FileNotFoundException {
    for (Handler h : logger.getHandlers()) {
        logger.removeHandler(h);
    }
      Handler stderrHandler = new FlushedStreamHandler(System.err, noColors ? CommandLineLogFormatter.INSTANCE : CommandLineLogFormatter.COLORS);
      logger.addHandler(stderrHandler);
      if (file == null)
    stderrHandler.setLevel(logLevel);
else {
    File dir = file.getParentFile();
    if (dir != null) {
        dir.mkdirs();
    }
          Handler fileHandler = new FlushedStreamHandler(new FileOutputStream(file, appendToLog), CommandLineLogFormatter.INSTANCE);
          logger.addHandler(fileHandler);
          if (logLevel.intValue() < Level.FINE.intValue()) {
              fileHandler.setLevel(logLevel);
              stderrHandler.setLevel(Level.FINE);
          }
          else {
              fileHandler.setLevel(Level.FINE);
              stderrHandler.setLevel(logLevel);
          }
      }
  }
项目:jboss-eap7.1-playground    文件:AbstractLoggerMain.java   
static private void setLogging(int logging) {
        Level logLevel = getLogLevel(logging%10);

        Logger.getLogger("org.jboss.wfink.eap71.playground").setLevel(logLevel);

        logLevel = getLogLevel((logging/10)%10);
        Logger.getLogger("org.xnio").setLevel(logLevel);
        Logger.getLogger("org.jboss.remoting").setLevel(logLevel);  //classes are remoting3

        logLevel = getLogLevel((logging/100)%10);
        Logger.getLogger("org.jboss.ejb.client").setLevel(logLevel);

        logLevel = getLogLevel((logging/1000)%10);
        Logger.getLogger("org.wildfly").setLevel(logLevel);

//      Logger.getLogger("org.jboss.invocation").setLevel(logLevel);

        // change default ConsoleHandler
        Logger root = Logger.getLogger("");
        Handler[] handlers = root.getHandlers();
        for (int i = 0; i < handlers.length; i++) {
            root.removeHandler(handlers[i]);
        }
        ConsoleHandler handler = new ConsoleHandler();
        handler.setFormatter(new PlaygroundFormatter());
        handler.setLevel(Level.ALL);
        root.addHandler(handler);
    }
项目:monarch    文件:GfshInitFileJUnitTest.java   
@BeforeClass
public static void setUpBeforeClass() throws Exception {
  saveLog4j2Config = System.getProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
  saveUserDir = System.getProperty("user.dir");
  saveUserHome = System.getProperty("user.home");

  julLogger = java.util.logging.Logger.getLogger("");
  saveHandlers = julLogger.getHandlers();
  for (Handler handler : saveHandlers) {
    julLogger.removeHandler(handler);
  }

  File log4j2XML = temporaryFolder_Config.newFile("log4j2.xml");
  FileUtils.writeStringToFile(log4j2XML, "<Configuration/>", APPEND);
  System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
      log4j2XML.toURI().toString());
}
项目:alvisnlp    文件:PlanBuilder.java   
public PlanBuilder(File planDir, File resourceDir) {
    super();

    this.planDir = planDir;
    this.resourceDir = resourceDir;

    logger = Logger.getLogger(ALVISNLP_LOGGER_NAME);
    Level logLevel = Level.INFO;
    logger.setLevel(logLevel);
    logger.setUseParentHandlers(false);
    for (Handler h : logger.getHandlers()) {
        logger.removeHandler(h);
    }
    Handler stderrHandler = new FlushedStreamHandler(System.err, CommandLineLogFormatter.INSTANCE);
    logger.addHandler(stderrHandler);
    stderrHandler.setLevel(logLevel);

       moduleFactory = new CompoundCorpusModuleFactory();
       moduleFactory.loadServiceFactories(CorpusModuleFactory.class, null, null, null);

       converterFactory = new CompoundParamConverterFactory();
       converterFactory.loadServiceFactories(ParamConverterFactory.class, null, null, null);
}
项目:monarch    文件:GfshInitFileJUnitTest.java   
@AfterClass
public static void tearDownAfterClass() throws Exception {
  for (Handler handler : saveHandlers) {
    julLogger.addHandler(handler);
  }

  if (saveLog4j2Config == null) {
    System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
  } else {
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, saveLog4j2Config);
    ((LoggerContext) LogManager.getContext(false)).reconfigure();
  }

  if (saveUserDir == null) {
    System.clearProperty("user.dir");
  } else {
    System.setProperty("user.dir", saveUserDir);
  }
  if (saveUserHome == null) {
    System.clearProperty("user.home");
  } else {
    System.setProperty("user.home", saveUserHome);
  }
}
项目:incubator-netbeans    文件:TopLogging.java   
private static synchronized Handler defaultHandler() {
    if (defaultHandler != null) return defaultHandler;

    File home = Places.getUserDirectory();
    if (home != null && !CLIOptions.noLogging) {
        File dir = new File(new File(home, "var"), "log");
        dir.mkdirs ();

        Handler h = NbLogging.createMessagesHandler(dir);
        defaultHandler = NbLogging.createDispatchHandler(h, 5000);
    }

    if (defaultHandler == null) {
        defaultHandler = streamHandler();
        disabledConsole = true;
    }
    return defaultHandler;
}
项目:incubator-netbeans    文件:TopLogging.java   
/** Allows tests to flush all standard handlers */
static void flush(boolean clear) {
    System.err.flush();


    Handler s = streamHandler;
    if (s != null) {
        s.flush();
    }

    Handler d = defaultHandler;
    if (d != null) {
        d.flush();
    }

    if (clear) {
        streamHandler = null;
        defaultHandler = null;
    }
}
项目:incubator-netbeans    文件:TopLoggingOwnConfigClassTest.java   
private String readLog() throws IOException {
    Handler[] ha = Logger.getLogger("").getHandlers();
    assertEquals("There is one handler", 1, ha.length);
    ha[0].flush();

    assertTrue("Log file exists: " + log, log.canRead());

    FileInputStream is = new FileInputStream(log);

    byte[] arr = new byte[(int)log.length()];
    int r = is.read(arr);
    assertEquals("all read", arr.length, r);
    is.close();

    return new String(arr);
}
项目:incubator-netbeans    文件:LinuxNotifier235632Test.java   
/**
 * Create a logging handler that sets value in an AtomicBoolean to true if
 * folder2 or text2.txt is refreshed.
 *
 * @param refreshedFlag The AtomicBoolean to be set to true if incorrect
 * refreshing was triggered.
 * @return The new logging handler.
 */
private Handler createHandler(final AtomicBoolean refreshedFlag) {
    Handler h = new Handler() {

        @Override
        public void publish(LogRecord record) {
            if (record.getMessage() != null
                    && record.getMessage().startsWith("refreshImpl for ")
                    && record.getParameters() != null
                    && record.getParameters().length > 0
                    && (record.getParameters()[0] == folder2FO
                    || record.getParameters()[0] == folder2text2TxtFO)) {
                refreshedFlag.set(true);
            }
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    };
    return h;
}
项目:incubator-netbeans    文件:Installer.java   
static void readLogs(Handler handler){
    UIHandler.waitFlushed();
    synchronized (UIGESTURE_LOG_LOCK) {

        File f = logFile(0);
        if (f == null || !f.exists()) {
            return ;
        }
        closeLogStream();

        File f1 = logFile(1);
        if (logsSize < UIHandler.MAX_LOGS && f1 != null && f1.exists()) {
            scan(f1, handler);
        }
        scan(f, handler);
    }
}
项目:incubator-netbeans    文件:Installer.java   
private static void scan(File f, Handler handler){
    try {
        LogRecords.scan(f, handler);
    } catch (IOException ex) {
        LOG.log(Level.INFO, "Broken uilogs file, not all UI actions will be submitted", ex);
        if (!fileContentReported) {
            try {
                if (LOG.isLoggable(Level.INFO)) {
                    LOG.log(Level.INFO, "Problematic file content = {0}", reportFileContent(f));
                }
            } finally {
                fileContentReported = true;
            }
        }
    }
}
项目:incubator-netbeans    文件:ConstrainedBinaryIndexerTest.java   
MockConstrainedIndexer() {
    h = new Handler() {
        @Override
        public void publish(LogRecord record) {
            if (record.getMessage().equals("RootsWork-finished")) {
                sem.release();
            }
        }
        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    };
    final Logger log = Logger.getLogger(RepositoryUpdater.class.getName() + ".tests"); //NOI18N
    log.setLevel(Level.FINEST);
    log.addHandler(h);
}
项目:Equella    文件:TomcatLogRedirector.java   
/**
 * Activates this feature.
 */
public static void activate()
{
    try
    {
        Logger rootLogger = LogManager.getLogManager().getLogger("");
        // remove old ConsoleHandler
        for( Handler handler : rootLogger.getHandlers() )
        {
            rootLogger.removeHandler(handler);
        }

        activeHandler = new JDKLogHandler();
        activeHandler.setLevel(Level.ALL);
        rootLogger.addHandler(activeHandler);
        rootLogger.setLevel(Level.ALL);
    }
    catch( Exception exc )
    {
        LogFactory.getLog(TomcatLogRedirector.class).error("activation failed", exc);
    }
}
项目:Example.EMA.Java.SpeedGuide    文件:SpeedGuideConsumer.java   
public void setDebug(boolean debug)
{
    _debug = debug;
    _consumerClient.setDebug(debug);

    if (!debug)
    {
        final Logger parentLogger = Logger.getAnonymousLogger().getParent();

        // Disable console logger if debug mode not turned on
        for (Handler handler : parentLogger.getHandlers())
        {
            if ( handler instanceof ConsoleHandler )
                parentLogger.removeHandler(handler);
        }
    }
}
项目:incubator-netbeans    文件:LogRecordsTest.java   
public void testAlwaysSetParamters() throws Exception {
    String what = "actionDelegates.xml";
    InputStream is = getClass().getResourceAsStream(what);
    class H extends Handler {
        int cnt;

        public void publish(LogRecord record) {
            cnt++;
            if (record.getParameters() == null) {
                fail("Each record shall have paramters, #" + cnt + " did not: " + record.getMessage());
            }
        }

        public void flush() {
        }

        public void close() throws SecurityException {
        }
    }

    H h = new H();
    is = getClass().getResourceAsStream(what);
    LogRecords.scan(is, h);
    is.close();

    assertEquals("The four amount of records", 5, h.cnt);
}
项目:openjdk-jdk10    文件:CrashNaNTest.java   
public static void main(String argv[]) {
    Locale.setDefault(Locale.US);

    // initialize j.u.l Looger:
    final Logger log = Logger.getLogger("sun.java2d.marlin");
    log.addHandler(new Handler() {
        @Override
        public void publish(LogRecord record) {
            Throwable th = record.getThrown();
            // detect any Throwable:
            if (th != null) {
                System.out.println("Test failed:\n" + record.getMessage());
                th.printStackTrace(System.out);

                throw new RuntimeException("Test failed: ", th);
            }
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    });

    // enable Marlin logging & internal checks:
    System.setProperty("sun.java2d.renderer.log", "true");
    System.setProperty("sun.java2d.renderer.useLogger", "true");
    System.setProperty("sun.java2d.renderer.doChecks", "true");

    testFillDefaultAt();
    testDrawComplexAt();

    testPathClosed();

    testStrokedShapes();
}
项目:incubator-netbeans    文件:ReadBigDataTest.java   
private int readAsSAX(final int[] cnts, int err, final File[] arr) throws IOException, FileNotFoundException {
    class H extends Handler {
        int cnt;

        public void publish(LogRecord record) {
            cnt++;
        }

        public void flush() {
        }

        public void close() throws SecurityException {
        }
    }

    int i = -1;
    for (File f : arr) {
        LOG.log(Level.WARNING, "scanning {0}", f.getPath());
        i++;
        InputStream is = new BufferedInputStream(new FileInputStream(f));
        H h = new H();
        try {
            LogRecords.scan(is, h);
        } catch (IOException ex) {
            LOG.log(Level.WARNING, null, ex);
            err++;
            continue;
        } finally {
            is.close();
        }

        assertEquals("The same amount for " + f, h.cnt, cnts[i]);
    }
    return err;
}
项目:incubator-netbeans    文件:TestKit.java   
public static void removeHandlers(Logger log) {
    if (log != null) {
        Handler[] handlers = log.getHandlers();
        for (int i = 0; i < handlers.length; i++) {
            log.removeHandler(handlers[i]);
        }
    }
}
项目:incubator-netbeans    文件:StatusTest.java   
public void testPurgeRemovedIgnoredFiles () throws Exception {
    File folder = new File(repositoryLocation, "folder");
    final File file1 = new File(folder, "ignored");
    folder.mkdirs();
    file1.createNewFile();

    File ignoreFile = new File(repositoryLocation, ".gitignore");
    write(ignoreFile, "ignored");
    getCache().refreshAllRoots(Collections.<File, Collection<File>>singletonMap(repositoryLocation, Collections.singleton(file1)));
    assertTrue(getCache().getStatus(file1).containsStatus(Status.NOTVERSIONED_EXCLUDED));
    file1.delete();
    assertFalse(file1.exists());
    final boolean[] cleaned = new boolean[1];
    Git.STATUS_LOG.addHandler(new Handler() {
        @Override
        public void publish(LogRecord record) {
            if (record.getMessage().contains("refreshAllRoots() uninteresting file: {0}") && file1.equals(record.getParameters()[0])) {
                cleaned[0] = true;
            }
        }
        @Override
        public void flush() {
        }
        @Override
        public void close() throws SecurityException {
        }
    });
    getCache().refreshAllRoots(Collections.<File, Collection<File>>singletonMap(repositoryLocation, Collections.singleton(folder)));
    assertTrue(cleaned[0]);
}
项目:incubator-netbeans    文件:CslTestBase.java   
protected ComputedHints getHints(NbTestCase test, Rule hint, String relFilePath, FileObject fileObject, String caretLine) throws Exception {
    ComputedHints hints = computeHints(test, hint, relFilePath, fileObject, caretLine, ChangeOffsetType.NONE);

    if (checkAllHintOffsets()) {
        // Run alternate hint computation AFTER the real computation above since we will destroy the document...
        Logger.global.addHandler(new Handler() {
            @Override
            public void publish(LogRecord record) {
                if (record.getThrown() != null) {
                    StringWriter sw = new StringWriter();
                    record.getThrown().printStackTrace(new PrintWriter(sw));
                    fail("Encountered error: " + sw.toString());
                }
            }

            @Override
            public void flush() {
            }

            @Override
            public void close() throws SecurityException {
            }

        });
        for (ChangeOffsetType type : new ChangeOffsetType[] { ChangeOffsetType.OUTSIDE, ChangeOffsetType.OVERLAP }) {
            computeHints(test, hint, relFilePath, fileObject, caretLine, type);
        }
    }

    return hints;
}
项目:incubator-netbeans    文件:NbLogging.java   
/** Does its best to close provided handler. Can close handlers created by
 * {@link #createDispatchHandler(java.util.logging.Handler, int)} as well.
 */
public static void close(Handler h) {
    if (h == null) {
        return;
    }
    if (h instanceof DispatchingHandler) {
        ((DispatchingHandler)h).doClose();
    } else {
        h.close();
    }
}
项目:incubator-netbeans    文件:StartLog.java   
@Override
public String getHead(Handler h) {
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\"");
    sb.append(" encoding='UTF-8'?>\n");
    sb.append("<log>\n");
    return sb.toString();
}
项目:incubator-netbeans    文件:TopLogging.java   
/** Logger for test purposes.
 */
static Handler createStreamHandler (PrintStream pw) {
    StreamHandler s = new StreamHandler (
        pw, NbFormatter.FORMATTER
    );
    return NbLogging.createDispatchHandler(s, 50);
}
项目:Java-EX    文件:LogUtil.java   
public static void setGlobalLevel(Level newLevel) {
  Logger rootLogger = LogManager.getLogManager().getLogger("");
  rootLogger.setLevel(newLevel);
  for (Handler h : rootLogger.getHandlers()) {
    h.setLevel(newLevel);
  }
}
项目:metanome-algorithms    文件:LoggingUtils.java   
public static void disableLogging() {
    // Disable Logging (FastSet sometimes complains about skewed key distributions with lots of WARNINGs)
    Logger root = Logger.getLogger("");
    Handler[] handlers = root.getHandlers();
    for (Handler handler : handlers)
        handler.setLevel(Level.OFF);
}
项目:openjdk-jdk10    文件:DebugLogger.java   
private static Logger instantiateLogger(final String name, final Level level) {
    final Logger logger = java.util.logging.Logger.getLogger(name);
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        @Override
        public Void run() {
            for (final Handler h : logger.getHandlers()) {
                logger.removeHandler(h);
            }

            logger.setLevel(level);
            logger.setUseParentHandlers(false);
            final Handler c = new ConsoleHandler();

            c.setFormatter(new Formatter() {
                @Override
                public String format(final LogRecord record) {
                    final StringBuilder sb = new StringBuilder();

                    sb.append('[')
                    .append(record.getLoggerName())
                    .append("] ")
                    .append(record.getMessage())
                    .append('\n');

                    return sb.toString();
                }
            });
            logger.addHandler(c);
            c.setLevel(level);
            return null;
        }
    }, createLoggerControlAccCtxt());

    return logger;
}
项目:alog    文件:Alog.java   
/**
 * Adds a PrintStreamLogHandler to the named logger, if there isn't one already.
 * This can be used repeatedly to acquire the same logger, but doing so would be
 * inefficient.  Use Logger.getLogger after this has installed the handler.
 *
 * @param name Log name.
 * @param out Where to print the log.
 */
public static Logger getLogger(String name, PrintStream out) {
    Logger ret = Logger.getLogger(name);
    for (Handler handler : ret.getHandlers()) {
        if (handler instanceof PrintStreamLogHandler) {
            PrintStreamLogHandler pslh = (PrintStreamLogHandler) handler;
            if (pslh.getOut() == out) {
                return ret;
            }
        }
    }
    ret.addHandler(new PrintStreamLogHandler(name, out));
    return ret;
}
项目:mi-firma-android    文件:LogManager.java   
/** Obtiene, en formato XML, el registro acumulado de la ejecuci&oacute;n actual.
 * @return Registro acumulado de la ejecuci&oacute;n actual
 * @throws IOException Si no hay registro o este no se puede leer */
public static String getLogFile() throws IOException {
    if (!installed || logFile == null) {
        throw new IOException("No esta instalado el manejador de fichero"); //$NON-NLS-1$
    }

    final Handler[] handlers = LOGGER.getHandlers();
    for (final Handler h : handlers) {
        if (h instanceof FileHandler) {
            h.close();
            LOGGER.info("Cerrado el manejador de fichero para permitir que sea procesado"); //$NON-NLS-1$
            LOGGER.removeHandler(h);
        }
    }

    final InputStream is = new FileInputStream(
        new File(
            logFile.replace("%h", Platform.getUserHome())  //$NON-NLS-1$
        )
    );
    final String log = new String(AOUtil.getDataFromInputStream(is));
    is.close();

    LOGGER.addHandler(createFileHandler(logFile));

    return log;
}
项目:openaudible    文件:AudibleClient.java   
private static void setLevel(Logger pLogger, Level pLevel) {
    Handler[] handlers = pLogger.getHandlers();
    for (Handler h : handlers) {
        h.setLevel(pLevel);
    }
    pLogger.setLevel(pLevel);
}
项目:incubator-netbeans    文件:BaseFileObjectTestHid.java   
public void testDeletedFileDoesNotReturnInputStream() throws Exception {
    final FileObject testFo = FileUtil.createData(root,"testfile.data");
    final File testFile = FileUtil.toFile(testFo);
    final Logger LOGGER = Logger.getLogger(FileObj.class.getName());
    final Handler handler = new Handler() {
        @Override
        public void publish(LogRecord record) {
            if ("FileObj.getInputStream_after_is_valid".equals(record.getMessage())) {
                testFile.delete();
            }
        }
        @Override
        public void flush() {
        }
        @Override
        public void close() throws SecurityException {
        }
    };
    final Level originalLevel = LOGGER.getLevel();
    LOGGER.setLevel(Level.FINEST);
    try {
        LOGGER.addHandler(handler);
        try {
            testFo.getInputStream();
            assertTrue("Exception not thrown by deleted file getInputStream()", false);
        } catch (FileNotFoundException e) {
            //pass - expected exception
        } finally {
            LOGGER.removeHandler(handler);
        }
    } finally {
        LOGGER.setLevel(originalLevel);
    }
}
项目:incubator-netbeans    文件:NotifyExcPanelTest.java   
public void testHandlesThatImplementCallableForJButtonAreIncluded() throws Exception {
    class H extends Handler 
    implements Callable<JButton> {
        public JButton button = new JButton("Extra");

        public void publish(LogRecord arg0) {
        }

        public void flush() {
        }

        public void close() throws SecurityException {
        }

        public JButton call() throws Exception {
            return button;
        }
    } // end of H

    H handler = new H();

    main.addHandler(handler);

    List<Object> options = Arrays.asList(NotifyExcPanel.computeOptions("prev", "next"));

    assertTrue("Contains our button: " + options, options.contains(handler.button));
}
项目:empiria.player    文件:AnswerEvaluationSupplierTest.java   
@Test
public void evaluateAnswer_evaluationBeforeAnswerProcessing() {
    // given
    Response response = mock(Response.class);
    Handler handler = mock(Handler.class);
    LOGGER.addHandler(handler);

    // when
    List<Boolean> evaluation = supplier.evaluateAnswer(response);

    // then
    assertThat(evaluation.isEmpty()).isTrue();
    verify(handler).publish(any(LogRecord.class));

}
项目:bibliome-java-utils    文件:LogBuilder.java   
public Logger getLogger() throws IOException {
    Logger logger = Logger.getLogger("qsync");
    logger.setUseParentHandlers(false);
    Handler handler = new FlushedStreamHandler(System.err, LogFormatter.INSTANCE);
    logger.addHandler(handler);
    if (logFile != null) {
        Handler fileHandler = new FileHandler(logFile);
        logger.addHandler(fileHandler);
    }
    return logger;
}
项目:openjdk-jdk10    文件:LoggerFinderAPITest.java   
public LoggerFinderAPITest(boolean verbose) {
    this.warnDuplicateMappings = verbose;
    for (Handler h : Logger.getLogger("").getHandlers()) {
        if (h instanceof ConsoleHandler) {
            Logger.getLogger("").removeHandler(h);
        }
    }
    Logger.getLogger("").addHandler( new Handler() {
        @Override
        public void publish(LogRecord record) {
            StringBuilder builder = new StringBuilder();
            builder.append("GOT LogRecord: ")
                    .append(record.getLevel().getLocalizedName())
                    .append(": [").append(record.getLoggerName())
                    .append("] ").append(record.getSourceClassName())
                    .append('.')
                    .append(record.getSourceMethodName()).append(" -> ")
                    .append(record.getMessage())
                    .append(' ')
                    .append(record.getParameters() == null ? ""
                            : Arrays.toString(record.getParameters()))
                    ;
            System.out.println(builder);
            if (record.getThrown() != null) {
                record.getThrown().printStackTrace(System.out);
            }
        }
        @Override public void flush() {}
        @Override public void close() {}
    });
}
项目:incubator-netbeans    文件:InstallerTest.java   
public void testCreateMessageIssue160019() throws IOException {//ignore annotations
    final List<LogRecord> logs = new ArrayList<LogRecord>();
    ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
    Exception rootExc = new NullPointerException("root");
    Exceptions.attachMessage(rootExc, "annotation message");
    LogRecord rec = new LogRecord(Level.SEVERE, "test");
    rec.setThrown(rootExc);
    LogRecords.write(bos, rec);
    bos.close();
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    LogRecords.scan(bis, new Handler() {

        @Override
        public void publish(LogRecord record) {
            logs.add(record);
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    });
    bis.close();

    assertEquals(1, logs.size());
    Throwable thrown = logs.get(0).getThrown();
    assertEquals("thrown is annotated", "annotation message", thrown.getCause().getMessage());
    String message = Installer.createMessage(thrown);
    assertEquals("annontation should be ignored", "NullPointerException: root", message);
}
项目:incubator-netbeans    文件:BugTriggersTest.java   
public void testRootLoggerHasHandler() throws Exception {
    for (Handler h : Logger.getLogger("").getHandlers()) {
        if (h instanceof Callable) {
            return;
        }
    }
    fail("No handler which implements Callable");
}
项目:Banmanager    文件:BanmanagerProxy.java   
private void disable() {
    getProxy().getLogger().info("Disabling plugin " + getDescription().getName() + " version " + getDescription().getVersion() + " by " + getDescription().getAuthor());

    try {
        onDisable();
        for (Handler handler : getLogger().getHandlers())
            handler.close();
    } catch (Exception exception) {
        exception.printStackTrace();
    }

    getProxy().getScheduler().cancel(this);
    getExecutorService().shutdownNow();
    getProxy().getLogger().info("Disabled plugin " + getDescription().getName() + " version " + getDescription().getVersion() + " by " + getDescription().getAuthor());
}