Joys of Java Logging

Jan 20, 2017

Searching the internet you’ll find lots of details on slf4j and many of the other logging libraries. They sufficiently drown out the few details available relating to Java logging on Oracles website (aside from API docs). The reason I started shaving this yak is that the default configure in an absence of logger.properties leaves you with an undesirable 2 lines for every record. What I wanted was something more akin to the following:

1
2
3
2017-01-20 14:43:23 INFO com.markelintl.messages.publisher.Pipeline start executing 3 stages
2017-01-20 14:43:23 INFO com.markelintl.messages.publisher.Stage run startup - acme.VendorStage
2017-01-20 14:43:23 INFO com.markelintl.messages.publisher.Stage run startup - acme.MapStage

Ah nice and scanable by the human eye and no external dependencies!

The basic structure I adopted for my little project was as follows:

1
2
3
4
src
    +- main
        +- resources
        +- logger.properties

The contents of my final file which includes the output formatting is:

1
2
3
4
5
6
7
8
9
handlers= java.util.logging.ConsoleHandler
.level= INFO

java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

javax.jms.connection.level = INFO

java.util.logging.SimpleFormatter.format=%1$tF %1$tT %4$s %2$s %5$s%6$s%n

Once you’ve done that you’ll need to wire it into your code thusly:

1
2
3
4
5
6
7
8
9
// loads the log properites
final InputStream is = Thread.currentThread()
                            .getContextClassLoader()
                            .getResourceAsStream("resources/logger.properties");
// retrieves the global log manager
final LogManager manager = LogManager.getLogManager();

// turns up the log sheen to level 10!
manager.readConfiguration(is);

And there you go… nice clean 1 line logs without external depedencies.

tags: [ java ]