Java通过多个类进行日志记录

Joz*_*rab 8 java logging java.util.logging

我想登录我的应用程序,其中包含几个类.我想在最后有一个.txt日志文件.因此,我创建了一个静态记录器实例,并在一个类中为它创建了一个FileHandler.因为我想拥有一个文件,所以我在FileHandler中将第二个参数设置为true,以便能够在日志记录期间附加日志文件.

public class MyLogging {
    static Logger logger;
    public Handler fileHandler;
    Formatter plainText;

    public MyLogging() throws IOException{
        //instance the logger
        logger = Logger.getLogger(MyLogging.class.getName());
        //instance the filehandler
        fileHandler = new FileHandler("myLog.txt",true);
        //instance formatter, set formatting, and handler
        plainText = new SimpleFormatter();
        fileHandler.setFormatter(plainText);
        logger.addHandler(fileHandler);

    }
Run Code Online (Sandbox Code Playgroud)

之后,我创建了其他记录器.我知道我必须为每个类实例一个记录器.因此我只为每个类制作记录器(没有FileHandler).但所有的记录器都引用了一个类(不是我创建记录器的类).例如:

public class Test1 {
    static Logger logger;

    public Test1()throws IOException {

        logger = Logger.getLogger(MyLogging.class.getName());
    }
Run Code Online (Sandbox Code Playgroud)

虽然执行了日志记录,但我不确定这是否是正确的解决方案.你能给我一些建议如何用java.util.logging来记录多个类吗?

Inf*_*ion 7

在MyLogging类中,private不要使用构造函数,而是public需要以下方法:

private static Logger getLogger(){
    if(logger == null){
        try {
            new MyLogging();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return logger;
}
public static void log(Level level, String msg){
    getLogger().log(level, msg);
    System.out.println(msg);
}
Run Code Online (Sandbox Code Playgroud)

log方法是静态的,因此可以使用类名从任何类调用它.

因此,从您的所有类中,您可以记录只需调用日志方法,如下所示:

public class Test1 {
    //static Logger logger; //no need to create an object for logging

    public Test1()throws IOException {

         MyLogging.log(Level.INFO, MyLogging.class.getName()); //call log method using classname
    }
Run Code Online (Sandbox Code Playgroud)