使用 Java.util 的 Logger 和 FileHandler 类时,几秒钟后未更新日志文件 [英] Log File not being updated after few seconds while using Logger and 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!
推荐答案
硬引用您的记录器.经验法则是在类中使用静态 final 字段.
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);
来自记录器.getLogger(String) 文档:
注意:LogManager 可能只保留对新创建的 Logger 的弱引用.重要的是要了解,如果没有对 Logger 的强引用,先前创建的具有给定名称的 Logger 可能会随时被垃圾回收.
Note: The LogManager may only retain a weak reference to the newly created Logger. It is important to understand that a previously created Logger with the given name may be garbage collected at any time if there is no strong reference to the Logger.
当记录器被垃圾收集时,您的 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:
LG:由于 OpenJDK 中的弱引用,记录器更改可能丢失 (LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE)
LG: Potential lost logger changes due to weak reference in OpenJDK (LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE)
这篇关于使用 Java.util 的 Logger 和 FileHandler 类时,几秒钟后未更新日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!