Design question: do I use (AOP, IoC, ?) for access to Logger?

Discussions

Web tier: servlets, JSP, Web frameworks: Design question: do I use (AOP, IoC, ?) for access to Logger?

  1. I'm trying to learn and see the benefits of IoC and AOP.

    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:
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;

    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:
    setLog(Log);
    getLog();

    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.

    Fred
  2. 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.Fred

    Hey Frederic, you should take another look at AOP, especially introduction :). This is exactly their purpose!

    Introduction: Adding methods or fields to an advised class. Spring allows you to introduce new interfaces to any advised object. For example, you could use an introduction to make any object implement an IsModified interface, to simplify caching.
  3. Hi Alexandre,

    I looked into Introduction form of Spring AOP, and that's exactly what I'm looking for. Many thanks for the tip :)

    Frederic