views:

283

answers:

1

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?)

+6  A: 

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.

Boris Pavlović
don't you need to override toString() ?
Jason S
has been overriden, thank you
Boris Pavlović
Delegating to log4j requires extra work to ensure that source file and line numbers are correct.
James A. N. Stauffer
Thanks for your reply - it looks nice, but I don't I'll use it. It adds an extra layer to log4j (MyLogger implementation and its factory), which is difficult to enforce developers to use, without adding much benefits. We might use your Error definition and define an ObjectRenderer for it,
runec
but I believe I'll rather look for som tool that can scan source code during nightly builds and reports issues such as this.
runec