As per NLog's documentation:
Most applications will use one logger per class, where the name of the logger is the same as the name of the class.
This is the same way that log4net operates. Why is this a good practice?
As per NLog's documentation:
Most applications will use one logger per class, where the name of the logger is the same as the name of the class.
This is the same way that log4net operates. Why is this a good practice?
In most cases, the name of the class provides a good name for the logger. When scanning the log files, you can see the log message and associate it directly with a line of code.
A good example where this is not the best approach, is Hibernate's SQL logs. There is a shared logger named "Hibernate.SQL" or something like that, where a number of different classes write raw SQL out to a single logger category.
Advantage for using "logger per file" in NLog: you have possibility to manage/filter logs by namespace and class name. Example:
NLogger has a very useful code snippet to do this. The
nlogger
snippet will create the following code: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:
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.If you are using NLOG you can specify the callsite in the config, this will record the class name and method where the logging statement was located.
You could then use a constant for your logger name or the assembly name.
Disclaimer: I don't know how NLOG collects this information, my guess would be reflection so you may need to consider the performance. There are a few issues with Async methods if you are not using NLOG v4.4 or later.
I can see a few reasons for this choice.
Makes it easy to configure appenders by namespace or class.
There is also a performance benefit in the case of NLog. Most users will use
Looking up the current class from stack trace take some (but not much) performance.