This morning I thought of something that could be improved in my code: access to a Logger for ad-hoc logging.
Right now, if I want to log some random message (for example, for debugging), I have to add the following:
private static final Log log = LogFactory.getLog(MyClass.class);
log.debug("id = " + id);
There has to be a better way.
Ideally, when all is said and done, if I want to log something in a class, I'd like to be able to do it using just this:
getLog().debug("id = " + id);
I could have an abstract base class that contains the instance of the log, and have my classes extend that class, but this is extremely limiting since most of my classes have their own hierarchy and logging does not belong in that hierarchy!
I know there has to be an elegant way to do this. Something along the lines of "injecting" a Logger automatically. So have a class that implements:
and have the logger injected by the container. Then, the class just uses getLog() to retrieve it. However again I run into the problem: how do I achieve this without having every class have to extend a base class, nor having to repeat the same code of those methods? Is there a way I can have them be "decorated" with a logger without them "knowing" it, and obtain the logger only if needed?
I'm thinking something with Spring perhaps.. which I have yet to learn. But again I wouldn't have to repeat some kind of configuration for each of my classes in some XML file..
As for AOP, as I understand it, it does things e.g. before and after each method invocation, and that's not what I'm looking for here. I want specific ad-hoc logging, not generalized logging across the whole application.
Any suggestions? I'd appreciate it! Thanks in advance.