log4net strategy on named loggers?

log4net, logging

Solution

I basically use

public class MyClass
{
    private static readonly ILog log = Log.Get<MyClass>();
}

where Log.Get is a class that basically does this internally

return LogManager.GetLogger(typeof(T));

The startup cost is even smaller than the reflection way as well as cleaner imo.

Update: given my experience in later years with dependency injection, unit testing and fakes, I can no longer say that I condone the approach outlined above. The problem with the approach (both mine and that of the OP) is that the code have explicit knowledge about how the log instance is created.

One one side, this increased coupling makes it harder to test: there is no easy way of replacing the `ILog` instance with a fake one. On another side, changes made to my `Log` class will cause changes to ripple throughout all classes that uses it.

I therefore go the route of injecting the `ILog` instance, usually via constructor injection, and outsource the how to construct a logger to my DI framework of choice:

public class MyClass
{
    readonly ILog _log;

    public class MyClass(ILog log)
    {
        _log = log;
    }
}

This allows for proper decoupling. The code no longer need to know how loggers are constructed. Most dependency injection frameworks have means of looking at the type being injected and then using that to construct the log instance. Here's an approach for log4net and Autofac.

Problem

I typically declare the following in every class: ``` private static readonly log4net.ILog log = log4net.LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); ``` and use the static member within each class to log at different levels (info, debug, etc.) I saw that somewhere and have been using it somewhat mindlessly, reasoning that the setup is flexible enough to help me filter by namespace and log individual types if I wanted to in troubleshooting production issues and what not. But I've rarely had to use that "level" of fine logging. So, I would like to see what others are using. Do you use the above, as I have a feeling many are using just that, or do you create named loggers such as "debug", "trace", "error", "moduleA", etc. and share the logger among different types, assemblies?

Original source

Related problems