java类java.util.logging.Formatter的实例源码

LogFormatterTest.java 文件源码 项目:incubator-netbeans 阅读 36 收藏 0 点赞 0 评论 0
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());
}
JMXLogPublisher.java 文件源码 项目:Pogamut3 阅读 24 收藏 0 点赞 0 评论 0
@Override
public void publish(LogRecord record) {
    Formatter actualFormatter = formatter;
    if (actualFormatter != null) {
        String message = actualFormatter.format(record); 
        notification.sendNotification(
            new JMXLogRecordNotification(
                objectName,
                sequenceNumber++, 
                record.getMillis(),
                message,
                record
            )
        );
    }
}
Logging.java 文件源码 项目:sequence-mining 阅读 37 收藏 0 点赞 0 评论 0
/** Set up console handler */
public static Handler setUpConsoleHandler() {
    final ConsoleHandler handler = new ConsoleHandler() {
        @Override
        protected void setOutputStream(final OutputStream out) throws SecurityException {
            super.setOutputStream(System.out);
        }
    };
    handler.setLevel(Level.ALL);
    final Formatter formatter = new Formatter() {
        @Override
        public String format(final LogRecord record) {
            return record.getMessage();
        }
    };
    handler.setFormatter(formatter);
    return handler;
}
Test.java 文件源码 项目:bisdk 阅读 30 收藏 0 点赞 0 评论 0
private static void initLog()
{
    Formatter simpleFormatter;

    try
    {
        String path = new File(".").getCanonicalPath();
        String logName = String.valueOf(System.currentTimeMillis());
        simpleFormatter = new SimpleFormatter();
        fileHandler = new FileHandler(path + logName + ".log");
        fileHandler.setFormatter(simpleFormatter);
        fileHandler.setLevel(Level.ALL);
    }
    catch (IOException e)
    {
        errorLog.log(Level.WARNING, e.getMessage(), e);
    }
}
SimpleTomEEFormatterTest.java 文件源码 项目:tomee 阅读 25 收藏 0 点赞 0 评论 0
@Test
public void formatNullThrown() throws Exception {
    final String previousLineSeparatorProperty = System.getProperty(LINE_SEPARATOR_KEY);
    try {
        final String lineSeparatorValue = "\n";
        final String logMessage = "An example log record";
        final Level level = Level.FINEST;

        System.setProperty(LINE_SEPARATOR_KEY, lineSeparatorValue);
        final LogRecord logRecordInput = new LogRecord(level, logMessage);
        logRecordInput.setThrown(null);

        final Formatter formatter = new SimpleTomEEFormatter();
        final String actualFormatOutput = formatter.format(logRecordInput);

        final String expectedFormatOutput = level.getLocalizedName() + " - " + logMessage + "\n";

        assertEquals(expectedFormatOutput, actualFormatOutput);
    } finally {
        System.setProperty(LINE_SEPARATOR_KEY, previousLineSeparatorProperty);
    }
}
SimpleTomEEFormatterTest.java 文件源码 项目:tomee 阅读 27 收藏 0 点赞 0 评论 0
@Test
public void formatNotNullThrown() throws Exception {
    final String previousLineSeparatorProperty = System.getProperty(LINE_SEPARATOR_KEY);

    try {
        final String lineSeparatorValue = "\n";
        final String logMessage = "An example log record";
        final Level level = Level.CONFIG;
        final String exceptionMessage = "An example exception";
        final Throwable thrown = new Exception(exceptionMessage);

        System.setProperty(LINE_SEPARATOR_KEY, lineSeparatorValue);
        final LogRecord logRecordInput = new LogRecord(level, logMessage);
        logRecordInput.setThrown(thrown);

        final Formatter formatter = new SimpleTomEEFormatter();
        final String actualFormatOutput = formatter.format(logRecordInput);

        final String expectedFormatOutput = level.getLocalizedName() + " - " + logMessage + lineSeparatorValue + ExceptionUtils.getStackTrace(thrown);

        assertEquals(expectedFormatOutput, actualFormatOutput);
    } finally {
        System.setProperty(LINE_SEPARATOR_KEY, previousLineSeparatorProperty);
    }
}
SESLogFormatter.java 文件源码 项目:SES 阅读 28 收藏 0 点赞 0 评论 0
/**
 * 
 * @param args the
 */
