[C #] My log4net use manual (Perfect)

Source: Internet
Author: User
Tags datetime local time modifier syslog log4net

1. Log4net Introduction

Log4net is. NET, a very good open source logging component. Log4net logging is very powerful. It can be divided into different levels of the log, in different formats, output to different media. Under the Java platform, it also has a sister component--log4j.

Log4net's download Address: http://logging.apache.org/log4net/download.html

2. Composition of the Log4net

The log4net is composed of five parts, namely Appenders, Filters, Layouts, loggers and object renders.

2.1 appenders

Appenders is used to define how the log is exported. It can also implement logging filtering and output formats by configuring filters and layout.

Its output is as follows: Adonetappender logs to the database. There are two ways to use SQL and stored procedures. Ansicolorterminalappender the log to the ANSI terminal. aspnettraceappender   can view logged logs in the form of trace in asp.net. Bufferingforwardingappender caches log events before outputting to the child appenders. Consoleappender logs output to the application console. Eventlogappender writes the log to Windows event log. Fileappender prints the log to a file. Forwardingappender sends log events to the child appenders. Localsyslogappender writes logs to local syslog service  (for UNIX only). Memoryappender the log to a memory buffer. Netsendappender logs output to Windows messenger service. These log information will be displayed in the User Terminal's dialog box. Outputdebugstringappender log output to Debuger, if the program does not debuger, output to the system Debuger. If the system Debuger is also unavailable, the message is ignored. remotesyslogappender  writes logs to Remote syslog service via the UDP network protocol. Remotingappender through. Net remoting writes the log to the remote receiving end. Rollingfileappender writes the log to a file in the form of a rollback file. Smtpappender writes the log to the message. Smtppickupdirappender the message into a directory as a file, an SMTP proxy such as the IIS SMTP agent can read or send them. The Telnetappender client uses Telnet to accept log events. Traceappender writes the log to the .net trace  system. Udpappender sends the log to a remote host in the form of connectionless UDP datagrams or UDPCLBroadcast in the form of ient.

2.2 Filters

Filters can be used to filter out the contents of the Appender output. There are several filters: Denyallfilter prevents all log events from being logged levelmatchfilter only log events of a specified level are logged Levelrangefilter events that are within a specified range of log levels are logged Loggermatchfilter logger name matching to record the PropertyFilter message matches the specified property value only to be logged Stringmathfilter message matches the specified string before being recorded

2.3 Layouts

Layout is used to control the output format of Appender, so that it can be linear or can make XML. A appender can only have one layout.

The most commonly used layout should be the patternlayout of the user-defined format, followed by Simplelayout and Exceptionlayout. Then there are 4 layout, two of which are layout to output XML, but Chinese can be problematic.

Exceptionlayout needs to give logger the method of passing in the exception object as a parameter to work, otherwise it will not output anything. The output will contain message and trace

Finally, let's say Patterlayout's formatted string:

Conversion Pattern Name Effect
A Equivalent to AppDomain
AppDomain The friendly name of the application domain that raised the log event. (I'm using the name of an executable file in general.) )
C Equivalent to logger
C Equivalent to type
Class Equivalent to type
D Equivalent to date
Date

The local time that the log event occurred. Output UTC time using%utcdate. You can also follow a date format, enclosed in curly braces, after date. For example:%date{hh:mm:ss,fff} or %date{dd MMM yyyy hh:mm:ss,fff}. If nothing follows date, the ISO8601 format is used.

Date format and. NET, the same format is used in the ToString method of the DateTime class.

In addition, Log4net also has 3 of its own format formatter. They are "absolute", "DATE" and "ISO8601" respectively representing Absolutetimedateformatter,datetimedateformatter and Iso8601dateformatter. For example:%date{iso8601} or %date{absolute}.

They have better performance than ToString.

exception

Exception information

An exception object must be stored in the log event, and nothing will be output if the log event does not contain an exception object. The exception output is finished with a newline. Typically, a newline is added before the output exception, and the exception is placed at the end.

F Equivalent to file
File

The name of the source code file where the log request occurred.

Warning: valid only when debugging. Invoking local information can affect performance.

Identity

The name of the currently active user (Principal.Identity.Name).

Warning: performance is affected. (When I test,%identity returns are empty.) )

L Equivalent to location
L Equivalent to line
Location

The method that raises the log event, including the namespace and class name, and the source file and line number in which it resides.

Warning: performance is affected. No PDB file, only method name, no source file name and line number.

Level

Log event level

Line

The line number that raised the log event

Warning: performance is affected.

Logger

The name of the logger object that records the log event.

You can use the precision specifier to control the output level of the logger name, and the default output full name.

Note that the control of the precision character is started from the right. For example: Logger is named "A.B.C", the output model is %logger{2} , and "B.C" is output.

M Equivalent to message
M Equivalent to method
Message

The message provided by the application to the log event.

Mdc

MDC (old: threadcontext.properties) is now part of the event properties. It is reserved for compatibility and is equivalent to property.

Method

The name of the method in which the log request occurred (only the method name).

Warning: performance is affected.

N Equivalent to newline
NewLine

Line feed

Ndc

NDC (nested diagnostic context)

P Equivalent to level
P Equivalent to property
Properties Equivalent to property
Property

The special properties of the output event. For example: %property{user} outputs the user property. property is added to the time by loggers or appenders. There is a default property "Log4net:hostname" will always have.

%property will output the attributes.

I don't know how to use it, except that I can use it to get a host name. )

R Equivalent to timestamp
T Equivalent to thread
Timestamp

The number of milliseconds to elapse from the start of the program to the occurrence of the event.

Thread

The thread that raised the log event, using the thread number if there is no thread name.

Type

The full name of the class that raised the log request.

You can use the precision control character. For example: The class name is "Log4net." Layout.patternlayout ", the format model is %type{1} will output" patternlayout ". (also starting from the right.) )

Warning: performance is affected.

U Equivalent to identity
Username

The WindowsIdentity of the current user. (Similar to: Hostname/username)

Warning: performance is affected.

Utcdate

The UTC time at which the log event occurred. It can also be followed by a date format, enclosed in curly braces. For example:%utcdate{hh:mm:ss,fff} or %utcdate{dd MMM yyyy hh:mm:ss,fff}. If utcdate follows nothing, the ISO8601 format is used.

Date format and. NET, the same format is used in the ToString method of the DateTime class.

In addition, Log4net also has 3 of its own format formatter. They are "absolute", "DATE" and "ISO8601" respectively representing Absolutetimedateformatter,datetimedateformatter and Iso8601dateformatter. For example:%date{iso8601} or %date{absolute}.

They have better performance than ToString.

W Equivalent to username
X Equivalent to NDC
X Equivalent to MDC
%

% percent output a percent semicolon

Instructions for invoking local information (caller location information):

Local information is invoked by%type%file%line%method%location%class%c%F%l%l. Doing so can affect performance. Local information is used with System.Diagnostics.StackTrace.. Net 1.0 does not support System.Diagnostics.StackTrace classes.

Local information is normally obtained in debug mode, may not be obtained in a debug mode, or can only be partially acquired. (According to my test, there is a program database (. pdb) file that needs to be in fact.) )

