Log4net detailed steps to create a system log-practical tips

Source: Internet
Author: User
Tags datetime system log create database log4net

Objective
Users can download the log4net source code from http://logging.apache.org/log4net/. After you unpack the package, load the Log4net.sln into visual Studio. NET in the unzipped src directory, and you can get log4net.dll after compiling. The user wants to add the log function in own program, only then can the Log4net.dll introduce the project.

Configuring in a Project

Step One: First refer to the Log4net.dll file in your project.
Step Two: Add the configsections node in the Web.config file

Copy Code code as follows:

<configSections>
<section name= "log4net" type= "log4net". Config.log4netconfigurationsectionhandler, log4net "/>
<!--Configure a knot named log4net-->
</configSections>

Step three: Add log4net configuration node

Copy Code code as follows:

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

And then add it under the Log4net node
Writing to a configuration in a local text file

Copy Code code as follows:

<appender name= "Logfileappender" type= "log4net". Appender.fileappender ">
<!--defines the name of the--> that the log is logged to the file, which indicates that the attachment is named.
<!--There is also an attachment in the log4net rollingfileappender it means that many files will be recycled, for example, the setup can generate 20 files, each file size of 2K, if the first 、-->
<!--file is larger than 2K, a file name is automatically created-->
<param name= "File" value= "C:\Log\DBLog.txt"/> <!--the presence path of logging-->
<param name= "Appendtofile" value= "true"/><!--true to indicate that the log is attached to a file, or FALSE, a new file is recreated-->
<layout type= "log4net. Layout.patternlayout ">
<!--output content control-->
<param name= "Conversionpattern" value= "%d [%t]%-5p%c [%x]-%m%n"/>
</layout>
</appender>

The annotations are clear and are not explained.
Write configuration for the specified mailbox

Copy Code code as follows:

<appender name= "Smtpappender" type= "log4net". Appender.smtpappender ">
<!--set up an attachment to send e-mail-->
<authentication value= "Basic"/>
<to value= "518@qq.com"/>
<from value= "a@163.com"/>
<username value= "Account"/>
<password value= "Password"/>
<subject value= "program Exception Log mail send"/>
<smtphost value= "smtp.163.com"/>
<buffersize value= "/>"
<lossy value= "true"/>
<evaluator type= "log4net. Core.levelevaluator ">
<threshold value= "Debug"/>
</evaluator>
<layout type= "log4net. Layout.patternlayout ">
<conversionpattern value= "%newline%date [%thread]%-5level%logger [%PROPERTY{NDC}]-%message%newline%newline% NewLine "/>
</layout>
</appender>

Through the 163 mailbox server sent
Writes the log to the database related configuration, but also establishes a corresponding database table

Copy Code code as follows:

<appender name= "Adonetappender" type= "log4net". Appender.adonetappender ">
<!--operations stored in the database-->
<buffersize value= "Ten"/>
<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"/>
<layout type= "log4net. Layout.patternlayout ">
<conversionpattern value= "%thread"/><!--the thread number when logging log-->
</layout>
</parameter>
<parameter>
<parametername value= "@log_level"/>
<dbtype value= "String"/>
<size value= "/>"
<layout type= "log4net. Layout.patternlayout ">
<conversionpattern value= "%level"/><!--log level-->
</layout>
</parameter>
<parameter>
<parametername value= "@log_logger"/>
<dbtype value= "String"/>
<size value= "255"/>
<layout type= "log4net. Layout.patternlayout ">
<conversionpattern value= "%logger"/><!--which logger stores the log-->
</layout>
</parameter>
<parameter>
<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= "@log_exception"/>
<dbtype value= "String"/>
<size value= "255"/>
<layout type= "log4net. Layout.exceptionlayout "/><!--exception information-->
</parameter>
</appender>

Another way to write a file is to configure

Copy Code code as follows:

<appender name= "Rollingfile" type= "log4net". Appender.rollingfileappender ">
<!--This is the rollingfileappender--> I mentioned above.
<file value= "Example.log"/><!--file name-->
<appendtofile value= "False"/><!--creates a new file, typically set to true, set to false here to see the created file-->
<maximumfilesize value= "1KB"/><!--file Size-->
<maxsizerollbackups value= ""/><!--Create 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

Copy Code code as follows:

<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 the level value and the list of Appender. If no value is defined for level, debug is the default. You can define the Appender object used by the log object through the <appender-ref> tab. <appender-ref> declares a reference to a Appender object that is defined elsewhere. The settings in a Logger object override the root log settings. 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> label's Additivity property to False.
Then there will be write to the database log and write the mailbox
Initializing the configuration in the Global.asax file

Copy Code code as follows:

protected void Application_Start ()
{
Read log if you use Log4net, the application starts with an initialization configuration
Log4net. Config.XmlConfigurator.Configure ();

Arearegistration.registerallareas ();

Registerglobalfilters (globalfilters.filters);
RegisterRoutes (routetable.routes);
}

Call

Copy Code code as follows:

private static readonly log4net. ILog log = log4net. Logmanager.getlogger ("loggering");
Public ActionResult About ()
{
Log. Info ("log Information");
Log. Debug ("Debug Information");
Log. Error ("error information");
Log. Warn ("Warn information");
Exception ex = new Exception ("Test exception information");
Log. Fatal ("Fatal information", ex);
return View ();
}

Run for a moment


Log4net DEBUG, INFO, WARN, ERROR distinguish very well. The normal DEBUG, INFO log, let it be recorded in the log file.
For WARN, ERROR-level logs, while logging to the log file, send an email to my mailbox. In this way, I do not have to go to see the log file every day, and secondly, what the problem, can be notified in time by e-mail.
Database structure

Copy Code code as follows:

Create DATABASE Log4net
Go
Use Log4net
CREATE TABLE _log
(
ID int identity (1,1) primary key NOT NULL,
Date datetime NULL,
thread int NULL,
Level varchar (TEN) NULL,
Logger varchar () NULL,
Message varchar (MB) NULL,
Exception varchar (MB) NULL
)

Still want to optimize, have time again to ponder ponder.

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.