Log4net five steps

Source: Internet
Author: User
Tags log4net

This article does not teach you a full understanding of log4net. It just wants to teach you how to use log4net
1. Introduce the log4net. dll component.
2. Create a configuration file
Either method is in Web. config or app. config.
Add the following configuration section
<Configsections>
<Section name = "log4net" type = "log4net. config. log4netconfigurationsectionhandler, log4net"/>
</Configsections>
In the configuration section above, you can use the copy function.

Add the definition of log4net configuration content, followed by the above content definition in the config file. The following is an example:
<Log4net>
<Root>
<Level value = "all"/>
<Appender-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] %-5 p % 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 = "leleapp" type = "log4net. appender. leleappender, log4net">
<Layout type = "log4net. layout. patternlayout, log4net">
<Param name = "conversionpattern" value = "% d [% T] %-5 p % C-% m % N"/>
</Layout>
</Appender>
<Logger name = "log4nettest. logtest">
<Level value = "debug"/>
<Appender-ref = "rollingfile"/>
<Appender-ref = "coloredconsoleapp"/>
<Appender-ref = "systemevent"/>
</Logger>
</Log4net>
If you are too lazy to write, you can copy the above content.
However, the XSD layers in the log4net configuration Section are as follows:

<Log4net>
<Root> <level/> <appender-ref = ""/> </root>
<Appender name = "" type = "fully qualified appender class name">
<Param name = "" value = ""/>
<Layout type = "log4net. layout. patternlayout, log4net">
<Param name = "" value = ""/>
</Layout>
</Appender>
<Logger>
<Level value = ""/>
<Appender-ref = ""/>
</Logger>
Why not? It's actually quite easy.
Log4net is the root flag of the log4net configuration section.
The root mark defines a root-level recorder. log4net recorder uses hierarchical structure. Two logger, A is called loggera, and B is called loggera. b, B is the son of A. B will automatically inherit some definitions of A, such as level definition and appender-ref definition. Root is the total logger, the other defined logger is his descendant and will inherit his settings.

Each logger, including root, (root is also a logger, but it is only an ancestor. In other aspects, like other logger), can define a level.
Level defines the Log Level of the record, that is, the log level above which you want to record, the level from high to low is:
None
Fatal
Error
Warn
Debug
Info
All

Note that if you define debug, the information below the debug level will not be logged. What do you mean? That is to say, even if you use log.info () in the program to write a log, but you specify the level as debug in the configuration, because the info level is lower than debug, logs are not recorded. this process is flexible.

Another configuration of logger is appender-Ref. Ref is a reference. The log4net architecture is very interesting, and the scalability is very high. It is divided into four elements:
Logger
Appender
Layout
Filter

Logger is the log recorder.
Appender provides Recording Media
Layout is responsible for formatting the recorded content
Filter filters content.

It can be said that the entire process is a log pipeline, and each member is responsible for one of the links.
Logger sends the record information, and appender receives the information. It formats the record information according to the internal layout configuration, determines whether the information is filtered out based on the filter, and finally serializes it.

Therefore, the logger appender-ref defines who the logger is looking for to write the content to disks, streams, or other media. Therefore, it is very important.
Since it is a ref reference, you must define the referenced appender object.

Each appender represents an output medium.
The name attribute specifies its name, and type indicates the name of a class in the log4net. appender namespace. This indicates the media used.
Log4net supports more than a dozen appender types. The most common types are rollingfileappender, adonetappender, eventlogappender, and fileappender. logs are respectively recorded in files, system logs, and databases.
In addition, other parameters in appender are marked with Param and defined as key/value.
Here is a small tip: Every appender and log4net does not specify the parameters they need in the document. How do we know?
It turns out that you can directly query the attribute names of the corresponding appender class for these Param names. For example, when using eventlogappender, we know that it has
LOGNAME, applicationname attribute, which means that you can directly Add the following content to the appender's Param:
<Param name = "LOGNAME" value = "application"/>
<Param name = "applicationname" value = "log4nettest"/>

After the appender name and type attributes are defined and Param is used to specify parameters for them, an appender is created, you can use his name to reference it in <appender-ref of logger. Then, the logger that references it writes to the media defined in appender when writing logs.
A logger can reference multiple appender. The result is that the same log is recorded in multiple media at the same time, such as sending an email at the same time, writing the system log, and sending it to a remote host. however, although this can be done, you should be careful, because it will have a certain impact on the performance, unless you need it, do not use this function indiscriminately

