How to set up logging with NLog in a .NET project
March 1st, 2014Logging is quite useful, and one popular tool for .Net logging is log4net. Another really nice tool is NLog. Here’s how to implement logging and configure NLog for your website in a few steps.
NLog can target lots of types including files, database, e-mail and Windows Event Log. This example demonstrates how to configure NLog to store the logging output to the Windows Event Log.
First you need to install NLog. The easiest way is to install the NuGet package simply called “NLog”, and if you don’t want to create your own configuration file you could also install “NLog Configuration” which installs an empty NLog.config file to your project. Otherwise you have to create the file “NLog.config” in your webroot.
Edit the properties of the NLog.config file and change Copy To Output Directory value to “Copy Always“.
If you want to target the Event Log, you need to register the application as a source by starting Powershell as administrator and run the command (where “MyAppNameHere” should be a unique name which represents your application):
New-EventLog -LogName Application -Source MyAppNameHere
Here is an example of the content of an NLog.config file, which logs to the event log:
1 2 3 4 5 6 7 8 9 10 11 12 | <?xml version="1.0"?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwExceptions="true"> <targets> <target xsi:type="EventLog" name="eventlog" layout="${callsite:className=true:includeSourcePath=true:methodName=true:fileName=true}:${newline}${message}${newline}${newline}${exception:format=type,message,method:maxInnerExceptionLevel=5:innerFormat=shortType,message,method}" log="Application" source="MyAppNameHere"/> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="eventLog" /> </rules> </nlog> |
How to implement logging in a class, in this example named “MyClass”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | using NLog; private static readonly Logger Logger = LogManager.GetLogger(typeof(MyClass).Name); ... catch (Exception ex) { if (Logger.IsErrorEnabled) { Logger.ErrorException("All your base are belong to us!", ex); // or just log the error message: Logger.Error("You have no chance to survive make your time."); // or log with another level: Logger.Info("Somebody set up us the bomb."); } } |
To see the logged messages from your application in the event log, open Event Viewer, go to Windows Logs -> Application. A tip is to filter the log using the “Filter Current Log” in the Actions tab and selecting your application source name (which you also reference in the config file) so you only see relevant logs.