Log exception information using Nlog
First refer to the Nlog DLL file, modify the configuration file, under configuration under the Configsections node, configure the Nlog associated configuration section for example < Name= "Nlog" type= "NLog.Config.ConfigSectionHandler, nlog" /> , Configure the Nlog log output path configuration under the configuration node
<Nlogxmlns= "Http://www.nlog-project.org/schemas/NLog.xsd"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"> <Targets> <Targetname= "FileLog"type= "File"FileName= "${basedir}/log/${shortdate}/${level}.txt"Layout= "" ${date:format=yyyy-mm-dd hh\:mm\:ss} "" ${level} "${message} ${exception}" /> </Targets> <rules> <Loggername="*"MinLevel= "Debug"WriteTo= "FileLog" /> </rules> </Nlog>
Create a new property that inherits from Handleerrorattribute, which handles exceptions with the following code
Public classCustomerexceptionattribute:handleerrorattribute {/// <summary> ///Exception Handling/// </summary> /// <param name= "Filtercontext" ></param> Public Override voidonexception (Exceptioncontext filtercontext) {NLog.LogManager.GetCurrentClassLogger (). Error (filtercontext.exception); Base. Onexception (Filtercontext); FilterContext.HttpContext.Response.Redirect (""); } }
Add the attribute where you want to handle the exception
[customerexception] public actionresult Index () { int0 ; int 3 / A; return View (); }
MVC Exception Handling