In addition, you can define the optional layout in the appender. The layout definition is very necessary. If you do not want to see your logs in the future, you may feel dizzy. Although log4net helps you write logs, the log information format is customized by our users.
The type parameter of layout specifies the definition of the class to be used for formatting. Commonly Used types include xmllayout, simplelayout, and patternlayout. Of course, you need to select the type based on your needs and the format you want to generate, if you want to output the file in XML format, you must not use simplelayout.
Layout uses Param to define its parameters in the form of key/value
The parameters used by each layout class are certainly different. For details, you can view the attributes of each layout class.
The conversionpattern parameter can be used to specify a format string.
And you can specify a header parameter as a string starting with the log. footer can specify the end string.
Here is a tip. I always want to generate a carriage return when I start or end a log. Although the logger will automatically press Enter when writing a log, but the header and footer won't, what should I do? Use \ n \ r? (I have seen it from others' blogs) In practice, \ n \ r will change the log as it is and will not convert it at all. in fact, we can use XML entities and use & amp; #13; & amp; #10; To insert a line break at the specified position.

Finally, as described in the log4net documentation, if you do not want your log files to become large and the read/write performance may degrade, we recommend that you manage logs hierarchically, to reduce the granularity, in other words, apart from defining the root, each module or every entity is defined based on the purpose and purpose of the logger configuration, the advantage is that logs are dispersed, and the log file growth is not so fast. the structure of each logger is exactly the same as that of root. as mentioned above, if you create a hierarchical relationship with logs, you can name them with their name attributes like the namespace in C #.
It should be noted that the logger definition is optional and is only a suggestion. In the log4net configuration, apart from defining a root and an appender, all other configurations are optional.

Another method for configuring log4net is to configure it in a separate XML file. At this time, you only need to copy the content in the log4net tag and do not need configsections.

3. Read the configuration in the application code
This step is very simple. You can read the log4net configuration in the assemblyinfo. CS file of the application assembly.
For winform applications, you can add
[Assembly: log4net. config. domconfigurator ()] or
[Assembly: log4net. config. xmlconfigurator ()]
For webform, you can add
[Assembly: log4net. config. domconfigurator (configfile = "Web. config", watch = true)]

Note: If you are using a nunit test friend, use the generated event, copy "$ (projectdir) app. config" "$ (targetpath). config"

4. Get the ilog object in the Application
Introduce the log4net space in the class that requires the logger function, and add static read-only members to the class (static purpose is to use only one object, and read-only is to prevent incorrect modification)
Private Static readonly ilog logger = logmanager. getlogger (typeof (class ))
You can obtain the logger object with the same name as the class in the configuration file.

5. Write logs
Very simple logger. deub (written content)
Others include info, warn, and error, which are easy to understand.

This article does not teach you a full understanding of log4net. It just wants to teach you how to use log4net
1. Introduce the log4net. dll component.
2. Create a configuration file
Either method is in Web. config or app. config.
Add the following configuration section
<Configsections>
<Section name = "log4net" type = "log4net. config. log4netconfigurationsectionhandler, log4net"/>
</Configsections>
In the configuration section above, you can use the copy function.

Add the definition of log4net configuration content, followed by the above content definition in the config file. The following is an example:
<Log4net>
<Root>
<Level value = "all"/>
<Appender-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] %-5 p % 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 = "leleapp" type = "log4net. appender. leleappender, log4net">
<Layout type = "log4net. layout. patternlayout, log4net">
<Param name = "conversionpattern" value = "% d [% T] %-5 p % C-% m % N"/>
</Layout>
</Appender>
<Logger name = "log4nettest. logtest">
<Level value = "debug"/>
<Appender-ref = "rollingfile"/>
<Appender-ref = "coloredconsoleapp"/>
<Appender-ref = "systemevent"/>
</Logger>
</Log4net>
If you are too lazy to write, you can copy the above content.
However, the XSD layers in the log4net configuration Section are as follows:

<Log4net>
<Root> <level/> <appender-ref = ""/> </root>
<Appender name = "" type = "fully qualified appender class name">
<Param name = "" value = ""/>
<Layout type = "log4net. layout. patternlayout, log4net">
<Param name = "" value = ""/>
</Layout>
</Appender>
<Logger>
<Level value = ""/>
<Appender-ref = ""/>
</Logger>
Why not? It's actually quite easy.
Log4net is the root flag of the log4net configuration section.
The root mark defines a root-level recorder. log4net recorder uses hierarchical structure. Two logger, A is called loggera, and B is called loggera. b, B is the son of A. B will automatically inherit some definitions of A, such as level definition and appender-ref definition. Root is the total logger, the other defined logger is his descendant and will inherit his settings.

Each logger, including root, (root is also a logger, but it is only an ancestor. In other aspects, like other logger), can define a level.
Level defines the Log Level of the record, that is, the log level above which you want to record, the level from high to low is:
None
Fatal
Error
Warn
Debug
Info
All

Note that if you define debug, the information below the debug level will not be logged. What do you mean? That is to say, even if you use log.info () in the program to write a log, but you specify the level as debug in the configuration, because the info level is lower than debug, logs are not recorded. this process is flexible.

