Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 207
gulbrandr Avatar asked Nov 27 '10 16:11

gulbrandr


1 Answers

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.

like image 127
JOTN Avatar answered Oct 02 '22 13:10

JOTN