From Mike Mason's IoC taken too far entry, Mike states that he has a problem with ..

    * A Log4J logger instance - initialized using IoC rather than
    * static logging to cut down on the number of Logger instances
    private final Logger logger;

He is dead right. Logging is not a thing for IoC to handle. Going a tad further, and guaranteed to ignite the wrath of hundreds, I'd say that logging has no place being hard-coded in reusable components. In it's place I'd have a Monitor interface (handed in by Ctor Injector IoC in at least one of the contructors). That monitor interface may well have an implementation that forwarded to Log4J (as well as commons logging, Java 1.4 logging, NullObject logger etc). Anyway the overly simple Log4J logger may look like :-

  class FooBarLog4JMonitor implements FooBarMonitor {
    // this method from the FooBarMonitor interface
    public decentBusinessThingHappened(Class cls, String msg) {
      Logger.getLogger(cls).info("A Decent Business Thing Happened: " + msg);

Lots of room for reimplementation there.

Anyway the main point is the proper way to abstract away logging type and destination is to hide all logging implementation behind an interface. It is not for the component developer to choose Log4J over CommonsLogging (or other). The deployer of an application can then choose to include log4j.jar or other, or none at all if they want. You also get a better hook point for unit testing. That is if you can be bothered as log output is mostly never read, does not affect the running of the machine and thus is of low value and a mistake to spend too much time coding.

blog comments powered by Disqus


April 20th, 2004