Log4net configuration under MVC and the use of thread queues to log exception information

Source: Internet
Author: User

Log4net is used to record the log, the program can be run in the process of information output to some places (files, databases, eventlog, etc.), the log is the program's black box, can be
The log looks at the system's running process to discover problems with the system. The role of the log: the process of running the steps, the success of the failure to record, the critical data recorded down the system problems. Log4j.
For the Web site, you can not display the exception information to the user, the exception information can only be recorded to the log, the issue of the log file sent to developers, you can know the problem.


Configuring the Log4net Environment


(1) Create a new WebApplication

(2) Add a reference to the Log4net.dll (Bin\net\2.0\release cannot reference the debug version) (copy the corresponding DLL file to the Lib folder in the project.) )


(3) Add configuration in Web. config (or app. config), see Remarks

(4) Initialization: Add log4net at the beginning of the program. Config.XmlConfigurator.Configure (); Do not add to the page load

Add to Application_Start () in MVC

(5) Logmanager.getlogger (typeof) where the log is to be printed. Debug ("Information");. Pass the log class name that you want to log by Logmanager.getlogger get the ilog of this class (so that in the log file you can see which class output the log is), and then call the Debug method output message. Because there is more than one place inside a class to print the log, Ilog is generally declared as a static field.
Private static ILog Logger=logmanager.getlogger (typeof (Test))
Output error message with the Ilog.error method, the second parameter can pass the exception object. Log. Error ("* * * * +ex"), log. Error ("* * * ERROR", ex)
Test code:
ILog logger = Logmanager.getlogger ("errormsg");
Logger. Error (ex. ToString ());

Appender: The logs can be exported to different locations, with different output targets corresponding to different appender:rollingfileappender (scrolling files), Adonetappender (database), Smtpappender (mail), etc.

Level: Identifies the important level of this log information. None>fatal>error>warn>debug>info>all, set a level, then the log below this level will not be written into the Appender.

Log4net can also set a number of appender, can be realized at the same time log to file, data, send mail, etc. can be set different levels of appender, can achieve the normal level are recorded to the file, error above level send mail , can be implemented for different classes to set different Appender, you can also customize the Appender, so that you can implement the error message to send text messages and so on.

(*) In addition to log4net, there are Enterprise Library logging application Block, Apache Commonlog and Nlog, etc., are similar.

Log4net Configuration
<configuration>
<configSections>
<section name= "log4net" type= "log4net. Config.log4netconfigurationsectionhandler, log4net "/>
</configSections>
<log4net>
<!--Define some output appenders--
<appender name= "Rollinglogfileappender" type= "log4net. Appender.rollingfileappender ">
<file value= "Test.txt"/>
<appendtofile value= "true"/>
<maxsizerollbackups value= "Ten"/>
<maximumfilesize value= "1024KB"/>
<rollingstyle value= "Size"/>
<staticlogfilename value= "true"/>
<layout type= "log4net. Layout.patternlayout ">
<conversionpattern value= "%date [%thread]%-5level%logger-%message%newline"/>
</layout>
</appender>
<root>
<level value= "DEBUG"/>
<appender-ref ref= "Rollinglogfileappender"/>
</root>
</log4net>
</configuration>

<log4net>
<!--OFF, FATAL, ERROR, WARN, INFO, DEBUG, all---
<!--Set Root logger level-to-ERROR and its appenders-
<root>
<level value= "All"/>
<appender-ref ref= "Sysappender"/>
</root>

<!--Print Only messages of level DEBUG or 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= "Appendtofile" value= "true"/>
<param name= "Rollingstyle" value= "Date"/>
<param name= "Datepattern" value= "&quot; Logs_&quot;yyyymmdd&quot;. txt&quot; "/>
<param name= "Staticlogfilename" value= "false"/>
<layout type= "log4net. Layout.patternlayout,log4net ">
<param name= "Conversionpattern" value= "%d [%t]%-5p%c-%m%n"/>
<param name= "header" value= "& #13;& #10;----------------------header--------------------------& #13; & #10; "/>
<param name= "Footer" value= "& #13;& #10;----------------------Footer--------------------------& #13; & #10; "/>
</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"/>
</layout>
</appender>
</log4net>

Thread Open record exception information management

First step: New MyExceptionAttribute.cs inheritance Handleerrorattribute

 Public classMyexceptionattribute:handleerrorattribute { Public StaticQueue<exception> Exceptionqueue =NewQueue<exception>(); /// <summary>        ///can catch exception data/// </summary>        /// <param name= "Filtercontext" ></param>         Public Override voidonexception (Exceptioncontext filtercontext) {Base.            Onexception (Filtercontext); Exception ex=filtercontext.exception; //Write to queueExceptionqueue.enqueue (ex); //Skip to error pageFilterContext.HttpContext.Response.Redirect ("/error.html"); }    }

Step Two: Modify the custom filter in the FilterConfig.cs filter

 Public class Filterconfig    {        publicstaticvoid  registerglobalfilters (globalfiltercollection filters)        {            //filters. ADD (New Handleerrorattribute ());            Filters. ADD (new  Myexceptionattribute ());        }    }

Step three: Create a thread in Global.asax.cs and record the exception with Log4net

protected voidApplication_Start () {log4net. Config.XmlConfigurator.Configure ();//Read about log4net configuration information in the configuration fileArearegistration.registerallareas ();            Webapiconfig.register (globalconfiguration.configuration);            Filterconfig.registerglobalfilters (globalfilters.filters);            Routeconfig.registerroutes (routetable.routes);            Bundleconfig.registerbundles (Bundletable.bundles); //opens a thread that scans the queue for exception information.             stringFilePath = Server.MapPath ("/log/"); ThreadPool.QueueUserWorkItem ((a)= {                 while(true)                {                    //determine if there is data in the queue                    if(MyExceptionAttribute.ExceptionQueue.Count () >0) {Exception ex=MyExceptionAttribute.ExceptionQueue.Dequeue (); if(ex!=NULL)                        {                            //writes exception information to the log file. //string fileName = DateTime.Now.ToString ("Yyyy-mm-dd"); //File.appendalltext (FilePath + filename+ ". txt", ex. ToString (), System.Text.Encoding.UTF8);ILog Logger= Logmanager.getlogger ("errormsg"); Logger. Error (ex.                        ToString ()); }                        Else                        {                            //If there is no data in the queue, restThread.Sleep ( the); }                    }                    Else                    {                        //If there is no data in the queue, restThread.Sleep ( the);        }}},filepath); }

Log4net configuration under MVC and the use of thread queues to log exception information

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.