Java – log4j extra logging arguments

javalog4jlogging

I'm developing a (internal) library where I want to enforce that developers using this lihrary include a text ID when logging error or fatal level messages. Without modifying log4j, what we want to enforce is similar to:

logger.error( "E1234:An error has occured" );

With none or minor extension to log4j we could either, during nightly builds, scan the source code to verify that the text ID is included, or implement a log4j appender that verifies it during runtime.

What we would like, however, is to add an extra argument to the error-method. E.g.:

logger.error( "E1234", "An error has occured" );

This could be handled by implementing some facade class for the log4j Logger class.

Have anyone else had similar issue? What was your solution? For now, we prefer the first code example. In the future we might implement the code analyzer to execute during nightly builds (or do anyone know about some existing code analyzer that can be configured to detect a missing text ID from an error() method call?)

Best Answer

Avoid compound keys like this: "E1234:An error has occured"

I would use

public enum Error {
 E1234("E1234", "An error has occured"),
 E1245("E1235", "Other error has occured"),
 private final String code;
 private final String description;
 Error(code, description) {
   this.code;
   this.description = description
 }
 @Override
 public String toString() {
   return this.code + ": " + this.description;
 }
}

Then, you can create your own interface with methods which accept an Error:

public interface MyLogger {
 void error(Error);
 void info(Error);
 void warn(Error);
 void debug(Error);
}

Then implement it and delegate to log4j real logging job. This will help your developer avoiding problems.