Log4net Five steps away

Source: Internet
Author: User
Tags system log log4net

This article is reproduced in Prague from heroes

This article is not to teach you a comprehensive understanding of log4net, this article just want to teach you orderly, according to paste Lu painting scoop like will use Log4net

1, Introduction of Log4net.dll components
2. Create a configuration file
Two methods, one in Web. config or app. Config
Join the following configuration section
<configSections>
<section name= "log4net" type= "log4net. Config.log4netconfigurationsectionhandler,log4net "/>
</configSections>
The configuration section above, the copy can be used

Add the definition of log4net configuration content, this immediately after the above content is defined in the config file, the following is an example:
<log4net>
<root>
<level value= "All"/>
<appender-ref ref= "Rollingfile"/>
</root>

<appender name= "Rollingfile" type= "log4net. Appender.rollingfileappender,log4net ">
<param name= "File" value= "Log.txt"/>
<param name= "Appendtofile" value= "false"/>
<param name= "Rollingstyle" value= "Date"/>
<param name= "Datepattern" value= "yyyy. Mm.dd "/>
<param name= "Staticlogfilename" value= "true"/>
<layout type= "log4net. Layout.patternlayout,log4net ">
<param name= "Conversionpattern" value= "%d [%t]%-5p%c-%m%n"/>
<param name= "header" value= "& #13;& #10;----------------------header--------------------------& #13; & #10; "/>
<param name= "Footer" value= "& #13;& #10;----------------------Footer--------------------------& #13; & #10; "/>
</layout>
</appender>
<appender name= "ConsoleApp" type= "log4net. Appender.consoleappender,log4net ">
<layout type= "log4net. Layout.patternlayout,log4net ">
<param name= "Conversionpattern" value= "%d [%t]%-5p%c-%m%n"/>
</layout>
</appender>
<logger name= "Log4nettest.logtest" >
<level value= "DEBUG"/>
<appender-ref ref= "Rollingfile"/>
<appender-ref ref= "Coloredconsoleapp"/>
<appender-ref ref= "Systemevent"/>
</logger>
</log4net>
If you don't bother to write, you can copy the above content
However, just a little explanation, the XSD hierarchy of the Log4net configuration section is as follows

<log4net>
<root><level/><appender-ref ref= ""/></root>
<appender name= "" type= "Appender Fully qualified class name" >
<param name= "" value= ""/>
<layout type= "log4net. Layout.patternlayout,log4net ">
<param name= "" value= ""/>
</layout>
</appender>
<logger>
<level value= ""/>
<appender-ref ref= ""/>
</logger>
It's really simple.
Log4net is the root tag of the Log4net configuration section
The root tag defines a root level of the recorder, log4net of the record of the hierarchy of organizations, the name of two logger,a is called loggera,b name loggera.b, then B is the son of a, B will automatically inherit a of some definitions, such as level definition, Appender-ref definition and so on, root is the total logger, the rest of the defined logger are his descendants, will inherit his settings

Every logger, including root (root is also a logger, but he is an ancestor, other aspects, like other logger), can define level
Level defines the log levels of records, that is, what level of logs you want to log, and the level from high to low is:
None
Fatal
ERROR
WARN
DEBUG
INFO
All

Level definition be aware that if you define debug, then the information below the debug level will not be logged, what do you mean? That is, even if you write a log message in the program with Log.info (), you specify the level in the configuration as debug, Because the info level is lower than debug, it is not logged. This is a very flexible process.

Logger also has a configuration is appender-ref, ref is the meaning of reference, log4net architecture is very interesting, very high extensibility is worth learning, he is divided into four elements:
Logger
Appender
Layout
Filter

Logger is the recorder who is responsible for the log
Appender to provide recorded media
Layout is responsible for formatting the contents of the entry
Filter is responsible for filtering the content

It can be said that the whole process is a log pipeline, each member responsible for one of the links
Logger sends out the record information, Appender receives the information, according to the internal layout configuration to the record information to format, according to filter decides whether this information is filtered out, finally, serializes it

So, logger's appender-ref is the definition of who logger to find to write content to disk, stream, or other media, so it's important.
Since it's a ref reference, it's definitely going to define the referenced Appender object.

