Preface
As a web platform or winform application, error logging is a basic and important function, an easy way is to use try {} catch {} to record errors. This method has obvious drawbacks of code accumulation. In addition, it cannot fully record exceptions when handling uncontrollable exceptions.
Original Solution
Take the web as an example. The following code is the method I used previously. The idea is to use the page base class to record errors and inherit the class from other pages, in this way, the error information is recorded in a text file.
Public class sessionglobal: system. web. UI. page {public sessionglobal () {This. load + = new eventhandler (basepage_load); this. error + = new eventhandler (basepage_error );} /// <summary> /// handle page errors /// </Summary> /// <Param name = "sender"> </param> /// <Param name = "E"> </param> void basepage_error (Object sender, eventargs e) {string filepath = mappath ("~ \ Log "); string filename =" errlog _ "+ String. Format (" {0: yyyymmdd} ", datetime. Now) +". log "; if (! Directory. exists (filepath) {try {directory. createdirectory (filepath);} catch {}} stringbuilder sblogcontent = new stringbuilder (); sblogcontent. append ("************************************* * ****************** \ r \ n "); sblogcontent. append ("error address:" + httpcontext. current. request. URL. tostring () + "\ r \ n"); sblogcontent. append ("absolute path:" + request. physicalapplicationpath. tostring () + request. filepath. tostr Ing () + "\ r \ n"); If (request. urlreferrer! = NULL) {sblogcontent. append ("Previous Page:" + request. urlreferrer. tostring () + "\ r \ n");} sblogcontent. append ("Client IP:" + request. userhostaddress. tostring () + "\ r \ n"); sblogcontent. append ("client browser:" + request. useragent. tostring () + "\ r \ n"); sblogcontent. append ("error message:" + httpcontext. current. error. message + "\ r \ n"); sblogcontent. append ("error time:" + datetime. now. tostring () + "\ r \ n"); sblogcontent. append ("\ r \ n "); Sblogcontent. append ("************************************* * ***************** \ r \ n "); string file = filepath + "\" + filename; # Write the region log if (! File. exists (File) {try {streamwriter Sw = file. createtext (File); Sw. writeline (sblogcontent. tostring (); Sw. close () ;}catch {}} else {try {streamwriter Sw = file. appendtext (File); Sw. writeline (sblogcontent. tostring (); Sw. close () ;}catch {}# endregion }}
Of course, this is a very simple way to record errors, and its disadvantages are also obvious: first, it can only record error class information, and that is, it is only limited to storage in text (or database) cannot be stored as a Windows event.
Log4net Introduction
Log4net is a well-known Logging Component from log4j. In addition to text file records, log4net also supports Windows event records, console, and database records, as well as control the log level to be recorded, log types include fail, error, warn, info, and debug.
Log4net consists of five parts: appenders, filters, layouts, logger, and object renders. Appenders defines the log output. filters is used to filter the content output by appender. You can set the specified level, specify the logger name, message matching attribute, or string to be recorded. layouts is used to control the appender output format, loggers directly interact with the application and generate logs from it. Then, the referenced appender records the specified media, and the layouts controls the output format. Object renders defines the ilog implementation method.
Use log4net
First download log4net from the official website and add references to the project. Then define the parameters in Web. config. We use it in the simplest way:
<configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net debug="true"> <appender name="LogFileAppender" type="log4net.Appender.FileAppender"> <param name="File" value="log\\log4net.log"/> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/> </layout> </appender> <logger name="File"> <level value="All" /> <appender-ref ref="LogFileAppender" /> </logger> </log4net>
Here we write data to the log folder of the current site. If you are worried about text growth, you can set the text size limit. For settings here you can view this article: http://blog.csdn.net/lyjcn/archive/2009/08/11/4432833.aspx can also view the official documentation.
The appender name defined above is file, which must also be used in the Code. Otherwise, an error occurs that the object cannot be instantiated.
The specific implementation is very simple:
Ilog log = log4net. logmanager. getlogger ("file"); // introduce log4net // record the error log. error ("error", new exception ("error occur"); // records serious error logs. fatal ("Fatal", new exception ("Fatal occur"); // records the General Information log. info ("info"); // record debugging information log. debug ("debug"); // log the warning information. warn ("Warn ");