public static void main(String[] args) {
    Logger logger = Logger.getLogger("test");
    logger.info("test");

    logger.addHandler(new ConsoleHandler());
    logger.info("tes");

    Formatter f = new SESLogFormatter("prefix");

    Handler[] handlers = logger.getHandlers();
    Handler handler;

    logger.info("" + handlers.length);
    for (int i = 0; i < handlers.length; i++) {
        handler = handlers[i];
        handler.setFormatter(f);
    }

    logger.info("test2");
}
LocalFileHandler.java 文件源码 项目:enviroCar-app 阅读 31 收藏 0 点赞 0 评论 0
@SuppressLint("SimpleDateFormat")
protected FileHandler createHandler(String finalPath) throws IOException {
    FileHandler h = new FileHandler(finalPath, MAX_SIZE, 3, true);

    final DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    final String sep = System.getProperty("line.separator");

    h.setFormatter(new Formatter() {

        @Override
        public String format(LogRecord r) {
            String date = format.format(new Date(r.getMillis()));
            return String.format(Locale.US, "%s [%s]: (%d) %s%s", date, r.getLevel(), r.getThreadID(), r.getMessage(), sep);
        }

    });

    h.setLevel(Level.ALL);
    return h;
}
LogFormatterTest.java 文件源码 项目:incubator-netbeans 阅读 32 收藏 0 点赞 0 评论 0
public void testFormatterDoesNotIncludeHashOnEditor() throws ClassNotFoundException {
    LogRecord r = new LogRecord(Level.INFO, "EDIT");
    JEditorPane ep = new javax.swing.JEditorPane();
    ep.setName("SomeName");
    r.setParameters(new Object[] { ep });
    Formatter formatter = new LogFormatter();
    String s = formatter.format(r);
    assertEquals("No @\n" + s, -1, s.indexOf("@"));
    if (s.indexOf("SomeName") == -1) {
        fail("SomeName should be there:\n" + s);
    }
}
DispatchingHandlerTest.java 文件源码 项目:incubator-netbeans 阅读 40 收藏 0 点赞 0 评论 0
public void testOwnFormatter() throws UnsupportedEncodingException {
    class MyFrmtr extends Formatter {
        private int cnt;
        @Override
        public String format(LogRecord record) {
            cnt++;
            return record.getMessage();
        }
    }
    MyFrmtr my = new MyFrmtr();

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    StreamHandler sh = new StreamHandler(os, NbFormatter.FORMATTER);
    DispatchingHandler dh = new DispatchingHandler(sh, 10);
    dh.setFormatter(my);
    dh.publish(new LogRecord(Level.WARNING, "Ahoj"));
    dh.flush();
    String res = new String(os.toByteArray(), "UTF-8");
    assertEquals("Only the message is written", "Ahoj", res);
    assertEquals("Called once", 1, my.cnt);
}
TracingMetricRegistry.java 文件源码 项目:JInsight 阅读 27 收藏 0 点赞 0 评论 0
private static Logger createMetricUpdateTracer() {
  Logger logger = Logger.getLogger(TracingMetricRegistry.class.getName() + ".metricUpdates");
  ConsoleHandler handler = new ConsoleHandler();
  handler.setFormatter(new Formatter() {
    @Override
    public String format(LogRecord record) {
      return ">>" + record.getMessage() + "\n";
    }
  });
  logger.addHandler(handler);
  logger.setUseParentHandlers(false);
  handler.setLevel(Level.ALL);
  //logger.setLevel(Level.ALL);

  return logger;
}
AbstractProcessorWithLogging.java 文件源码 项目:jtsgen 阅读 26 收藏 0 点赞 0 评论 0
@Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        final Optional<String> jtsgenLogLevel = Optional.ofNullable(processingEnv.getOptions().get("jtsgenLogLevel"));
        String packageName = AbstractProcessorWithLogging.class.getPackage().getName();
        final Logger logger = Logger.getLogger(packageName);
        if (jtsgenLogLevel.isPresent()) {
            Level level = jtsgenLogLevel
                    .map(
                            (x) -> {
                                try {
                                    return Level.parse(x.trim().toUpperCase());
                                } catch (IllegalArgumentException ex) {
                                    return Level.OFF;
                                }
                            }
                    ).orElse(Level.INFO);
            Formatter oneLineFormatter = new OneLineFormatter();
            ConsoleHandler consoleHandler = new ConsoleHandler();
            consoleHandler.setLevel(level);
            consoleHandler.setFormatter(oneLineFormatter);
            logger.setUseParentHandlers(false);
            logger.setLevel(level);

//        consoleHandler.setFormatter(oneLineFormatter);
            logger.addHandler(consoleHandler);
            LOG.log(Level.FINER,() -> String.format("LogLevel %s = %s ", packageName, level.getName()));
        } else {
            logger.setLevel(Level.OFF);
        }
    }
