tags:

views:

313

answers:

4

I'm using java.util.logging.Logger logging in my program. How do I enable FINE logging for a single class, while setting it to WARNING for every other class?

I'd prefer to do this programatically in my main() method rather than needing to set up additional properties files.

+1  A: 
Logger log = Logger.getLogger(this.getClass().getName()).setLevel(Level.FINE);
stevedbrown
That's close, but doesn't work for two reasons:1) I want to be able to put the the code in my main class, so not all users of my utility class have to see the FINE logging.2) It seems that even if I do what you suggested the handler is still swallowing all my FINE messages.
A: 

I believe that you can set your log level for your Handler and your specific class Logger to FINE, while keeping all the other Loggers for the rest of your code base to WARNING should do the trick. Both the Logger and the Handler need to pass the level filter for a message to be logged.

akf
A: 

If you do not want to have a logger defined for every single class in question but rather want to share loggers between classes, you can alternatively implement your own java.util.logging.Handler that has its own way of filtering for class names using the information provided by LogRecord.getSourceClassName().

A: 

Well, here's a method I added to my mail class that's actually working. I would still welcome any improvements from others.

private static void setupLogging() {
  // To enable FINE logging in a single class, apparently this bewildering
  // maze of statements is required.
  Logger.getLogger("").setLevel(Level.FINE);
  for (Handler handler : Logger.getLogger("").getHandlers()) {
    handler.setLevel(Level.FINE);
  }
  MyOtherClass.logger.setLevel(Level.FINE);
  Logger.getLogger("").setLevel(Level.WARNING);
}