Each appender represents an output medium
The Name property specifies its names, and the type is log4net. Appender the name of a class for the namespace, meaning, specify which media to use
There are more than 10 types of appender supported by Log4net, the most commonly used are Rollingfileappender,adonetappender,eventlogappender,fileappender, which are recorded in the file, respectively. system logs and databases
In addition, other parameters within the Appender are marked with PARAM, defined in key/value form
Here's a tip, every appender,log4net doesn't ask what parameters they need in a document, so how do we know?
Originally, these param names, you can directly check the corresponding Appender class property name, for example, when using Eventlogappender, by looking at the properties of the class, we know that it has
The Logname,applicationname attribute, then, means that you can add the following directly to this appender param:
<param name= "LogName" value= "Application"/>
<param name= "ApplicationName" value= "Log4nettest"/>

After defining the name and type property of the Appender and specifying the parameters for it using Param, a appender is established, and you can use his name to reference it in the <appender-ref of logger, then, The logger that references it is written to the media defined in Appender when it writes to the log.
A logger can refer to multiple appender, the result is that the same log, is logged to multiple media at the same time, such as, at the same time, send messages, write to the system log, sent to the remote host. However, although you can do this, be careful, because, will have a certain impact on performance, unless you need to, Otherwise, do not mess with this feature

In addition, Appender can define the optional Layout,layout definition is very necessary, if you do not want to see your log will feel dizzy, although log4net to help you write the log, but the format of the log information is our user-defined
The type parameter of layout specifies which class is used to format the definition, often with xmllayout,simplelayout,patternlayout, which, of course, depends on your needs, and the format you want to produce, if you want to output the XML document format, I'm sure you can't use Simplelayout.
Layout uses Param to define its parameters in key/value form
The parameters used by each layout class are certainly different, and you can look at the properties of each layout class, specifically.
Where patternlayout can use the Conversionpattern parameter to specify a format string
And you can specify a header parameter, a string that starts at the beginning of the log, footer to specify the trailing string
Here is a little trick, the beginning and end of the log always want to produce a carriage return, although logger write a log will be automatically enter, but the header and footer will not, how to do? With \n\r? (I've seen it on other people's blogs), \n\r will be the same as the original one. In fact, we can use the XML entity, using & #13;& #10; You can insert a carriage return line break at the specified location.

Finally, as the log4net document says, if you do not want your log files to become very large, so that the performance of reading and writing down, it is recommended that you still rank management log, the granularity is reduced, that is, in addition to the definition of root, and finally, for each module or each entity, depending on the purpose, purpose, The benefit of defining the respective logger configuration is that the log is dispersed and the log file grows less quickly. Each logger structure is exactly the same as root, which is no longer described here. As I said before, if you let the log generate hierarchical relationships, you can follow their Name property like C # The name of namespace in the same way.
To illustrate, the definition of logger is not necessary, just a suggestion, log4net configuration, in addition to the definition of a root and a appender, the others are optional

Another way to configure log4net is to configure it in a separate XML file, and at this point, simply copy the contents of the log4net tag and do not need to configsections

3, read the configuration in the application code
This is a very simple step, you can read the Log4net configuration in the application set's AssemblyInfo.cs file
For WinForm applications, you can join
[Assembly:log4net. Config.domconfigurator ()] or
[Assembly:log4net. Config.xmlconfigurator ()]
For WebForm you can join
[Assembly:log4net. Config.domconfigurator (configfile= "Web. config", Watch=true)]

Note: If you are using a NUnit test friend, to use the post-build event, copy "$ (projectdir) app. Config" "$ (TargetPath). config"

4. Get the Ilog object in the application
In classes that need to use the Logger feature, introduce log4net space and add static read-only members to the class (static purpose is to use only one object, read-only to prevent false changes)
private static readonly ILog Logger=logmanager.getlogger (typeof (Class))
Here you can get the logger object with the same name as the class name in the configuration file.

5, write Log
Very simple logger. Deub (Write content)
Other info,warn,error and so on, it's easy to understand.

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.