SystemLogger.java 文件源码 项目:uavstack 阅读 32 收藏 0 点赞 0 评论 0
private SystemLogger(String name, String rootpath, String logFilePattern, int logBufferSize, int fileSizeLimit,
        int fileCountLimit, boolean append, Formatter format) {

    this.filePattern = logFilePattern;
    this.fileSizeLimit = fileSizeLimit;
    this.fileCountLimit = fileCountLimit;
    this.logBufferSize = logBufferSize;
    this.shouldAppend = append;

    log = new PLogger(name);
    log.enableConsoleOut(true);
    log.setLogLevel(LogLevel.INFO);

    this.logRoot = rootpath + "/logs";

    if (!IOHelper.exists(logRoot)) {
        IOHelper.createFolder(logRoot);
    }

    log.enableFileOut(this.logRoot + "/" + this.filePattern, true, this.logBufferSize, this.fileSizeLimit,
            this.fileCountLimit, this.shouldAppend, format);
}
AppSetup.java 文件源码 项目:scorekeeperfrontend 阅读 30 收藏 0 点赞 0 评论 0
/**
 * Do some common setup for all applications at startup
 * @param name the application name used for Java logging and database logging
 */
public static void appSetup(String name)
{
    // Set our platform wide L&F 
    System.setProperty("swing.defaultlaf", "javax.swing.plaf.nimbus.NimbusLookAndFeel");
    UIDefaults defaults = UIManager.getLookAndFeelDefaults();
    defaults.put("Table.gridColor", new Color(140,140,140));
    defaults.put("Table.showGrid", true);

    // Set the program name which is used by PostgresqlDatabase to identify the app in logs
    System.setProperty("program.name", name);

    // Start with a fresh root set at warning
    Logger root = LogManager.getLogManager().getLogger("");
    Formatter format = new SingleLineFormatter();

    root.setLevel(Level.WARNING);
    for(Handler handler : root.getHandlers()) {
        root.removeHandler(handler);
    }

    // Set prefs levels before windows preference load barfs useless data on the user
    Logger.getLogger("java.util.prefs").setLevel(Level.SEVERE);
    // postgres JDBC spits out a lot of data even though we catch the exception
    Logger.getLogger("org.postgresql.jdbc").setLevel(Level.OFF);
    Logger.getLogger("org.postgresql.Driver").setLevel(Level.OFF);

    // Add console handler if running in debug mode
    if (Prefs.isDebug()) {
        ConsoleHandler ch = new ConsoleHandler();
        ch.setLevel(Level.ALL);
        ch.setFormatter(format);
        root.addHandler(ch);
    }

    // For our own logs, we can set super fine level or info depending on if debug mode and attach dialogs to those
    Logger applog = Logger.getLogger("org.wwscc");
    applog.setLevel(Prefs.isDebug() ? Level.FINEST : Level.INFO);
    applog.addHandler(new AlertHandler());

    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            applog.log(Level.WARNING, String.format("\bUncaughtException in %s: %s", t, e), e);
        }});

    try {
        File logdir = Prefs.getLogDirectory().toFile();
        if (!logdir.exists())
            if (!logdir.mkdirs())
                throw new IOException("Can't create log directory " + logdir);
        FileHandler fh = new FileHandler(new File(logdir, name+".%g.log").getAbsolutePath(), 1000000, 10, true);
        fh.setFormatter(format);
        fh.setLevel(Level.ALL);
        root.addHandler(fh);
    } catch (IOException ioe) {
        JOptionPane.showMessageDialog(FocusManager.getCurrentManager().getActiveWindow(),
                "Unable to enable logging to file: " + ioe, "Log Error", JOptionPane.ERROR_MESSAGE);
    }

    // force the initialization of IdGenerator on another thread so app can start now without an odd delay later
    new Thread() {
        public void run() {
            IdGenerator.generateId();
        }
    }.start();
}
ColorLogFormatter.java 文件源码 项目:ColorConsole 阅读 26 收藏 0 点赞 0 评论 0
public ColorLogFormatter(ColorConsoleBungee plugin, Formatter oldFormatter) {
    this.plugin = plugin;
    this.oldFormatter = oldFormatter;

    List<String> ignoreMessages = plugin.getConfiguration().getStringList("hide-messages");
    boolean colorizeTag = plugin.getConfiguration().getBoolean("colorPluginTag");
    boolean truncateColor = plugin.getConfiguration().getBoolean("truncateColor", false);

    Map<String, String> levelColors = Maps.newHashMap();
    if (plugin.getConfiguration().getBoolean("colorMessage", false)) {
        levelColors.put("FATAL", plugin.getConfiguration().getString("FATAL"));
        levelColors.put("ERROR", plugin.getConfiguration().getString("ERROR"));
        levelColors.put("WARN", plugin.getConfiguration().getString("WARN"));
        levelColors.put("DEBUG", plugin.getConfiguration().getString("DEBUG"));
        levelColors.put("TRACE", plugin.getConfiguration().getString("TRACE"));
    }

    this.formatter = new CommonFormatter(ignoreMessages, colorizeTag, truncateColor, levelColors);
}
EntryPoint.java 文件源码 项目:THUTag 阅读 27 收藏 0 点赞 0 评论 0
public static void setLogFormat() {
  Logger root = Logger.getLogger("");
  Handler [] handlers = root.getHandlers();  // returns 1

  for (int i = 0; i < handlers.length; i++) {
    if (handlers[i] instanceof ConsoleHandler) {
      ((ConsoleHandler)handlers[i])
          .setFormatter(new Formatter() {
            public SimpleDateFormat format =
              new SimpleDateFormat("yy/MM/dd HH:mm:ss");

            public String format(LogRecord record) {
              Date d = new Date(record.getMillis());
              return format.format(d) + " " + record.getMessage()  + "\n";
            }

          });
    }
  }

}
TestServer.java 文件源码 项目:ExilePearl 阅读 34 收藏 0 点赞 0 评论 0
public void configureLogger(boolean useLogger) {
    if (this.useLogger != useLogger && logger != null) {
        return;
    }
    this.useLogger = useLogger;

    if (useLogger) {
        logger = Logger.getLogger(serverName);
    } else {
        logger = Mockito.mock(Logger.class);
        return;
    }

// Format the logger output
Formatter formatter = new Formatter() {
    private final DateFormat df = new SimpleDateFormat("hh:mm:ss");
    @Override
    public String format(LogRecord record) {
        String level = record.getLevel().getLocalizedName().toUpperCase();
        if (level.equals("WARNING")) {
            level = "WARN";
        }

        Throwable thrown = record.getThrown();
        if (thrown != null) {
            thrown.printStackTrace();
        }

        return String.format("[%s %s]: %s\n", df.format(new Date(record.getMillis())), level, formatMessage(record));
    }
};

logger.setUseParentHandlers(false);
ConsoleHandler handler = new ConsoleHandler();
      handler.setFormatter(formatter);
      logger.addHandler(handler);
  }
