Java日志记录不是所有类的日志记录? [英] Java logging not logging for all classes?

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

问题描述

我正在尝试在Java中进行一些日志记录(我使用的是Java本身提供的日志而不是log4j),这是我的代码:

I am trying to do some logging in java(I am using the one provided by java itself not log4j), here is my code :

这是我的 logger类:

public class MyLogger {

    static MyFormatter formatter = null;
    static FileHandler fileHandler = null;
    static ConsoleHandler consoleHandler = null;
    static String preName = "";
    static Long time = System.currentTimeMillis();
    static String file_path = "/Users/rs/Documents/asl_v1/"+preName+time+".log";

    // setup method
    static public void setup() throws SecurityException, IOException {
        if(fileHandler == null)
            fileHandler = new FileHandler(file_path,true);
        if(consoleHandler == null)
            consoleHandler = new ConsoleHandler();
        if(formatter == null)
            formatter = new MyFormatter();  
        }

    static public Logger classLogger(String className){
        Logger logger = Logger.getLogger(className);
        logger.setUseParentHandlers(false);
        if(fileHandler == null || consoleHandler == null || formatter == null)
            try {
                setup();
                fileHandler.setFormatter(formatter);
                consoleHandler.setFormatter(formatter);
                Handler[] handlers = logger.getHandlers();
                // array of registered handlers
                for (int i = 0; i < handlers.length; i++)
                    logger.removeHandler(handlers[i]);

                logger.setLevel(Level.INFO);
                logger.addHandler(fileHandler);

            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        return logger;
    }

    static public Logger classLogger(String className,
            String log_prefix) {
        preName = log_prefix;
        file_path = "/Users/rs/Documents/asl_v1/"+preName+time+".log";
        return classLogger(className);
    }

这是我的 formatter类:

public class MyFormatter extends Formatter {

    @Override
    public String format(LogRecord record) {
        // TODO Auto-generated method stub
        StringBuilder r = new StringBuilder();
        r.append("<")
            .append(record.getMillis())
            .append(">")
            .append(" ")
            .append(record.getSourceClassName())
            .append(" ")
            .append(record.getSourceMethodName())
            .append(" ")
            .append(record.getThreadID())
            .append(" ")
            .append(record.getLevel())
            .append(" ")
            .append(record.getMessage())
            .append(System
            .getProperty("line.separator"));

            return r.toString();
    }



}

我在我的代码中添加了 MakeClient类:

I have added the following in my code in class MakeClient :

public final static Logger logger = MyLogger.classLogger(MakeClientsClass.class.getName(),"client-");
logger.info("Beginning experiment");

ClientInstance 中的这段代码:

public final static Logger logger = MyLogger.classLogger(ClientThreadInstance.class.getName());
logger.info("Client with id ::"+client_id);

MakeClient的日志文件看起来很好,但是ClientInstance的文件没有出现(我很难保证数据会记录在同一文件中,即使那样也不会发生)

The log file for MakeClient appears just fine, but the file for ClientInstance doesnt appear(I tought the data would be logged in the same file,even that does not happen)

我试图将其记录在我做过的完全独立的文件中:

I tried to log it in a totally separate file i did:

  public final static Logger logger = MyLogger.classLogger(ClientThreadInstance.class.getName(),"client-instance");
    logger.info("Client with id ::"+client_id);

但是根本没有文件出现! 因此记录器适用于MakeClient类,但不适用于其他类!

But there is no file appearing at all! So the logger works for the MakeClient class but not for the other class!!

推荐答案

这是MyLogger类的更正版本.请参见下面.

Here is the corrected version of your MyLogger class. Please see below.

public class MyLogger {

    static MyFormatter formatter = null;
    static FileHandler fileHandler = null;
    static ConsoleHandler consoleHandler = null;
    static String preName = "";
    static Long time = System.currentTimeMillis();
    static String file_path = "/Users/rs/Documents/asl_v1/" + preName + time + ".log";

    // setup method
    static public void setup() throws SecurityException, IOException {
        /*if (fileHandler == null)*/
            fileHandler = new FileHandler(file_path, true);
        if (consoleHandler == null)
            consoleHandler = new ConsoleHandler();
        if (formatter == null)
            formatter = new MyFormatter();
    }

    static public Logger classLogger(String className) {
        Logger logger = Logger.getLogger(className);
        logger.setUseParentHandlers(false);
        /*if (fileHandler == null || consoleHandler == null || formatter == null)*/    
            try {
                setup();
                fileHandler.setFormatter(formatter);

                consoleHandler.setFormatter(formatter);
                Handler[] handlers = logger.getHandlers();

                // array of registered handlers
                for (Handler handler : handlers) {
                   logger.removeHandler(handler);
                }

                logger.setLevel(Level.INFO);
                logger.addHandler(fileHandler);
            } catch (SecurityException | IOException e) {
                e.printStackTrace();
            }

        return logger;
    }

    static public Logger classLogger(String className, String log_prefix) {
        preName = log_prefix;
        file_path = "/Users/rs/Documents/asl_v1/" + preName + time + ".log";
        return classLogger(className);
    }
}

如果在这里看到,您正在为所有类加载相同的FileHandler,因此,当您运行应用程序时,它仅工作一个FileHandler实例.现在,在setup()方法中注释了文件处理程序不是null的检查,而且首先,如果check从参数化的classLogger方法中注释掉了,因为setup()方法具有相关的检查,因此无需重复检查.仍然需要做出一些努力来更改您的logger类,例如,如果路径与旧类相同,则使用现有的FileHandler等.

If you see in here, you are loading the same FileHandler for all of your classes and therefore when you run your application it worked only one instance of FileHandler. Now file handler not null check is commented in setup() method and also first if check is commented it out from parameterized classLogger method since setup() method has relevant checks, so no need to duplicate them. Still it requires a bit effort to make changes in your logger class, like if the path is the same with the old one, then use existing FileHandler, etc..

请考虑在日志记录中使用Factory设计模式,这会使您的代码健壮,流畅且可维护.现在太乱了.

Please consider using Factory design pattern in your logging which makes your code robust, smooth and maintainable. Now it is too messy.

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

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