Another configuration of logger is appender-Ref. Ref is a reference. The log4net architecture is very interesting, and the scalability is very high. It is divided into four elements:
Logger
Appender
Layout
Filter

Logger is the log recorder.
Appender provides Recording Media
Layout is responsible for formatting the recorded content
Filter filters content.

It can be said that the entire process is a log pipeline, and each member is responsible for one of the links.
Logger sends the record information, and appender receives the information. It formats the record information according to the internal layout configuration, determines whether the information is filtered out based on the filter, and finally serializes it.

Therefore, the logger appender-ref defines who the logger is looking for to write the content to disks, streams, or other media. Therefore, it is very important.
Since it is a ref reference, you must define the referenced appender object.

Each appender represents an output medium.
The name attribute specifies its name, and type indicates the name of a class in the log4net. appender namespace. This indicates the media used.
Log4net supports more than a dozen appender types. The most common types are rollingfileappender, adonetappender, eventlogappender, and fileappender. logs are respectively recorded in files, system logs, and databases.
In addition, other parameters in appender are marked with Param and defined as key/value.
Here is a small tip: Every appender and log4net does not specify the parameters they need in the document. How do we know?
It turns out that you can directly query the attribute names of the corresponding appender class for these Param names. For example, when using eventlogappender, we know that it has
LOGNAME, applicationname attribute, which means that you can directly Add the following content to the appender's Param:
<Param name = "LOGNAME" value = "application"/>
<Param name = "applicationname" value = "log4nettest"/>

After the appender name and type attributes are defined and Param is used to specify parameters for them, an appender is created, you can use his name to reference it in <appender-ref of logger. Then, the logger that references it writes to the media defined in appender when writing logs.
A logger can reference multiple appender. The result is that the same log is recorded in multiple media at the same time, such as sending an email at the same time, writing the system log, and sending it to a remote host. however, although this can be done, you should be careful, because it will have a certain impact on the performance, unless you need it, do not use this function indiscriminately

In addition, you can define the optional layout in the appender. The layout definition is very necessary. If you do not want to see your logs in the future, you may feel dizzy. Although log4net helps you write logs, the log information format is customized by our users.
The type parameter of layout specifies the definition of the class to be used for formatting. Commonly Used types include xmllayout, simplelayout, and patternlayout. Of course, you need to select the type based on your needs and the format you want to generate, if you want to output the file in XML format, you must not use simplelayout.
Layout uses Param to define its parameters in the form of key/value
The parameters used by each layout class are certainly different. For details, you can view the attributes of each layout class.
The conversionpattern parameter can be used to specify a format string.
And you can specify a header parameter as a string starting with the log. footer can specify the end string.
Here is a tip. I always want to generate a carriage return when I start or end a log. Although the logger will automatically press Enter when writing a log, but the header and footer won't, what should I do? Use \ n \ r? (I have seen it from others' blogs) In practice, \ n \ r will change the log as it is and will not convert it at all. in fact, we can use XML entities and use & amp; #13; & amp; #10; To insert a line break at the specified position.

Finally, as described in the log4net documentation, if you do not want your log files to become large and the read/write performance may degrade, we recommend that you manage logs hierarchically, to reduce the granularity, in other words, apart from defining the root, each module or every entity is defined based on the purpose and purpose of the logger configuration, the advantage is that logs are dispersed, and the log file growth is not so fast. the structure of each logger is exactly the same as that of root. as mentioned above, if you create a hierarchical relationship with logs, you can name them with their name attributes like the namespace in C #.
It should be noted that the logger definition is optional and is only a suggestion. In the log4net configuration, apart from defining a root and an appender, all other configurations are optional.

Another method for configuring log4net is to configure it in a separate XML file. At this time, you only need to copy the content in the log4net tag and do not need configsections.

3. Read the configuration in the application code
This step is very simple. You can read the log4net configuration in the assemblyinfo. CS file of the application assembly.
For winform applications, you can add
[Assembly: log4net. config. domconfigurator ()] or
[Assembly: log4net. config. xmlconfigurator ()]
For webform, you can add
[Assembly: log4net. config. domconfigurator (configfile = "Web. config", watch = true)]

Note: If you are using a nunit test friend, use the generated event, copy "$ (projectdir) app. config" "$ (targetpath). config"

4. Get the ilog object in the Application
Introduce the log4net space in the class that requires the logger function, and add static read-only members to the class (static purpose is to use only one object, and read-only is to prevent incorrect modification)
Private Static readonly ilog logger = logmanager. getlogger (typeof (class ))
You can obtain the logger object with the same name as the class in the configuration file.

5. Write logs
Very simple logger. deub (written content)
Others include info, warn, and error, which are 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.