In the Web application running process, we will inevitably encounter the program run exception, this time we should record the exception information, so that developers and maintenance personnel to restore the cause of the exception, the cause of the exception to repair. In the ASP.net platform for logging of the components also have a lot of, such as Log4net, commonlogging, and so on, we choose the log4net for abnormal log records.
1. Catch exceptions
A global exception handling filter is provided in asp.net mvc: Handleerrorattribute, which can be used to capture exception information.
We create a new type Log4exceptionattribute under the Models folder, inherit the Handleerrorattribute class, and override the Onexception method to catch the exception data:
Using SYSTEM.WEB.MVC;
Namespace PMS. Webapp.models
{public
class Log4exceptionattribute:handleerrorattribute
{
///<summary>
///overrides onexception method to catch Exception data
///</summary>
///<param name= "Filtercontext" ></param> Public
override void Onexception (Exceptioncontext filtercontext)
{
base. Onexception (filtercontext);
Capture current exception data
var ex = filtercontext.exception;
}
}
After creating a new filter We also need to complete the registration of our own definition of exception handling filtering in the Registerglobalfilters method called in the global file.
Using SYSTEM.WEB.MVC;
Using PMS. Webapp.models;
Namespace PMS. WEBAPP
{public
class Filterconfig
{public
static void Registerglobalfilters ( Globalfiltercollection filters)
{
//filters. ADD (New Handleerrorattribute ());
Filters. ADD (New Log4exceptionattribute ());}}
2. In view of the problems that may arise when multi-user concurrent operation, we need to create a new queue to carry out the temporary storage of exception information, while opening up a thread to deal with the exception information in the queue.
Create a new static exception type queue in the Log4exceptionattribute class, and when an exception occurs, the program automatically triggers the Onexception method, after which the current exception information is queued and jumps to the error page.
Using System;
Using System.Collections.Generic;
Using SYSTEM.WEB.MVC;
Namespace PMS. Webapp.models
{public
class Log4exceptionattribute:handleerrorattribute
{public
static queue< Exception> exceptions=new queue<exception> ();
<summary>
///rewrite onexception method to catch Exception data
///</summary>
///<param name= "Filtercontext "></param> public
override void Onexception (Exceptioncontext filtercontext)
{
base. Onexception (filtercontext);
Captures the current exception data
var ex = filtercontext.exception;
The exception data is queued to
Exceptions.enqueue (ex);
Jump to error page
filterContext.HttpContext.Response.Redirect ("/error.html");}}
The configuration of the log4net is done in the application configuration file, and we first make the log4net configuration in the configuration file. Log4net need to configure the node location and springnet exactly the same, first need to add a child node in the Configsessions, and then add log4net nodes in the configuration node to complete the specific configuration.
<configuration> <configSections> <section name= "EntityFramework" type= " System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, version=6.0.0.0, Culture=neutral, publickeytoken=b77a5c561934e089 "requirepermission= false"/> <!--for more information on Entity Framework config Uration, visit http://go.microsoft.com/fwlink/? linkid=237468--> <!--↓log4net configuration ↓--> <section name= "Log4net" type=. Config.log4netconfigurationsectionhandler, log4net "/> <!--↑log4net configuration ↑--> <!--↓spring.net configuration ↓--> Sectiongroup name= "Spring" > <section name= "context" type= "Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc4 "/> </sectionGroup> <!--↑spring.net configuration ↑--> </configSections> <!--↓spring. NET configuration ↓--> <spring> <context> <resource uri= "File://~/Config/controllers.xml"/> <resource uri= "File://~/Config/services.xml"/> </context> </spring> <!--↑spring.net configuration ↑--> <!--↓log4net configuration ↓--> <log4net> <!--off, FATAL, ERROR, WAR N, INFO, DEBUG, all--> <!--Set root logger level to ERROR and its appenders--> <root> <level V Alue= ' All '/> <appender-ref ref= ' sysappender '/> </root> <!--Print only messages to Level DEBUG O R above in the packages--> <logger name= "Weblogger" > <level value= "DEBUG"/> </logger> < Appender name= "Sysappender" type= "log4net". Appender.rollingfileappender,log4net "> <param name=" File "value=" app_data/"/> <param-name=" AppendToFil E "value=" true "/> <param name=" Rollingstyle "value=" Date "/>" <param "name=" Datepattern "" value= "yy YyMMdd ". txt" "/> <param name=" Staticlogfilename "value=" false "/> <layout" type=. Layout.patternlayout,log4net "> <param name=" Conversionpattern "value="%d [%t]%-5p%c-%m%n "/>";p Aram Name= "Header" value= "
----------------------Header--------------------------
"/> <param name=" Footer "value="
----------------------Footer-------------------------- "/> </layout> </appender> <appender name=" ConsoleApp "type=" log4net. Appender.consoleappender,log4net "> <layout type=" log4net. Layout.patternlayout,log4net "> <param name=" Conversionpattern "value="%d [%t]%-5p%c-%m%n "/> </layo
Ut> </appender> </log4net> <!--↑log4net configuration ↑--> ... </configuration>
In the configuration file can be recorded in the information, format, file name, etc. to make specific configuration, the following is a detailed configuration information
<?xml version= "1.0"?> <configuration> <configSections> <section name= "log4net" type= "Log4" Net. Config.log4netconfigurationsectionhandler,log4net "/> </configSections> <!--site Log configuration section--> <log4net > <root> <!--control level, from low to High: all| debug|info| warn| error| fatal| Off--> <!--For example, if the definition level is info, then the level of the info level downward, such as the debug log will not be recorded--> <!--if no value is defined for levels, the default is debug--> <level VA Lue= "ERROR"/> <appender-ref ref= "Rollingfileappender"/> </root> <appender name= "Rollingfileappend Er "type=" log4net. Appender.rollingfileappender "> <!--log file name opening--> <file value=" C:\Log\TestLog4net.TXT "/> <!--multiple threads Minimum lock--> <lockingmodel type= "log4net. Appender.fileappender+minimallock "/> <!--date format, a daily change of file records, such as not set will always record a day of the log, you need to set the--> <datepattern value=" ( YYYYMMDD) "/> <!--whether to append to the file, default to True, usually without setting the--> <appendtofile value=" true "/> <!--transform in the form of a date, in which case only one Log--> ≪! --the node settings for maxsizerollbackups and maximumfilesize are meaningless at this time--> <!--<rollingstyle value= "Date"/>--> <!--
The form of a transform is the log size--> <!--the node settings for maxsizerollbackups and maximumfilesize are meaningful in this case--> <rollingstyle value= "Size"/> <!--the number of log files recorded per day, maximumfilesize with--> <maxsizerollbackups value= "ten"/> <!--the maximum size of each log file--> & lt;! --Available units: kb| mb| Gb--> <!--do not use decimals, otherwise it will be written to the current log--> <maximumfilesize value= "2MB"/> <!--log format--> <layout typ E= "Log4net. Layout.patternlayout "> <conversionpattern value="%date [%t]%-5p%c-%m%n]/> </layout> </append
Er> </log4net> </configuration>
opens a thread in the Application_Start method in the global file to write error information in the queue to the log file.
Using System.Linq;
Using System.Threading;
Using System.Web.Http;
Using SYSTEM.WEB.MVC;
Using System.Web.Optimization;
Using System.Web.Routing;
Using Log4net; Using PMS.
Webapp.models;
Using SPRING.WEB.MVC; Namespace PMS. WEBAPP {//NOTE: For instructions on enabling IIS6 or IIS7 Classic mode,//please visit http://go.microsoft.com/? linkid=9394801 public class Mvcapplication:springmvcapplication//httpapplication {protected void application_s Tart () {log4net.
Config.XmlConfigurator.Configure ()//Read log4net configuration information arearegistration.registerallareas ();
Webapiconfig.register (globalconfiguration.configuration);
Filterconfig.registerglobalfilters (globalfilters.filters);
Routeconfig.registerroutes (routetable.routes);
Bundleconfig.registerbundles (Bundletable.bundles);
Opens a thread to scan the exception information queue.
var FilePath = Server.MapPath ("/log/"); ThreadPool.QueueUserWorkItem ((a) => {while (true) {//Determine if the queue has data if (log4exc Eptionattribute.Exceptions.any ()) {//OUT team an exception information var ex = Log4ExceptionAttribute.Exceptions.Dequeue ();
If the exception information is not an empty if (ex = null) continue;
Writes exception information to the log file var logger = Logmanager.getlogger ("errormsg"); Logger. Error (ex.
ToString ());
else {//If the exception information queue is empty, the thread rests for three seconds Thread.Sleep (3000);
}}, FilePath);
}
}
}
The configuration of the error log successfully completed.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.