Application of Log4net Exception Log records in ASP. NET mvc3.0

Source: Internet
Author: User
Tags log4net

Log4net is. NET next to a very good open source logging component. Log4net logging is a very powerful feature. It can be divided into different levels of the log, in different formats, output to different media. This article is primarily about how to use log4net to quickly create system logs in Visual Studio2010 (ASP. Mvc3.0), and how to extend them to output custom fields.

Users can download log4net source code from http://logging.apache.org/log4net/. After unpacking the package, load the Log4net.sln into Visual Studio. NET under the extracted src directory and compile to get log4net.dll. Users in their own programs to join the log function, just Log4net.dll into the project can be.

Configuring in Projects

The first step: first refer to the Log4net.dll file in your project.

Step two: Add configsections nodes in the Web. config file

  <configSections>    <section name= "log4net" type= "log4net. Config.log4netconfigurationsectionhandler, log4net "/>    <!--Configure a node name called Log4net-->  </ Configsections>

Step three: Add the log4net configuration node

<log4net debug= "true" ></log4net>

Then add it under the Log4net node

Writing to a configuration in a local text file

         <appender name= "Logfileappender" type= "log4net. Appender.fileappender ">             <!--defines the name of the attachment that is logged to the file, which means the names of the attachments--                      <!-- There is also an attachment in log4net rollingfileappender it means that many files will be generated in a loop, for example, the setup can generate 20 files, each file size is 2K, then if the first 、-->                       <!-- Files that are larger than 2K will automatically create a sequentially named file--             <param name= "file" value= "C:\Log\DBLog.txt"/> <!--the existence of log records--             <param name= "Appendtofile" value= "true"/><!--to True indicates that the log is appended to the file and False, a new file is recreated-             < Layout type= "log4net. Layout.patternlayout ">               <!--Output Control--               <param name=" Conversionpattern "value="%d [%t]%-5p%c [%x] -%m%n "/>             </layout>              </appender>


The note is clear, it is not explained.

Write the configuration of the specified mailbox

 <appender name= "Smtpappender" type= "log4net. Appender.smtpappender "> <!--set up an attachment to send e-mail messages-<authentication value=" Basic "/> & Lt;to value= "[email protected]"/> <from value= "[email protected]"/> <usernam E value= "Account"/> <password value= "password"/> <subject value= "program exception logging mail send"/> &             Lt;smtphost value= "smtp.163.com"/> <buffersize value= "Up"/> <lossy value= "true"/> <evaluator type= "log4net. Core.levelevaluator "> <threshold value=" Debug "/> </evaluator> <lay Out Type= "log4net. Layout.patternlayout "> <conversionpattern value="%newline%date [%thread]%-5level%logger [%property {NDC}] -%message%newline%newline%newline "/> </layout> </appender> 

163 mailbox servers are sent through the

Write the log to the relevant configuration of the database, and create a corresponding database table

         <appender name= "Adonetappender" type= "log4net. Appender.adonetappender "> <!--Store to database--<buffersize value="/> &lt ; ConnectionType value= "System.Data.SqlClient.SqlConnection, System.Data, version=1.0.3300.0, Culture=neutral, publickeytoken=b77a5c561934e089 "/> <connectionstring value=" server=.; Database=log4net;user id=sa;password=saa "/> <commandtext value=" INSERT into _log ([date],[thread],[level ],[logger],[message],[exception]) VALUES (@log_date, @log_thread, @log_level, @log_logger,                  @log_message, @log_exception) "/> <parameter> <parametername value=" @log_date "/> <dbtype value= "DateTime"/> <layout type= "log4net.                 Layout.rawtimestamplayout "/><!--can be thought of as logging time--</parameter> <parameter> <parametername value= "@log_thRead "/> <dbtype value=" String "/> <size value=" 255 "/> <la Yout type= "log4net.                 Layout.patternlayout "> <conversionpattern value="%thread "/><!--Logging Thread number--- </layout> </parameter> <parameter> <parametername value                 = "@log_level"/> <dbtype value= "String"/> <size value= "/>" <layout type= "log4net. Layout.patternlayout "> <conversionpattern value="%level "/><!--Log Level--&L t;/layout> </parameter> <parameter> <parametername value= "@log_l Ogger "/> <dbtype value=" String "/> <size value=" 255 "/> <l Ayout type= "log4net. Layout.patternlayout "> <conversionpattern value="%loggeR "/><!--which logger stores this log--</layout> </parameter> &LT;PARAMETER&G                 T <parametername value= "@log_message"/> <dbtype value= "String"/> <size value= "4000"/> <layout type= "log4net.                 Layout.patternlayout "> <conversionpattern value="%message "/><!--log Information-- </layout> </parameter> <parameter> <parametername value= "@lo                 G_exception "/> <dbtype value=" String "/> <size value=" 255 "/> <layout type= "log4net. Layout.exceptionlayout "/><!--exception Info-</parameter> </appender>

