How to redirect java.util.logging to a file?

对着背影说爱祢 提交于 2019-12-04 23:27:19

问题


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.

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

This file is initialized with:

System.setProperty("java.util.logging.config.file", "logging.properties");

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?

Thank you for your time.


回答1:


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.



来源:https://stackoverflow.com/questions/4292599/how-to-redirect-java-util-logging-to-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!