Why do loggers recommend using a logger per class?
With log4net, using one logger per class makes it easy to capture the source of the log message (ie. the class writing to the log). If you don't have one logger per class, but instead have one logger for the entire app, you need to resort to more reflection tricks to know where the log messages are coming from.
Compare the following:
Log per class
using System.Reflection;
private static readonly ILog _logger =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public void SomeMethod()
{
_logger.DebugFormat("File not found: {0}", _filename);
}
One logger per app (or similar)
Logger.DebugFormat("File not found: {0}", _filename); // Logger determines caller
-- or --
Logger.DebugFormat(this, "File not found: {0}", _filename); // Pass in the caller
Using the second example, the Logger would need to build a stack trace to see who was calling it or your code would always have to pass in the caller. With the logger-per-class style, you still do this, but you can do it once per class instead of once per call and eliminate a serious performance problem.
Advantage for using "logger per file" in NLog: you have possibility to manage/filter logs by namespace and class name. Example:
<logger name="A.NameSpace.MyClass" minlevel="Debug" writeTo="ImportantLogs" />
<logger name="A.NameSpace.MyOtherClass" minlevel="Trace" writeTo="ImportantLogs" />
<logger name="StupidLibrary.*" minlevel="Error" writeTo="StupidLibraryLogs" />
<!-- Hide other messages from StupidLibrary -->
<logger name="StupidLibrary.*" final="true" />
<!-- Log all but hidden messages -->
<logger name="*" writeTo="AllLogs" />
NLogger has a very useful code snippet to do this. The nlogger
snippet will create the following code:
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
So only few keystrokes and you have logger per class. It will use namespace and class name as the name of the logger. To set different name to your class logger, you can use this:
private static NLog.Logger logger = NLog.LogManager.GetLogger("MyLib.MyName");
And, as @JeremyWiebe said, you don't have to use tricks to get the name of the class which is trying to log a message: Name of the logger (which is usually the name of the class) can be easy logged to file (or other target) by using ${logger}
in layout.