LogBasedFileLog.java 文件源码 项目:icedtea-web 阅读 28 收藏 0 点赞 0 评论 0
public LogBasedFileLog(String loggerName, String fileName, boolean append) {
    try {
        File futureFile = new File(fileName);
        if (!futureFile.exists()) {
            FileUtils.createRestrictedFile(futureFile, true);
        }
        fh = new FileHandler(fileName, append);
        fh.setFormatter(new Formatter() {
            @Override
            public String format(LogRecord record) {
                return record.getMessage() + "\n";
            }
        });
        impl = Logger.getLogger(loggerName);
        impl.setLevel(Level.ALL);
        impl.addHandler(fh);
        log(FileLog.getHeadlineHeader().toString() + " log-based impl.");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Tester.java 文件源码 项目:VarJ 阅读 29 收藏 0 点赞 0 评论 0
public static void main(String[] args)
{
    if (args.length < 1) {
        System.err.println("usage: java backend.logging.Tester <verbosity level>");
        System.exit(1);
    }
    int vlevel = Integer.parseInt(args[0]);
    Level level = VarLogger.getLogLevel(vlevel);
    Formatter formatter = VarLogger.canHandleColor() ?
        new RenameLevelFormatter(
            RenameLevelFormatter.ColorNameStrategy.getInstance())
        : new SimpleFormatter();
    Logger LOG = new VarLogger.FormatterBuilder()
                     .formatter(formatter)
                     .level(level)
                     .build()
                     .getLogger();
   System.out.println("Log level: " + LOG.getLevel());
    LOG.log(ERROR, "A error message;");
    LOG.log(INFO,  "An info message;");
    LOG.log(DEBUG, "A debug message;");
}
MailHandler.java 文件源码 项目:kore-javamail 阅读 29 收藏 0 点赞 0 评论 0
/**
 * Sets the attachment <tt>Formatter</tt> object for this handler.
 * The number of formatters determines the number of attachments per
 * email.  This method should be the first attachment method called.
 * To remove all attachments, call this method with empty array.
 * @param formatters a non null array of formatters.
 * @throws SecurityException  if a security manager exists and the
 * caller does not have <tt>LoggingPermission("control")</tt>.
 * @throws NullPointerException if the given array or any array index is
 * <tt>null</tt>.
 * @throws IllegalStateException if called from inside a push.
 */
public final void setAttachmentFormatters(Formatter... formatters) {
    checkAccess();
    if (formatters.length == 0) { //Null check and length check.
        formatters = emptyFormatterArray();
    } else {
        formatters = copyOf(formatters,
                formatters.length, Formatter[].class);
        for (int i = 0; i < formatters.length; ++i) {
            if (formatters[i] == null) {
                throw new NullPointerException(atIndexMsg(i));
            }
        }
    }

    synchronized (this) {
        if (isWriting) {
            throw new IllegalStateException();
        }

        this.attachmentFormatters = formatters;
        this.fixUpAttachmentFilters();
        this.fixUpAttachmentNames();
    }
}
MailHandler.java 文件源码 项目:kore-javamail 阅读 30 收藏 0 点赞 0 评论 0
/**
 * Sets the attachment file name formatters.  The format method of each
 * attachment formatter will see only the <tt>LogRecord</tt> objects that
 * passed its attachment filter during formatting. The format method will
 * typically return an empty string. Instead of being used to format
 * records, it is used to gather information about the contents of an
 * attachment.  The <tt>getTail</tt> method should be used to construct the
 * attachment file name and reset any formatter collected state.  The
 * formatter must ensure that the attachment file name does not contain any
 * line breaks.  The <tt>toString</tt> method of the given formatter should
 * be overridden to provide a useful attachment file name, if possible.
 * @param formatters and array of attachment name formatters.
 * @throws SecurityException  if a security manager exists and the
 * caller does not have <tt>LoggingPermission("control")</tt>.
 * @throws IndexOutOfBoundsException if the number of attachment
 * name formatters do not match the number of attachment formatters.
 * @throws NullPointerException if any given array or name is <tt>null</tt>.
 * @throws IllegalStateException if called from inside a push.
 * @see Character#isISOControl(char)
 * @see Character#isISOControl(int)
 */
public final void setAttachmentNames(Formatter... formatters) {
    checkAccess();

    formatters = copyOf(formatters, formatters.length, Formatter[].class);
    for (int i = 0; i < formatters.length; ++i) {
        if (formatters[i] == null) {
            throw new NullPointerException(atIndexMsg(i));
        }
    }

    synchronized (this) {
        if (this.attachmentFormatters.length != formatters.length) {
            throw attachmentMismatch(this.attachmentFormatters.length, formatters.length);
        }

        if (isWriting) {
            throw new IllegalStateException();
        }

        this.attachmentNames = formatters;
    }
}
MailHandler.java 文件源码 项目:kore-javamail 阅读 32 收藏 0 点赞 0 评论 0
/**
 * Creates the formatted log record or reports a formatting error.
 * @param f the formatter.
 * @param r the log record.
 * @return the formatted string or an empty string.
 */
private String format(final Formatter f, final LogRecord r) {
    try {
        return f.format(r);
    } catch (final RuntimeException RE) {
        reportError(RE.getMessage(), RE, ErrorManager.FORMAT_FAILURE);
        return "";
    }
}
CollectorFormatter.java 文件源码 项目:kore-javamail 阅读 28 收藏 0 点赞 0 评论 0
/**
 * Gets and creates the formatter from the LogManager or creates the default
 * formatter.
 *
 * @param p the class name prefix.
 * @return the formatter.
 * @throws UndeclaredThrowableException if the formatter can not be created.
 */
private Formatter initFormatter(final String p) {
    final LogManager m = LogManagerProperties.getLogManager();
    Formatter f;
    String v = m.getProperty(p.concat(".formatter"));
    if (v != null && v.length() != 0) {
        if (!"null".equalsIgnoreCase(v)) {
            try {
                f = LogManagerProperties.newFormatter(v);
            } catch (final RuntimeException re) {
                throw re;
            } catch (final Exception e) {
                throw new UndeclaredThrowableException(e);
            }
        } else {
            f = null;
        }
    } else {
        //Don't force the byte code verifier to load the formatter.
        f = Formatter.class.cast(new CompactFormatter());
    }
    return f;
}
BaseRunner.java 文件源码 项目:openwonderland 阅读 33 收藏 0 点赞 0 评论 0
/**
 * Get a log handler that should be used to write the log out to
 * the log file.
 * @return the handler to use
 */
protected Handler getLogFileHandler() throws IOException {
    logFileHandler = new FileHandler(getLogFile().getCanonicalPath());
    logFileHandler.setLevel(Level.ALL);
    logFileHandler.setFormatter(new Formatter() {
        @Override
        public String format(LogRecord record) {
            return record.getMessage() + "\n";
        }
    });

    return logFileHandler;
}
LogCtr.java 文件源码 项目:lBackup 阅读 41 收藏 0 点赞 0 评论 0
/**
 * 
 */
public LogCtr() {
    logger = Logger.getLogger("lbackup");  

    try{
        fh = new FileHandler(PATH_LOG, true);  
        logger.addHandler(fh);
        //SimpleFormatter formatter = new SimpleFormatter();  
        fh.setFormatter(new Formatter() {

            @Override
            public String format(LogRecord r) {
                Date date = new Date();
                date.setTime(r.getMillis());
                SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");


                return "[" + dateFormat.format(date) + "] " + r.getMessage() + "\r\n";
            }
        });

    }catch(Exception e){
        e.printStackTrace();
    }

}
JDKLogger.java 文件源码 项目:fax4j 阅读 24 收藏 0 点赞 0 评论 0
/**
 * This function initializes and returns the logger.
 * 
 * @return  The logger
 */
protected static final Logger initializeLogger()
{
    //get logger
    Logger logger=Logger.getLogger(FaxClient.class.getName());

    //enable all log events (fax4j logger filters out uneeded log events)
    logger.setLevel(Level.ALL);
    logger.setFilter(null);

    //enable to pass log events to parent loggers
    logger.setUseParentHandlers(true);

    //create handler
    Formatter formatter=new SimpleFormatter();
    Handler handler=new StreamHandler(System.out,formatter);

    //set filtering
    handler.setLevel(logger.getLevel());
    handler.setFilter(logger.getFilter());

    //add handler
    logger.addHandler(handler);

    return logger;
}
SocketHandler.java 文件源码 项目:wildfly-logstash 阅读 32 收藏 0 点赞 0 评论 0
private String createFormattedMessage(final ExtLogRecord record) {
  final Formatter formatter = getFormatter();
  try {
    return formatter.format(record);
  } catch (Exception e) {
    reportError("Could not format message", e, ErrorManager.FORMAT_FAILURE);
    return null;
  }
}
DataDownload.java 文件源码 项目:daris 阅读 32 收藏 0 点赞 0 评论 0
public static Logger createLogger() {

        Logger logger = Logger.getLogger(APP_NAME);
        logger.setLevel(Level.ALL);
        logger.setUseParentHandlers(false);
        /*
         * add file handler
         */
        try {
            FileHandler fileHandler = new FileHandler("%t/" + APP_NAME + ".%g.log", 5000000, 2);
            fileHandler.setLevel(Level.ALL);
            fileHandler.setFormatter(new Formatter() {

                @Override
                public String format(LogRecord record) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(new Date(record.getMillis())).append(" ");
                    sb.append("[thread: ").append(record.getThreadID()).append("] ");
                    sb.append(record.getLevel().getName()).append(" ");
                    sb.append(record.getMessage());
                    sb.append("\n");
                    return sb.toString();
                }
            });
            logger.addHandler(fileHandler);
        } catch (Throwable e) {
            System.err.println("Warning: failed to create daris-download.*.log file in system temporary directory.");
            e.printStackTrace(System.err);
            return null;
        }
        return logger;
    }
LogManagerHelper.java 文件源码 项目:syslog-java-client 阅读 30 收藏 0 点赞 0 评论 0
/**
 * Visible version of {@link java.util.logging.LogManager#getFormatterProperty(String, java.util.logging.Formatter)} .
 *
 * We return an instance of the class named by the "name" property.
 *
 * If the property is not defined or has problems we return the defaultValue.
 */
public static Formatter getFormatterProperty(@Nonnull LogManager manager, @Nullable String name, @Nullable Formatter defaultValue) {
    String val = manager.getProperty(name);
    try {
        if (val != null) {
            Class clz = ClassLoader.getSystemClassLoader().loadClass(val);
            return (Formatter) clz.newInstance();
        }
    } catch (Exception ex) {
        // We got one of a variety of exceptions in creating the
        // class or creating an instance.
        // Drop through.
    }
    // We got an exception.  Return the defaultValue.
    return defaultValue;
}
CachingLogHandler.java 文件源码 项目:netarchivesuite-svngit-migration 阅读 28 收藏 0 点赞 0 评论 0
/**
 * Package private method to get a formatter property. We return an instance
 * of the class named by the "name" property. If the property is not defined
 * or has problems we return the defaultValue.
 *
 * This method was copied from java.util.logging.LogManager, where it is
 * package private :-(
 *
 * @param name         The log property name
 * @param defaultValue The formatter if that property is not specified or
 *                     unparsable
 * @return The formatter from the property if set and parsable, the
 *         defaultValue otherwise
 */
@SuppressWarnings("rawtypes")
private Formatter getFormatterProperty(String name,
                                       Formatter defaultValue) {
    String val = LogManager.getLogManager().getProperty(name);
    try {
        if (val != null) {
            Class clz = ClassLoader.getSystemClassLoader().loadClass(val);
            return (Formatter) clz.newInstance();
        }
    } catch (Exception ex) {
        // We got one of a variety of exceptions in creating the
        // class or creating an instance.
        // Drop through.
    }
    // We got an exception.  Return the defaultValue.
    return defaultValue;
}


问题


面经


文章

微信
公众号

扫码关注公众号