我需要为 websphere 应用程序服务器 9 上安装和运行的每个应用程序生成一个日志文件。 我使用 JUL 来生成日志文件。我的解决方案是创建一个继承自 FileHandler 的特定类,并通过配置文件设置日志属性。
这是我的代码:
//Read config file
LogManager.getLogManager().readConfiguration(LoggerJUL.class.getResourceAsStream("/Logger.properties"));
//Add handler to logger
Logger.getLogger(clazz)).addHandler(new PersonalFileHandler());
PersonalFileHandler 扩展了 FileHandler,并且属性由运行时 FileHandler 类上的 configure 方法设置。
通过这种方式,我可以通过在 Websphere 上运行的应用程序创建一个日志文件,而无需覆盖服务器日志的目标。
虽然我实现了部分目标,但如果原始日志文件被锁定,则会生成额外的文件,如下所示:testLogs.log.0、testLogs.log.1、testLogs.log.0.1等。 我读了很多建议和解决方案,但我无法阻止这个问题。 有什么建议吗?
handlers = com.mucam.xxxx.PersonalFileHandler
# Set the default formatter to be the simple formatter
com.mucam.xxxx.PersonalFileHandler.formatter = java.util.logging.SimpleFormatter
# Write the log files to some file pattern
com.mucam.xxxx.PersonalFileHandler.pattern = C:/Users/pmendez/Documents/Log/testLogs.log
# Limit log file size to 5 Kb
com.mucam.xxxx.PersonalFileHandler.limit = 5000
# Keep 10 log files
com.mucam.xxxx.PersonalFileHandler.count = 10
#Customize the SimpleFormatter output format
java.util.logging.SimpleFormatter.format = %d{ISO8601} [%t] %-5p %c %x - %m%n
#Append to existing file
com.mucam.xxxx.PersonalFileHandler.append = true
最佳答案
Although I achieve part of the objective, extra files are generated if the original log file is locked, same like this: testLogs.log.0, testLogs.log.1, testLogs.log.0.1, etc. I read many suggestions and solutions, but i can't stop this isue. Any suggestions ?
由于您的计数设置为 10,因此您需要指定 %g
模式来记录生成。
com.mucam.xxxx.PersonalFileHandler.pattern = C:/Users/pmendez/Documents/Log/testLogs%g.log
该模式是绝对路径,因此如果您创建多个文件处理程序,它将 resolve conflicts通过在末尾附加唯一编号。这是由 %u
模式指定的。因此,如果您想移动文件名中整数的位置,请在模式中指定 %u
标记。
这也意味着您正在创建自定义文件处理程序的多个实例,并且它们不会被关闭。如果你想控制文件的数量,你要么需要控制你创建的 PersonalFileHandler 的数量,要么共享对单例 PersonalFileHandler 的引用。否则,您需要确保,如果显式创建 PersonalFileHandler,则在创建第二个新的 PersonalFileHandler 之前显式关闭该 PersonalFileHandler。
Loggers are subject to garbage collection 。该行:
Logger.getLogger(clazz).addHandler(new PersonalFileHandler());
除非其他地方的代码已经将该记录器固定在内存中,否则会受到垃圾收集的影响。这可能会导致日志文件被创建、锁定和清空。
关于java - 当原始日志被锁定时,FileHandler 会生成额外的日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57695437/