如何使用Simple Formatter修改日志格式?

时间:2018-03-09 03:13:08

标签: java logging formatter java.util.logging

我已尝试将此行添加到logging.properties中,但输出不会更改

java.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'

我也尝试过System.setProperty,但它仍然不起作用,我做错了什么?

import java.util.*;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.io.*;
import java.awt.*;

public class LoggerFormat
{
private static final Logger logger = Logger.getLogger(LoggerFormat.class.getName());

public static void main(String[] args)
{
    System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tF %1$tT %4$s %2$s %1$tL");
    SimpleFormatter sf = new SimpleFormatter();
    System.out.println("-- main method starts --");
    logger.info("in LoggerFormat");
    logger.warning("a test warning");
}
}

2 个答案:

答案 0 :(得分:1)

这里可能会出现一些问题。首先确保您运行的是已修复JDK-6381464 : SimpleFormatter should use one single line format的Java版本(7 b138)。

文档中未解释的一件事是,如果您是setting the pattern via the command line并且模式包含空白字符,则仅需要在模式上引用。

因此,如果您在logging.properties中设置格式,则删除引号:

java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n

如果要将格式设置为系统属性,则必须在启动时设置:

-Djava.util.logging.SimpleFormatter.format="%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n"

您要做的下一件事是使用测试程序来验证您的模式是否已编译。如果模式语法错误,SimpleFormatter将回退到默认模式。这是一个示例测试程序:

public static void main(String[] args) throws Exception {
    final String format = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n";
    final String key = "java.util.logging.SimpleFormatter.format";
    test(format);
    test(System.getProperty(key, format));
    test(LogManager.getLogManager().getProperty(key));
    test(new SimpleFormatter());
}

private static void test(Formatter f) {
    LogRecord record = newLogRecord();
    System.out.println(f.format(record));
}

private static LogRecord newLogRecord() {
    LogRecord r = new LogRecord(Level.INFO, "Message");
    r.setSourceClassName("sourceClassName");
    r.setSourceMethodName("sourceMethodName");
    r.setLoggerName("loggerName");
    return r;
}

private static void test(String format) {
    if (format != null) {
        LogRecord record = newLogRecord();
        Throwable t = record.getThrown();
        System.out.println(String.format(format,
                new java.util.Date(record.getMillis()),
                record.getSourceClassName(),
                record.getLoggerName(),
                record.getLevel().getLocalizedName(),
                record.getMessage(),
                t != null ? t.toString() : ""));
        //TODO: Place printStackTrace into a string.
    } else {
        System.out.println("Format is null.");
    }
}

最后,格式只能在启动时设置一次。加载SimpleFormatter后,该模式将用于该类的生命周期。使用System.setProperty仅在您开始记录之前设置模式时才有效,因此不依赖于在复杂程序中工作的路由。

答案 1 :(得分:0)

https://logging.apache.org/log4j/2.0/manual/messages.html请参阅此内容。有很好的扩展