C# – log4net – roll the own singleton, use LogImpl, etC

cnet

Reposting here… hopefully the better place to seek opinions on the matter. 🙂

Writing my own log4net wrapper class using C#. I want to create a lib such that I can reference it from any project/assembly in a given solution with a minimum of effort. ie: include the reference, maybe throw in a using statement and then make calls like MyLogger.Debug(blahblah); with perhaps a property (MyLogger) being set from a "main" method somewhere.

From reading the docs, I'm not sure if I should be writing my own or using LogImpl? The latter seems to include all of what I'd want to put in my own wrapper, so, why reinvent the wheel? But, there is also a note in the help that says thast an instance member of type logimpl is not thread safe whereas a static member is…

OTOH, if I make my own, I'd be looking at a singleton class I can create once and use throughout my solution (by passing the singleton ref to objects which require it) but I gotta rewrite all those Debug, Error, etc sections.

So… not sure what approach to take. What would you folks suggest as a beginning?

Best Answer

Generally singletons are considered bad:

...if you still feel the need to use Singleton objects, consider using the Factory Method pattern instead. It gives you all of the flexibility of the Singleton, with nowhere near as many problems.

...and you're supposed to inject the logger implementation into any class that uses it (or inject a logger factory if you only want the logger object to exist for as long as your class is using it), so:

interface IMyLogger
{
    void Log(string whatever);
}

class MyClass
{
    private readonly IMyLogger logger;

    public(IMyLogger logger)
    {
        if(logger == null) throw new ArgumentNullException("logger");
        this.logger = logger;
    }

    void someOtherMethod()
    {
        this.logger.Log("Something");
    }
}

This allows you to inject various different logger implementations. If you decide to go the shortcut route and use a Singleton, and then use the built-in one from log4net then you're pretty much coupling every class that uses it directly to your implementation, which is generally a bad idea.

Related Topic