Looking a project that uses Common.Logging for .NET, I noticed that some classes declare the logger instance as a class static member. For instance:
public class HelloJob : IJob
{
private static ILog _log = LogManager.GetLogger(typeof(HelloJob));
public HelloJob()
{
}
public virtual void Execute(IJobExecutionContext context)
{
_log.Info(string.Format("Hello World! - {0}", System.DateTime.Now.ToString("r")));
}
}
And in other classes the logger is declared as an instance member:
public class SimpleExample : IExample
{
public virtual void Run()
{
ILog log = LogManager.GetLogger(typeof (SimpleExample));
log.Info("------- Initializing ----------------------");
// etc
}
}
Is there a reason to prefer one approach or the other?
In which cases is each approach recommended? Is it related to thread safety?
Would it be a problem if I just declared a "Logger" class with a static "logger" member and the whole project used that (apart from the issue that I would in practice have a global variable)?
LogManager.GetLogger
is probably internally implemented via dependency injection; that is, the dependency is managed within the logger. I would not want my loggers stored as a "per-instance field" and getting that overhead for each instance created. Statically storing it once when the class is first loaded works for me. – Benumb