本文介绍了使用Logger和FileHandler Class of Java.util时,几秒钟后日志文件没有更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下类'LoggerUtil'来记录到控制台和文件'logfile.log'。记录到控制台工作正常。但是,记录到'logfile.log'文件在几个日志后停止。任何有关查找错误的建议都会受到欢迎。我附上以下代码:

I am using the following Class 'LoggerUtil' for logging to console and to a file 'logfile.log'. The logging to console is working fine. However, logging to 'logfile.log' file stops after few logs. Any suggestions in locating the bug would be welcome. I am attaching the code below:

public class LoggerUtil {   
  public static final String LOGGERNAME = "project.logging";

  static {
      try {
          Logger.getLogger(LOGGERNAME).setUseParentHandlers(false);
          Handler ch = new ConsoleHandler();
          Handler fh = new FileHandler("logfile.log");
          SimpleFormatter sf = new SimpleFormatter();
          fh.setFormatter(sf);
          Logger.getLogger(LOGGERNAME).addHandler(ch);
          Logger.getLogger(LOGGERNAME).addHandler(fh);
          setHandlersLevel(Level.ALL);
      } catch (IOException | SecurityException ex) {
          Logger.getLogger(LoggerUtil.class.getName()).log(Level.SEVERE, null, ex);
      }
  }

  public static void setHandlersLevel(Level level) {
      Handler[] handlers = Logger.getLogger(LOGGERNAME).getHandlers();
      for (Handler h : handlers) {
          h.setLevel(level);
      }
      Logger.getLogger(LOGGERNAME).setLevel(level);
  }

  public static Logger getLogger() {
      return Logger.getLogger(LOGGERNAME);
  }
}

我从项目中的不同位置调用以下代码记录:

I call the following code from various places in my project to log:

LoggerUtil.getLogger().log(Level.INFO, "Message to be logged");

请注意,我的项目是多线程的。各种线程使用相同的文件进行日志记录。这可能是一个并发问题,还是只是一个红鲱鱼!

Kindly note, my project is multithreaded. Various threads use the same file for logging. Could this be a concurrency issue or is that just a red herring!

推荐答案

对您的记录器进行硬性引用。经验法则是在类中使用静态最终字段。

Make a hard reference to your logger. Rule of thumb is to use a static final field in your class.

public static final String LOGGERNAME = "project.logging";
//Pin logger in memory.
private static final Logger logger = Logger.getLogger(LOGGERNAME);

来自Logger。文档:

From the Logger.getLogger(String) documentation:

当记录器被垃圾收集时,您的ConsoleHandler和FileHandler不会重新连接到新的记录器。

When the logger is garbage collected your ConsoleHandler and FileHandler are not reattached to the new logger.

使用FindBugs因为它检测到这个:

Use FindBugs because it detects this bug pattern:

这篇关于使用Logger和FileHandler Class of Java.util时,几秒钟后日志文件没有更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 15:53