Logger for Java library

João Daniel picture João Daniel · Mar 16, 2012 · Viewed 23.8k times · Source

I'm writing a library that gathers various functions that I'll be using in different applications. I want it to generate log statements visible for the user of the library, i.e., if I'm building an application and I'm using the library, I want the library to generate log statements visible to me. How do I do that? Since the log file will be configured by the developer of the application, how will my library know how to log?

Answer

Joe23 picture Joe23 · Mar 16, 2012

If you are developing a library the others will include in their application you should use a logging facade. Otherwise you force the users of your library to configure and include the logging framework you have choosen in addition to the framework they chose for their application.

For instance if you use log4j but the developer using your library uses logback he will have to include a log4j configuration file and the log4j jar (or take other measures) to make your library happy.

Logging Facades solve this problem (from Apache Commons Logging):

When writing a library it is very useful to log information. However there are many logging implementations out there, and a library cannot impose the use of a particular one on the overall application that the library is a part of.

The Logging package is an ultra-thin bridge between different logging implementations. A library that uses the commons-logging API can be used with any logging implementation at runtime. Commons-logging comes with support for a number of popular logging implementations, and writing adapters for others is a reasonably simple task.

Or the reasoning from SLF4J:

The Simple Logging Facade for Java or (SLF4J) serves as a simple facade or abstraction for various logging frameworks, e.g. java.util.logging, log4j and logback, allowing the end user to plug in the desired logging framework at deployment time.

Candidates for logging facades are:

Personally I would recommend SLF4J (with Logback).