Search code examples
javaapachejunitlogfactory

During a unit test how can I log all output to the console instead of logfiles


Originally titled: How can I get Apache LogFactory to always return the same log implementation?

I have a project that uses quite a few different loggers configured to go to different places. When I'm running a unit test, I want to override them all with a SimpleLogger that I instantiate myself. How can I set this into LogFactory so that it's always returned for unit tests?

I'd really rather not deal with an external configuration file.

As a little bit of background, I find loggers notorously untrustworthy. It's not really the logger exactly, it's that there are so many ways to configure it and filter the output--it can be done from various config files or anywhere in code, and then it could go out to a variety of locations. The logger can even send some kind of output (errors) to different locations from others based on the configuration.

Although this can be quite awesome and powerful, it's all undone when you spend 6 hours wondering why your code isn't being called when it actually IS being called but your output is being redirected.

When running tests I want to be as sure as possible that I'm seeing all the output, so I want to redirect ALL logs to the console. (All, as in my current project can create a couple dozen different logfiles spread across 6 directories.)


Solution

  • I finally figured out a way to do this.

    You can extend LogFactory with your own factory--overriding both getInstance methods to return your logger (apparently all the other methods can be empty) . I used SimpleLogger to divirt all logging to the console:

    public Log getInstance(String name) throws LogConfigurationException {
        // If this weren't just for testing I'd keep a map of these loggers instead...
        SimpleLog consoleLogger=new SimpleLog(name);
        consoleLogger.setLevel(SimpleLog.LOG_LEVEL_ALL);
        return consoleLogger;
    }
    public Log getInstance(Class className) throws LogConfigurationException {
        return getInstance(arg0.getName());
    }
    

    then install it with a static method inside this class:

    public static void initialize() {
        System.setProperty(LogFactory.FACTORY_PROPERTY, MyLogFactory.class.getName());
    }
    

    this confines the entire log re-router to one class, if you call initialize() at the beginning of a test, all log output for the session is re-routed to the console. Don't call it later or the code you are testing may have already called the "Normal" factory and cached the real logger.