Java通过多个类进行日志记录 [英] Java logging through multiple classes

查看:208
本文介绍了Java通过多个类进行日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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. Therefore I make one static logger instance and I made a FileHandler for it in one class. 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.

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);

    }

之后,我创建了其他记录器.我知道我必须为每个类实例一个记录器.因此,我只为每个类制作记录器(不带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. But all of the loggers referencing for one class (not for the class, where I have created the logger). E.g:

public class Test1 {
    static Logger logger;

    public Test1()throws IOException {

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

尽管已执行日志记录,但是我不确定这是否是正确的解决方案. 您能给我一些建议,如何使用java.util.logging通过多个类进行记录吗?

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?

推荐答案

在MyLogging类中,使构造函数private代替public,并且需要以下方法:

In MyLogging class, make the constructor private instead of public , and you need the following methods:

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);
}

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

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
    }

这篇关于Java通过多个类进行日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