Another way to write files is to configure

         <appender name= "Rollingfile" type= "log4net. Appender.rollingfileappender ">             <!--This is the rollingfileappender--> <file value= I mentioned above.             Example.log "/><!--file name---             <appendtofile value=" false "/><!--creates a new file, normally set to true, set to False, is to see the file created--             <maximumfilesize value= "1KB"/><!--File Size--             <maxsizerollbackups value= "20" /><!--Create the maximum number of files             --<layout type= "log4net. Layout.patternlayout ">                <conversionpattern value="%level%thread%logger-%message%newline "/>             </layout>         </appender>

There are two more nodes in the Log4net node

      <logger name= "loggering" >        <level value= "Warn"/> <appender-ref        ref= "Adonetappender"/>      </logger>      <root>        <level value= "info"/>          <!--<appender-ref ref= " Adonetappender "/>-->          <appender-ref ref=" Smtpappender "/>          <!--<appender-ref ref=" Logfileappender "/>          <appender-ref ref=" Coloredconsoleappender "/> <appender-ref          ref=" Eventlogappender "/>          <append-ref ref=" Netsendappender "/> <appender-ref          ref=" RollingFile "/ >-->      </root>

In the framework system, all log objects are descendants of the root log (root logger). Therefore, if a log object is not explicitly defined in the configuration file, the framework uses the properties defined in the root log. In the <root> tab, you can define a list of level and Appender values. If you do not define A level value, DEBUG is the default . the Appender object used by the log object can be defined through the <appender-ref> tag . <appender-ref> declares a reference to a Appender object that is defined elsewhere. Settings in a Logger object override the settings of the root log. For the Appender property, the child log object inherits the Appender list of the parent log Object . This default behavior can also be changed by explicitly setting the <logger> tag's additivity property to false.

Then there will be a write to the database log and a write to the mailbox

Initializing the configuration in the Global.asax file
        protected void Application_Start ()        {            //read log  If you use Log4net, the application starts with a configuration            log4net. Config.XmlConfigurator.Configure ();                        Arearegistration.registerallareas ();            Registerglobalfilters (globalfilters.filters);            RegisterRoutes (routetable.routes);        }
Call
        private static readonly log4net. ILog log = log4net. Logmanager.getlogger ("loggering");        Public ActionResult About ()        {              log. Info ("Log logging Information");             Log. Debug ("Debug Information");             Log. Error ("error message");             Log. Warn ("Warn information");             Exception ex = new Exception ("Abnormal information for testing");             Log. Fatal ("Fatal information", ex);            return View ();        }

Run for a minute

Summarize


DEBUG, INFO, WARN, ERROR in log4net are well differentiated. Normal DEBUG, INFO log, let it record in the log file it.

For WARN, ERROR level logs, log files to the same time, by the way to send e-mail to my mailbox. In this way, I do not have to look at the log files every day, and secondly, what is wrong, can be notified in a timely manner by e-mail.

Sample code Download link Http://url.cn/HZLDgr

Database structure

Create DATABASE Log4netgouse log4netcreate table _log (    ID int identity () primary key NOT NULL,    date datetime nu ll,    thread int null, level    varchar (TEN) NULL,    logger varchar () NULL,    Message varchar (+) NULL,    Exception varchar (+) NULL)

Also to be optimized, there is time to ponder.

This article is reproduced from Aehyok

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.