如何使用Java本机Logger?

时间:2014-10-08 07:32:54

标签: java logging java.util.logging

如何在没有外部库(即log4j)的情况下使用java.util.Logger类并将日志打印在文件中?我想从属性文件中使用记录器的格式化程序和参数。

1 个答案:

答案 0 :(得分:0)

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.LogManager;

public class LoggerConfiguration {

    private static final LogManager logManager = LogManager.getLogManager();

    /*
     * Java static block always loads before constructors
     */
    static {
        try {
            InputStream inputStream = 
                ClassLoader.class.getResourceAsStream("/logger.properties");

            logManager.readConfiguration(inputStream);

        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }
}

logger.properties文件示例内容

.level=ALL
java.util.logging.ConsoleHandler.level=ALL
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
confLogger.level=ALL

java.util.logging.FileHandler.pattern=%h/my-application%u.log
java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter

handlers=java.util.logging.ConsoleHandler,java.util.logging.FileHandler 

使用记录器的示例类:

import java.util.logging.Logger;

public class ExampleClass {

    private final static Logger LOG = Logger.getLogger(ExampleClass.class.getName());

    public static void main(String args[]) {
        LOG.info("an info message");

        new ExampleClass();
    }

    public ExampleClass() {
        LOG.info("one more message"); 
    }
}