[MVC learning notes] 4. Use Log4Net to record error logs, mvclog4net

Source: Internet
Author: User
Tags log4net

[MVC learning notes] 4. Use Log4Net to record error logs, mvclog4net

   

During Web application running, we will inevitably encounter program running exceptions. At this time, we should record the exception information so that developers and maintenance personnel can restore the cause of the exception, fix the cause of the exception. There are also many log recording components on the ASP. NET platform, such as Log4Net and CommonLogging. Here we use Log4Net to record exception logs.

   

1. Capture exceptions

ASP. net mvc provides a global exception handling filter: HandleErrorAttribute, which can be used to capture exception information.

In the Models folder, we create the Log4ExceptionAttribute type, inherit the HandleErrorAttribute class, and rewrite the OnException method to capture abnormal data:

Using System. web. mvc; namespace PMS. webApp. models {public class Log4ExceptionAttribute: handleErrorAttribute {// <summary> // rewrite the OnException method to capture the exception data /// </summary> /// <param name = "filterContext"> </param> public override void OnException (ExceptionContext filterContext) {base. onException (filterContext); // capture the current abnormal data var ex = filterContext. exception ;}}}

After creating a filter, we also need to register the custom exception processing filter 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. Considering the problems that may occur during multi-user concurrent operations, we need to create a new queue to store exception information temporarily. At the same time, a thread is opened to handle exceptions in the queue.

Create a static exception queue in the Log4ExceptionAttribute class. When an exception occurs, the program automatically triggers the OnException method. The method queues the current exception information 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 the OnException method to capture abnormal data /// </summary> /// <param name = "filterContext"> </param> public override void OnException (ExceptionContext filterContext) {base. onException (filterContext); // capture the current abnormal data var ex = filterContext. exception; // groups abnormal data. enqueue (ex); // jump to the error page filterContext. httpContext. response. redirect ("/Error.html ");}}}

Log4Net configuration is performed in the application configuration file. We first configure Log4Net in the configuration file. The node location to be configured for Log4Net is exactly the same as that for SpringNet. First, add a subnode to configSessions and then add a log4net node to 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 configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <! -- Configure Log4Net configurations --> <section name = "log4net" type = "log4net. Config. Log4NetConfigurationSectionHandler, log4net"/> <! -- Configure Log4Net to configure ingress --> <! -- Consumer Spring. net configuration example --> <sectionGroup name = "spring"> <section name = "context" type = "Spring. context. support. mvcContextHandler, Spring. web. mvc4 "/> </sectionGroup> <! -- Configure Spring. Net configurations --> </configSections> <! -- Configure Spring. Net to configure ingress --> <spring> <context> <resource uri =" file://~/Config/controllers.xml "/> <Resource uri =" file://~/Config/services.xml "/> </Context> </spring> <! -- Configure ingress Spring. Net --> <! -- Configure Log4Net to configure ingress --> <log4net> <! -- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL --> <! -- Set root logger level to ERROR and its appenders --> <root> <level value = "ALL"/> <appender-ref = "SysAppender"/> </root> <! -- Print only messages of level DEBUG or abve 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 =" AppendToFile "value =" true "/> <param name =" RollingStyle "value = "Date"/> <param name = "DatePattern" value = "& quot; logs _ & quot; yyyyMMdd & quot ;. t Xt & quot; "/> <param name =" StaticLogFileName "value =" false "/> <layout type =" log4net. layout. patternLayout, log4net "> <param name =" ConversionPattern "value =" % d [% t] %-5 p % c-% m % n "/> <param name =" Header" value = "& amp; #13; & #10; ---------------------- header ------------------------ & #13; & #10; "/> <param name =" Footer "value =" & #13; & #10; ---------------------- footer ------------------------ & #13; & #10; "/> </lay Out> </appender> <appender name = "leleapp" type = "log4net. appender. consoleAppender, log4net "> <layout type =" log4net. layout. patternLayout, log4net "> <param name =" ConversionPattern "value =" % d [% t] %-5 p % c-% m % n "/> </layout> </appender> </log4net> <! -- Configure Log4Net to configure ingress -->... </configuration>

You can configure the log information, format, and file name in the configuration file. The following describes the configuration information.

<? Xml version = "1.0"?> <Configuration> <configSections> <section name = "log4net" type = "log4net. Config. Log4NetConfigurationSectionHandler, log4net"/> </configSections> <! -- Site log configuration --> <log4net> <root> <! -- Control level, from low to high: ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF --> <! -- For example, if the definition level is INFO, the level of INFO is down. For example, DEBUG logs are not recorded. --> <! -- If the LEVEL value is not defined, the default value is DEBUG --> <level value = "ERROR"/> <appender-ref = "RollingFileAppender"/> </root> <appender name = "RollingFileAppender" type =" log4net. appender. rollingFileAppender "> <! -- Start with the Log file name --> <file value = "c: \ Log \ TestLog4net. TXT"/> <! -- Use the minimum lock when multithreading --> <lockingModel type = "log4net. Appender. FileAppender + MinimalLock"/> <! -- Date Format: Change the file record every day. If this parameter is not set, only logs of one day are recorded. You need to set --> <datePattern value = "(yyyyMMdd)"/> <! -- Whether to append to a file. The default value is true. Generally, you do not need to set --> <appendToFile value = "true"/> <! -- The form of transformation is date. In this case, there is only one log every day --> <! -- At this time, the node settings of MaxSizeRollBackups and maximumFileSize are meaningless --> <! -- <RollingStyle value = "Date"/> --> <! -- Change the log size in the form of --> <! -- In this case, the node settings of MaxSizeRollBackups and maximumFileSize make sense. --> <RollingStyle value = "Size"/> <! -- The number of log files recorded every day, used with maximumFileSize --> <MaxSizeRollBackups value = "10"/> <! -- Maximum size of each log file --> <! -- Available unit: KB | MB | GB --> <! -- Do not use decimals; otherwise, the current log will be written all the time --> <maximumFileSize value = "2 MB"/> <! -- Log format --> <layout type = "log4net. layout. patternLayout "> <conversionPattern value =" % date [% t] %-5 p % c-% m % n "/> </layout> </appender> </log4net> </configuration>

Enable a thread in the Application_Start method of the Global file to write error messages 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 the IIS6 or IIS7 Classic mode, // visit http://go.microsoft.com/?LinkId=9394801 Public class MvcApplication: SpringMvcApplication // HttpApplication {protected void Application_Start () {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); // enable a thread to scan the exception message queue. var filePath = Server. mapPath ("/Log/"); ThreadPool. queueUserWorkItem (a) =>{ while (true) {// checks whether the queue has data if (Log4ExceptionAttribute. exceptions. any () {// an exception message is displayed. var ex = Log4ExceptionAttribute. exceptions. dequeue (); // if the exception information is not empty, if (ex = null) continue; // write the exception information to the log file var logger = LogManager. getLogger ("errorMsg"); logger. error (ex. toString ();} else {// If the exception message queue is empty, the Thread takes three seconds to rest. sleep (3000) ;}}, filePath );}}}
The Error Log configuration is successfully completed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.