Exceptions require special treatment in NLog. You need to call a Logger method which takes Exception as its second argument. The method names match available log levels:
Typically you call one of these methods in the catch handler:
To write the details of the exception, use the ${exception} layout renderer in
your layout. Depending on the desired output you may want to specify different value for the "format" argument. The
following example displays the result of calling ToString() on the exception object.
]]>
If you can configure logging on the client-side (by providing the appropriate configuration file in application's directory), you can follow the tutorial.
However, if you do not control the clients, or they are not all local, or you wish a solution encapsulated to your component or assembly, you may wish to configure logging locally in your component assembly.
The solution is to create a log manager just for your component that will manage its own loggers. You need to load the configuration file by hand and/or configure logging programmatically but your configuration will be independent from application's config.
The following solution is usable for components not in the GAC. (Components in the GAC need to implement below method GetNLogConfigFilepath in some application-dependent fashion.)
internal class MyLogManager
{
// A Logger dispenser for the current assembly
public static readonly LogFactory Instance
= new LogFactory(new XmlLoggingConfiguration(GetNLogConfigFilePath()));
//
// Use a config file located next to our current assembly dll
// eg, if the running assembly is c:\path\to\MyComponent.dll
// the config filepath will be c:\path\to\MyComponent.nlog
//
// WARNING: This will not be appropriate for assemblies in the GAC
//
private static string GetNLogConfigFilePath()
{
// Use name of current assembly to construct NLog config filename
Assembly thisAssembly = Assembly.GetExecutingAssembly();
return Path.ChangeExtension(thisAssembly.Location, ".nlog");
}
}
Then create loggers with:
Logger logger = MyLogManager.Instance.GetLogger("name");
or
Logger logger = MyLogManager.Instance.GetCurrentClassLogger();
The loggers are independent from the ones created with NLog LogManager, and thus you can have safe private logging. That is, this will not interfere with other assemblies or the application exe itself using NLog.
If you want multiple assemblies to share this MyLogManager - just make it a public class and get others to use it.
You need to make sure that the configuration is properly closed when the process terminates (set MyLogManager.Instance.Configuration to null) or you may lose some log output. You may want to hook AppDomain.ProcessExit and AppDomain.DomainUnload events to turn off logging automatically. See the code of LogManager.cs for details.