Brian's Waste of Time

Wed, 26 Sep 2007

Logging for Libraries

A pet peeve of mine for a long time has been how many libraries handle logging. There are general two techniques:

  1. Don't log
  2. Use [commons-logging|log4r|printf|syslog|slf4j]

Both suck.

In the first case you cannot get info out. In the second case the library is deciding how you will get the info out. The first one is okay for anything that can never go wrong. I'm sure you can think of something in that category. For everything else, you frequently need to see what is going wrong -- or at least figure out why what you are giving it is garbage.

For a library, then, logging is a feature. This is where most folks whip out commons-logging, log4perl, or whatever. Bzzzz. You just added a dependency and dictated that users figure out how to make use of that logging system. The much better way is to expose logging via callbacks and provide concrete instances of the common cases.

An example might look like:

foo.setLogger(new FooLogger() {
    public void log(int level, String msg) {
        System.err.printf("%s\n",msg);
    }
})

Which is boring, but you know, covers 98% of the cases where you want logging in a library. To cover the common cases:

foo.setLogger(new PrintStreamLogger(System.err));
    ...
foo.setLogger(new Log4jLogger(Wombat.class));

This is the runtime-configured-slf4j-per-project approach. It seems kinda gnarly until you use the library and things just magically work they way you want. Any dependency on external logging is specifically selected by users, or they can do their own thing.

8 writebacks [/src] permanent link