Using java.util.logging to log on the console
Asked Answered
F

3

26

I want simply to log on the console using java.util.Logging:

Logger log = Logger.getLogger("my.logger");
log.setLevel(Level.ALL);
ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter(new SimpleFormatter());
log.addHandler(handler);
log.fine("hello world");

but this prints out nothing. What am I missing?

Thanks

Free answered 8/2, 2012 at 18:52 Comment(0)
C
33

Very simple, a logger can have several handlers, with each a different level.

handler.setLevel(Level.ALL);
Colostrum answered 8/2, 2012 at 19:5 Comment(4)
Which begs the question: just what is the purpose of Logger.setLevel(), if it doesn't set the levels?Divinity
The ConsoleHandler starts with level INFO. The levels are combined. My personal opinion is that the logging API does not provide an algebra, a sensible set of combinable operations with well defined semantics.Colostrum
the logger is used inside the class, may also be configurated by the class. the handler may be set globally. so you might have different handlers, for output to console and/or file. you definetly have different loggers, e.g. for each class.Gatefold
@kewlbfy right: one picks a specific logger for usage, and then one dispatch to plural handlers, like for file, console, email, ticket system or whatever.Colostrum
F
12

Logging on the standard System.out stream could be easily done by adding a StreamHandler handler:

logger.addHandler(new StreamHandler(System.out, new SimpleFormatter()))
Fissi answered 18/3, 2016 at 10:21 Comment(0)
D
9

I'm no expert on java logging, but if you change log.fine() to log.info() it will print. There's something fishy about fine - in practice, I never used it. Hopefully somebody who knows more can answer that.

ADDED: Yes, fine is special. I found an earlier SO answer for this:

Divinity answered 8/2, 2012 at 19:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.