%property the attribute in this thing seems to be set in code (except for the default property log4net:hostname).

Modifier for escape character:

Left
Format modifierJustify Minimum width Maximum width Comment
%20logger False 20 None

If the logger name is less than 20 characters, fill a space on the left .

%-20logger True 20 None

If the logger name is less than 20 characters, fill the space on the right .

%.30logger NA None 30

More than 30 characters will be truncated.

%20.30logger False 20 30

Logger name to between 20 to 30, less on the left to fill space, more truncation.

%-20.30logger True 20 30

Logger name to between 20 to 30, less on the right to fill space, more truncation.

2.4 Loggers

Logger are components that interact directly with the application. Logger simply produces a log, which is then recorded by its referenced appender to the specified medium and controlled by the layout output format.

Logger provides a variety of ways to record a log message, or there can be multiple logger at the same time. Each instantiated logger object is maintained by the Log4net as a named entity (Named Entity). Log4net uses the inheritance system, that is to say, if there are two logger, the names are A.B.C and a.b respectively. Then A.B is the ancestor of A.B.C. Each logger inherits the attributes of its ancestors.

Let's say the level of the log, which is high in the end:

Off > FATAL > ERROR > WARN > INFO > DEBUG > All

Where off indicates that logging is disabled, all indicates that all logs can be logged.

Logger implements the Ilog interface, Ilog defines 5 methods (debug,inof,warn,error,fatal) to log logs for different log levels respectively. These 5 methods also have 5 overloads. Let's use debug as an example to illustrate that the others are similar to it.

The Debug method is defined in Ilog as follows:

void Debug (object message);

void Debug (Object message, Exception ex);

There is also a Boolean property:

BOOL isdebugenabled {get;}

If you use Debug (object message, Exception Ex), the log will output Exception in the default configuration, regardless of whether%exception is defined in layout. Includes exception message and trace. If you use Debug (Object message), the log does not output exception anyway, because there is no.

Finally, there is a Logmanager class, which is used to manage the due logger. Its GetLogger static method, which can obtain the corresponding logger in the configuration file:

Log4net. ILog log = log4net. Logmanager.getlogger ("Logger-name");

2.5 Object Renders

My understanding of object renders is this. It will tell logger how to convert an object into a string and record it in a log. (You may notice that the interface defined in Ilog receives an object, not a string.) )

For example, you want to record the Orange object in the log, but at this point logger will only invoke the Orange default ToString method. So define a Orangerender class to implement the Log4net.ObjectRender.IObjectRender interface, and then register it. Then logger will know how to record orange in the log.

But I have not tested, the specific how to do or look at the document.

2.6 Repository

Repository is mainly used to maintain the organization structure of log objects. If you don't want to expand log4net yourself, you can use it without looking for it. But I still think I should mention it.

3. Use of log4net in the program

Do some configuration work before using Log4net. Configuration work can be done in a configuration file or in code. We mainly talk about how to configure log4net in a configuration file because it's more convenient and flexible, and you don't have to recompile your code. For how to configure using code, look at the connection in the document and later in the reference.

