Log4net Five steps away

Source: Internet
Author: User
Tags system log log4net

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 > <  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> < Levelvalue= "All" /> <Appender-refref= "Rollingfile" /> </Root> <Appendername= "Rollingfile"type= "log4net." Appender.rollingfileappender,log4net " > <paramname= "File"value= "Log.txt" /> <paramname= "Appendtofile"value= "false" /> <paramname= "Rollingstyle"value= "Date" /> <paramname= "Datepattern"value= "yyyy." Mm.dd " /> <paramname= "Staticlogfilename"value= "true" /> <Layouttype= "log4net." Layout.patternlayout,log4net ">  <paramname= "Conversionpattern"value= "%d [%t]%-5p%c-%m%n" />  <paramname= "Header"value= "& #13;& #10;----------------------header--------------------------& #13;& #10;" />  <paramname= "Footer"value= "& #13;& #10;----------------------footer--------------------------& #13;& #10;" /> </Layout> </Appender>  <Appendername= "ConsoleApp"type= "log4net." Appender.consoleappender,log4net ">   <Layouttype= "log4net." Layout.patternlayout,log4net ">     <paramname= "Conversionpattern"value= "%d [%t]%-5p%c-%m%n" />  </Layout> </Appender>  <Loggername= "Log4nettest.logtest">  < Levelvalue= "DEBUG" />  <Appender-refref= "Rollingfile" />  <Appender-refref= "Coloredconsoleapp" />  <Appender-refref= "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-refref="" /></Root> <Appendername=""type= "Fully qualified class name for Appender"> <paramname=""value="" /> <Layouttype= "log4net." Layout.patternlayout,log4net ">  <paramname=""value="" /> </Layout> </Appender> <Logger> < Levelvalue="" /> <Appender-refref="" /></Logger>

I don't understand. Log4net is the root tag of the Log4net configuration section defines a root-level logger, Log4net's loggers are hierarchically organized, and two logger,a are named Loggera,b. Then B is the son of a, B will automatically inherit some definitions of a, such as level definition, appender-ref definition, root is the total logger, the rest of the definition of logger are his descendants, will inherit his settings

Every logger, including root (root is also a logger, except that he is an ancestor, other aspects, as with other logger), can define level levels to define the log of records, that is, which level of log you want to record, 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 responsible for the log Appender provides the recording of the media layout is responsible for the contents of the formatted 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 issued record information, Appender received information, according to the internal layout configuration to the record information format, according to filter to determine whether this information is filtered out, and finally, serialization

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

Each appender represents an output Medium Name property specifies its name, and type is log4net. The name of a class for the Appender namespace, which means that there are more than 10 types of log4net support for specifying which media to use, the most commonly used are rollingfileappender,adonetappender, Eventlogappender,fileappender, log into the file, System log and database in addition, the other parameters in the Appender are marked with Param, in the form of key/value defined in it here is a small hint, Every appender,log4net doesn't ask what parameters they need in a document, so how do we know? Originally, the name of these param, 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 a logname,applicationname attribute, then, means that You can add the following directly to this appender param:

<name= "LogName"  value= "Application"/>< 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, Reference to its logger in writing to the log, is written to the Appender defined in the media to a logger can refer to multiple appender, the result is that the same log, is simultaneously logged to multiple media, such as, at the same time sending mail, write system log, Sent to the remote host. However, although you can do this, but be careful, because, will have a certain impact on performance, unless you need, 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, You can't use simplelayout. Layout uses param to define its parameters in key/value form the parameters used by each layout class are different, of course, you can see the properties of each layout class. Patternlayout can use the Conversionpattern parameter to specify a format string and can specify a header parameter, as a string at the beginning of the log, footer to specify the end string here's a little tip. The beginning and end of the log always want to produce a carriage return, although logger write a log will 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 # In the name of the namespace that can be explained that the definition of logger is not necessary, but 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, in the application code to read the configuration This step is very simple, you can read the log4net configuration in the AssemblyInfo.cs file of the application set for WinForm application, 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 the class that needs to use the Logger feature, introduce log4net space, add static read-only members to the class (static purpose is to use only one object, read-only to prevent mis-change) 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 is 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.