Every time I make a file new project I need to add logging – how many times have I spent time figuring out what needs to go where, how to format the error email, and how to log uncaught errors(oh noes!). Too many times. So here is me condensing adding NLog to a web project quickly and easily:
Install NLog.config(and with it NLog) on your web project.
Add these to NLog.config:
<targets> <target name="Mail" xsi:type="Mail" html="true" subject="Error Received" layout="${longdate} LEVEL=${uppercase:${level}}, LOCATION=${callsite:className=true:includeSourcePath=true:methodName=true}, MESSAGE=${message}${newline} EXCEPTION=${exception:format=tostring,StackTrace}${newline" addNewLines="true" replaceNewlineWithBrTagInHtml="true" to="[email protected]" from="[email protected]" useSystemNetMailSettings="true" > </targets> <rules> <logger name="*" level="Error" writeTo="Mail" > <logger name="*" level="Fatal" writeTo="Mail" > </rules>
Add this to global.asax.cs
protected void Application_Error() { Exception lastException = Server.GetLastError(); Logger logger = LogManager.GetCurrentClassLogger(); logger.Fatal(lastException); }
There is some feature interaction with how you handle your errors, to get things working you may need to temporarily change customErrors mode to Off in web.config(but this should never go to production!)