3.1 Defining configuration Files

The log4net configuration can be placed in the application's default configuration file (app.config or Web.config) or in your own configuration file.

If you use Visual Studio to edit a configuration file, its label for Log4net is not smart and automatically complete. Of course it's not impossible, look here:

Http://www.cnblogs.com/didasoft/archive/2007/07/23/log4net_xsd.html

Here's to thank Jerry, for providing us with the XSD schema.

Cut the crap, first look at an example of a complete configuration file:

<?xml version= "1.0" encoding= "Utf-8"?>

<configuration>

<configSections>
<section name= "Log4net"
Type= "Log4net. Config.log4netconfigurationsectionhandler, log4net-net-1.2.10 "/>
</configSections>

<log4net>

<root>
<level value= "WARN"/>
<appender-ref ref= "Logfileappender"/>
<appender-ref ref= "Consoleappender"/>
</root>

<logger name= "testapp.logging" >
<level value= "DEBUG"/>
</logger>

     <appender name= "Logfileappender"  
               type= "log4net. Appender.fileappender "> 
      <param name=" File "value=" Log-file.txt "/ >&NBSP
      <param name= "Appendtofile" value= "true"/>

       <layout type= "log4net. Layout.patternlayout "> 
        <param name=" Header " Value= "[header]& #13;& #10;" /> 
        <param name= "Footer value=" [footer]& #13; &# 10; " />&NBSP
        <param name= "Conversionpattern" &NBSP;
                value= "%d [%t]%-5p%c [%x] -%m %n "/> 
       </layout>

<filter type= "log4net. Filter.levelrangefilter ">
<param name= "Levelmin" value= "DEBUG"/>
<param name= "Levelmax" value= "WARN"/>
</filter>

</appender>

<appender name= "Consoleappender"
Type= "Log4net. Appender.consoleappender ">
<layout type= "log4net. Layout.patternlayout ">
<param name= "Conversionpattern"
Value= "%d [%t]%-5p%c [%x]-%m%n"/>
</layout>
</appender>

</log4net>
</configuration>

If the log4net configuration is not placed in the application's configuration file, it is not necessary to,<configsection> nodes <section> nodes in their own defined files.

The following is a description of the label elements.

3.1.1 <log4net>

All configurations are defined in the <log4net> element.

Supported Properties:

Debug Optionally, the value is true or FALSE and the default is False. Set to True to turn on internal debugging for log4net.
Update Optionally, the value is the merge (merge) or overwrite (overlay), and the default value is the merge. Set to overwrite, the configured libraries are reset when the configuration is committed.
Threshold Optionally, the value is the level registered in the Repository (library), and the default value is all.

Supported child elements:

Appender 0 or more
Logger 0 or more
Renderer 0 or more
Root Up to one
Param 0 or more

3.1.2 <root>

is actually a root logger, and all other logger inherit it by default. The root element has no attributes.

Supported child elements:

Appender-ref 0 or more, the name of the Appender to be referenced.
Level Up to one. Only events at this level or above will be recorded.
Param 0 or more, set some parameters.

3.1.3 <logger>

Supported Properties:

Name Must, logger's name.
Additivity Optionally, the value is true or FALSE and the default value is true. When set to False, the Appender in the parent logger is blocked.
Supported child elements:
Appender-ref 0 or more, the name of the Appender to be referenced.
Level Up to one. Only events at this level or above will be recorded.
Param 0 or more, set some parameters.

3.1.4 <appender>

Defines how the log is to be exported only as a child of log4net. The Name property must be unique and the type attribute must be specified.

Supported Properties:

Name Must, Appender the name of the object
Type Required, the output type of the Appender object
Supported child elements:
Appender-ref 0 or more to allow this appender to refer to other appender, not so appender types are supported.
Filter 0 or more, define the filters used by this app.
Layout Up to one. Defines the output format used by Appender.
Param 0 or more, set the value of the corresponding property in the Appender class.

In fact, <appender> can contain more than 4 child elements.

3.1.5 <layout>

Layout, only as a child element of <appender>.

Supported Properties:

Type The type of layout that is required
Supported child elements:
Param 0 or more, set some parameters.

3.1.6 <filter>

Filter, only as a child element of <appender>.

Supported Properties:

Type The type of filter that is required
Supported child elements:
Param 0 or more, set some parameters.

3.1.7 <param>

<param> elements can be child elements of how elements.

Supported Properties:

Name Required, the value is the name of the parameter of the parent object.
Value Optionally, in value and type, a property must be specified. Value is a string that can be converted to a parameter value.
Type Optionally, in value and type, a property must be specified. Type is the name of a class, and if the type is not defined in the Log4net assembly, the full name is required.
Supported child elements:
Param 0 or more, set some parameters.

3.2 Using configuration files

3.2.1 Associated configuration file

Log4net The default association is the application's configuration file (AppName.exe.config), which can be set using assembly custom properties. Here's a description of this custom attribute: Log4net. Config.xmlconifguratorattribute.

Xmlconfiguratorattribute has 3 properties: </

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.