简体   繁体   English

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

[英]Java logging through multiple classes

I would like to log in my application which consist of several classes. 我想登录我的应用程序,其中包含几个类。 I would like to have one .txt log file at the end. 我想在最后有一个.txt日志文件。 Therefore I make one static logger instance and I made a FileHandler for it in one class. 因此,我创建了一个静态记录器实例,并在一个类中为它创建了一个FileHandler。 Because I would like to have one file, I set the second argument for true in the FileHandler to be able to append the log file during logging. 因为我想拥有一个文件,所以我在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);

    }

After that, I created the other loggers. 之后,我创建了其他记录器。 I know that I have to instance one logger per class. 我知道我必须为每个类实例一个记录器。 Therefore I only make the logger (w/o FileHandler) for each class. 因此我只为每个类制作记录器(没有FileHandler)。 But all of the loggers referencing for one class (not for the class, where I have created the logger). 但所有的记录器都引用了一个类(不是我创建记录器的类)。 Eg: 例如:

public class Test1 {
    static Logger logger;

    public Test1()throws IOException {

        logger = Logger.getLogger(MyLogging.class.getName());
    }

Although the logging was performed, I am not sure that this is the right solution. 虽然执行了日志记录,但我不确定这是否是正确的解决方案。 Can you give me some advises how to make logging through multiple the classes with the java.util.logging? 你能给我一些建议如何用java.util.logging来记录多个类吗?

In MyLogging class, make the constructor private instead of public , and you need the following methods: 在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);
}

The log method is static, so it can be called from any class using the class name. log方法是静态的,因此可以使用类名从任何类调用它。

So from all your classes, you can log just be invoking log method as below: 因此,从您的所有类中,您可以记录只需调用日志方法,如下所示:

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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM