如何将java.util.logging重定向到文件? [英] How to redirect java.util.logging to a file?
问题描述
我有一个使用外部库的java程序。主程序使用 log4j
来记录其消息,库使用 java.util.logging
。
I have a java program using an external library. The main program uses log4j
to log its messages and the library uses java.util.logging
.
我的问题是来自外部库和主程序的日志消息在控制台中混合。
My problem is that log messages from the external library and the main program are mixed in the console.
我想重定向所有将外部库中的消息记录到文件中。我尝试使用 logging.properties
文件来执行此操作:
I would like to redirect all log messages from the external library to a file. I tried to do that with a logging.properties
file:
handlers= java.util.logging.FileHandler
.level= INFO
java.util.logging.FileHandler.pattern = foo.log
java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter
此文件初始化为:
System.setProperty("java.util.logging.config.file", "logging.properties");
不幸的是,来自外部库的日志消息一直出现在控制台中。
我应该使用类似 slf4j
的内容拦截来自 java.util.logging
的日志消息吗?
Unfortunately, log messages from the external library keep appearing in the console.
Should I use something like slf4j
to intercept log messages from java.util.logging
?
感谢您的时间。
推荐答案
以下是我的一些代码程式。这也可以自动旋转。配置类是我自己的,从属性文件中读取。你可以用你自己的值替换它。
Here's some code from one of my programs. This also does automatic rotation. The config class is my own that's read from a properties files. You can just replace that with your own values.
Logger rootLogger = Logger.getLogger("");
logHandler = new FileHandler(config.getLogFile(),
config.getLogRotateSize()*1024*1024,
config.getLogRotateCount(), false);
logHandler.setFormatter(new SimpleFormatter());
logHandler.setLevel(Level.INFO);
rootLogger.removeHandler(rootLogger.getHandlers()[0]);
rootLogger.setLevel(Level.INFO);
rootLogger.addHandler(logHandler);
注意这是一个独立的程序。任何应用程序服务器都有自己的日志记录配置工具。如果需要动态调试模式,程序还可以动态更改格式化程序和级别。
Note this is for a stand-alone program. Any application server has it's own logging configuration tools. The program can also change the formatter and levels on the fly if a dynamic debug mode is desired.
这篇关于如何将java.util.logging重定向到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!