Reputation: 1677
My goal is to use java.util.logging(jdk1.6)
I had configured a root logger and several named logger, where
root logger's handler set to java.util.logging.FileHandler
with settings
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.FileHandler.pattern = xxx.%u.log
java.util.logging.FileHandler.limit = 200000
java.util.logging.FileHandler.count = 20
java.util.logging.FileHandler.append = true
and named loggers' handler set to customFileH
with customized settings
customFileH.class = java.util.logging.FileHandler
customFileH.level = ALL
customFileH.formatter = xxxFormat
When I run the program, the root logger will write log to xxx.0.log,
while named logger will write log to xxx.0.log.1, as different log files.
Even I took out "%u" in file pattern; remark file rotation configs, did them write to different log files. :(
Thanks for any comment in advance. :)
Upvotes: 1
Views: 1024
Reputation: 11045
Looks like you are trying to apply log4j style configuration to java.util.logging. If you want to create multiple FileHandlers with different formatters then you have to use the config option to install each FileHandler. Create a config class:
package so;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.XMLFormatter;
public final class LoggingConfig {
/**
* Pin the loggers.
*/
private static final Logger root = Logger.getLogger("");
private static final Logger named = Logger.getLogger("some.name");
/**
* Configure the loggers.
* @throws Exception if there is a problem.
*/
public LoggingConfig() throws Exception {
root.addHandler(newRootHandler());
named.addHandler(newNamedHandler());
}
private FileHandler newRootHandler() throws IOException {
FileHandler f = new FileHandler("simple%g.%u.log", 200000, 20, true);
f.setFormatter(new SimpleFormatter());
return f;
}
private FileHandler newNamedHandler() throws IOException {
FileHandler f = new FileHandler("xml%g.%u.log", 200000, 20, true);
f.setFormatter(new XMLFormatter());
return f;
}
}
Then add the following to your logging.properties:
config=so.LoggingConfig
Otherwise, you can subclass FileHandler just to create a new class name that can be used in your logging.properties.
You have to use the %g option to distinguish rotated logs and %u to deal with conflicts. From the FileHandler documentation:
Thus if three processes were all trying to log to fred%u.%g.txt then they might end up using fred0.0.txt, fred1.0.txt, fred2.0.txt as the first file in their rotating sequences.
By default all of the named loggers will write to the handlers of the root logger. So depending on what you are doing you may not need to attach file handlers to the named loggers.
Upvotes: 1