Detailed steps for log4net to create system logs

Source: Internet
Author: User

Preface
You can download the source code of log4netfrom http://logging.apache.org/log4net. After the package is decompressed, load log4net. sln to Visual Studio. NET in the decompressed src directory. After compilation, you can obtain log4net. dll. To add the log function to your program, you only need to introduce log4net. dll into the project.

Configure in Project

Step 1: first reference the log4net. dll file in the project.
Step 2: Add configSections nodes to the Web. config file.

Copy codeThe Code is as follows:
<ConfigSections>
<Section name = "log4net" type = "log4net. Config. Log4NetConfigurationSectionHandler, log4net"/>
<! -- Configure a node named log4net -->
</ConfigSections>

Step 3: Add a log4net configuration Node

Copy codeThe Code is as follows:
<Log4net debug = "true">
</Log4net>

Then add
Write configuration in local text file

Copy codeThe Code is as follows:
<Appender name = "LogFileAppender" type = "log4net. Appender. FileAppender">
<! -- Defines the name of the attachment that logs to the file. -->
<! -- In log4net, there is also an attachment RollingFileAppender, which indicates that many files will be generated cyclically. For example, it is set that a total of 20 files can be generated, and the size of each file is 2 K, so if the first, -->
<! -- If the file size exceeds 2 kb, a file named in sequence is automatically created. -->
<Param name = "File" value = "c: \ Log \ DBLog.txt"/> <! -- Path of the log record -->
<Param name = "AppendToFile" value = "true"/> <! -- If it is true, the log will be appended to the file. If it is false, a new file will be created. -->
<Layout type = "log4net. Layout. PatternLayout">
<! -- Output content control -->
<Param name = "ConversionPattern" value = "% d [% t] %-5 p % c [% x]-% m % n"/>
</Layout>
</Appender>

The comment is clear and I will not explain it.
Write the configuration of the specified mailbox

Copy codeThe Code is as follows:
<Appender name = "SmtpAppender" type = "log4net. Appender. SmtpAppender">
<! -- Set the email sender -->
<Authentication value = "Basic"/>
<To value = "518@qq.com"/>
<From value = "a@163.com"/>
<Username value = "Account"/>
<Password value = "password"/>
<Subject value = "sending emails with program exception log records"/>
<SmtpHost value = "smtp.163.com"/>
<BufferSize value = "512" type = "codeph" text = "/codeph"/>
<Lossy value = "true"/>
<Evaluator type = "log4net. Core. LevelEvaluator">
<Threshold value = "debug"/>
</Evaluator>
<Layout type = "log4net. Layout. PatternLayout">
<ConversionPattern value = "% newline % date [% thread] %-5 level % logger [% property {NDC}]-% message % newline"/>
</Layout>
</Appender>

Sent through the 163 email server
Write logs to related configurations of the database, and create a corresponding database table.

Copy codeThe Code is as follows:
<Appender name = "ADONetAppender" type = "log4net. Appender. ADONetAppender">
<! -- Operations for storing data to a database -->
<BufferSize value = "10"/>
<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"/> <! -- It can be considered as the log recording 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 -->
</Layout>
</Parameter>
<Parameter>
<ParameterName value = "@ log_level"/>
<DbType value = "String"/>
<Size value = "50"/>
<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 recorder 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 file Writing Method Configuration

Copy codeThe Code is 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. Generally, this parameter is set to true. Here, it is set to false to see the created file. -->
<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 log4net nodes.

Copy codeThe Code is as follows:
<Logger name = "Loggering">
<Level value = "Warn"/>
<Appender-ref = "ADONetAppender"/>
</Logger>
<Root>
<Level value = "info"/>
<! -- <Appender-ref = "ADONetAppender"/> -->
<Appender-ref = "SmtpAppender"/>
<! -- <Appender-ref = "LogFileAppender"/>
<Appender-ref = "ColoredConsoleAppender"/>
<Appender-ref = "EventLogAppender"/>
<Append-ref = "NetSendAppender"/>
<Appender-ref = "RollingFile"/> -->
</Root>

In the framework system, all log objects are descendants of root logger. Therefore, if a log object is not explicitly defined in the configuration file, the framework uses the attributes defined in the root log. In the <root> label, you can define the list of level values and Appender. If no LEVEL value is defined, the default value is DEBUG. You can use the <appender-ref> label to define the Appender object used by the log object. <Appender-ref> declares a reference to the Appender object defined elsewhere. The setting in a logger object overwrites the setting of the root log. For the Appender attribute, the sub-log object inherits the Appender list of the parent log object. This default behavior can also be changed by explicitly setting the additivity attribute of the <logger> label to false.
Then there will be Database Log writing and email writing.
Initialize configuration in the Global. asax File

Copy codeThe Code is as follows:
Protected void Application_Start ()
{
// If log4net is used to read logs, initialize the configuration at the beginning of the application.
Log4net. Config. XmlConfigurator. Configure ();

AreaRegistration. RegisterAllAreas ();

RegisterGlobalFilters (GlobalFilters. Filters );
RegisterRoutes (RouteTable. Routes );
}

Call

Copy codeThe Code is 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


In Log4net, DEBUG, INFO, WARN, and ERROR are well differentiated. For normal DEBUG and INFO logs, record them in the log file.
Logs at the WARN and ERROR levels are recorded in log files and sent to my mailbox by email. In this way, I do not have to go to the log file every day. I will be notified by email in case of any problems.
Database Structure

Copy codeThe Code is 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 (10) null,
Logger varchar (20) null,
Message varchar (100) null,
Exception varchar (100) null
)

It is still to be optimized. If you have time, you can try again.

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.