Java日志记录没有记录所有类?

时间:2015-10-11 18:00:05

标签: java logging

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

这是我的记录器类

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

这是我的格式化程序类

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

的代码中添加了以下内容
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的文件没有出现(我认为数据会记录在同一个文件中,即使这样也不会发生)

我尝试将其记录在一个完全独立的文件中:

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

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

1 个答案:

答案 0 :(得分:1)

以下是MyLogger类的更正版本。请参阅下文。

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()方法中进行了注释,并且首先如果检查是从参数化的classLogger方法中注释掉的,因为setup()方法具有相关检查,因此不需要复制它们。仍需要一点努力才能在记录器类中进行更改,例如路径与旧路径相同,然后使用现有的FileHandler等。

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