How to use log4net with Dependency Injection

I think you’re not seeing the forest for the trees here. ILog and LogManager are a lightweight façade almost 1:1 equivalent to Apache commons-logging, and do not actually couple your code to the remainder of log4net.

<rant>
I’ve also found that almost always when someone creates a MyCompanyLogger wrapper around log4net they miss the point badly and will either lose important and useful capabilities of the framework, throw away useful information, lose the performance gains possible using even the simplified ILog interface, or all of the above. In other words, wrapping log4net to avoid coupling to it is an anti-pattern.
</rant>

If you feel the need to inject it, make your logger instance accessible via a property to enable injection but create a default instance the old-fashioned way.

As for including contextual state in every log message, you need to add a global property whose ToString() resolves to what you’re looking for. As an example, for the current heap size:

public class TotalMemoryProperty
{
    public override string ToString()
    {
        return GC.GetTotalMemory(false).ToString();
    }
}

Then to plug it in during startup:

GlobalContext.Properties["TotalMemory"] = new TotalMemoryProperty();

Leave a Comment