I am working on a project, and am currently working on implementing some logging with log4j and I was curious about how I should go about implementing the logs. The two implemen
There are 2 reasons (that I can think of) for having a Logger in the abstract class:
If you prefer static loggers (that's my preferred choice too), then n1cr4m's answer solves #1 and #2 very well.
However, if you're more interested in #2 and dislike the fact, that each concrete class needs to implement getLogger()
, then you could do the following. As an example I'll use a converter:
public abstract class AbstractConverter{
protected void logError(Logger logger, String someId, String msg){
logger.error("Error during conversion of unit \""+ someId + "\": " + msg);
}
}
The logger can be a static logger from a concrete class. Now anytime you log, you will uniformally print the prefix, which also forces the identification of the object it converts.
The drawback of this solution, is that if AbstractConverter
needs to use the logger himself in one of its methods, it wont be able to use the logger from the concrete class, unless you also make this a parameter, which I highly discourage. If you need this kind of functionality, use n1cr4m's solution.