Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate INFO and ERROR logs from java.util.logging

Tags:

java

logging

I'm configuring the logging for a Java application. What I'm aiming for is two logs: one for all messages and one for just messages above a certain level.

The app uses the java.util.logging.* classes: I'm using it as is, so I'm limited to configuration through a logging.properties file.

I don't see a way to configure two FileHandlers differently: the docs and examples I've seen set properties like:

java.util.logging.FileHandler.level = INFO

While I want two different Handlers logging at different levels to different files.

Any suggestions?

like image 326
user63196 Avatar asked Feb 06 '09 05:02

user63196


People also ask

What is difference between Java util logging and Log4j?

Java Util Logging performance is significantly affected by the lack of a buffered handler. There is no major difference between Log4j and Logback. Both Log4j and Logback show about 50% of the performance of my special case optimized strawman.

What is Java Util logging?

java. util. logging. LogManager is the class that reads the logging configuration, create and maintains the logger instances. We can use this class to set our own application specific configuration.

What is difference between log and logger in Java?

The call to LogFactory. getLog() is from the commons-logging api. log4j is a logging framework, i.e. it provides the code to log messages. Commons-logging is an abstraction layer for logging frameworks, it doesn't log anything itself.


1 Answers

http://java.sun.com/j2se/1.4.2/docs/guide/util/logging/overview.html is helpful. You can only set one Level for any individual logger (as you can tell from the setLevel() method on the logger). However, you can take the lowest of the two common levels, and then filter programmatically.

Unfortunately, you can't do this just with the configuration file. To switch with just the configuration file you would have to switch to something like log4j, which you've said isn't an option.

So I would suggest altering the logging in code, with Filters, with something like this:

class LevelFilter implements Filter {
    private Level Level;
    public LevelFilter(Level level) {
        this.level = level;
    }
    public boolean isLoggable(LogRecord record) {
        return level.intValue() < record.getLevel().intValue();
    }
}

And then on the second handler, do setFilter(new LevelFilter(Level.INFO)) or whatever. If you want it file configurable you could use a logging properties setting you've made up yourself, and use the normal Properties methods.

I think the configuration code for setting up the two file handlers ad the programmatic code is fairly simple once you have the design, but if you want more detail add a comment and I'll edit.

like image 55
Nick Fortescue Avatar answered Oct 13 '22 15:10

Nick Fortescue