Log4net usage notes and log4net notes

Source: Internet
Author: User
Tags log4net

Log4net usage notes and log4net notes

1. Log4net features

 

1. Custom log output level

Log4net divides logs into five levels of priority from high to low: FATAL> ERROR> WARN> INFO> DEBUG, and ALL (allow ALL log requests) and OFF (reject all log requests. The log level can be used to control whether logs are output.

If the configuration file defines the INFO level, there are three logging methods in the program.

Log. Info ("Log Content"), Log. Warn ("Log Content"), Log. Debug ("Log Content ")

Log. Info and Log. Debug both output logs. Log. Warn does not output logs.

2. Custom log output mode

Log4net provides flexible Log output methods, including outputting logs to text files, consoles, emails, Windows Event logs, and databases. The following flexible configurations are available for writing logs to text files.

A. Print logs by time period. Scroll logs are printed by month, by day, by time, and by level as you configure B. Scroll logs are printed by file size, such as a log file every 10 MB or MB, this prevents the log file from being too large. The log file size reaches 4, which is hard to be opened after 5g. C. Specify the log size. For example, if the log size is 500 mb, only one log will be logged and will not exceed 500 mb.

 

 

Ii. Log4net Installation

 

1. Users can download the source code of log4net from the http://logging.apache.org/log4net.

2. decompress the package and load log4net. sln to Visual Studio. NET under the decompressed src directory. After compilation, you can obtain log4net. dll.

3. To add the log function to your program, you only need to introduce log4net. dll into the project.

 

3. Use log4net in the program

 

1. log4net configuration file and program Association

Log4net configurations can be stored in the default configuration file (app. config or web. config) of the application, or in the configuration file specified by yourself. In the log4net framework, log4net. Config. XmlConfigurator is used to define the configuration file at the Assembly level.

For example, find the Assemblyinfo. cs file of the current project and add the following line to associate it with the Web. config file.

[Assembly: log4net. Config. XmlConfigurator (ConfigFile = "Web. config", Watch = true)]

 

Assemblyinfo. cs configuration instructions

ConfigFile

The path and file name of our configuration file, including the extension.

ConfigFileExtension

If we use different file extensions for the compiled Assembly, we need to define this property. By default, the assembly configuration file extension is "config ".

Watch (Boolean attribute)

The log4net framework uses this attribute to determine whether to monitor file changes at runtime. If this attribute is true, FileSystemWatcher will be used to monitor file changes, renaming, deletion, and other events.

The ConfigFile and ConfigFileExtension attributes cannot be used at the same time. ConfigFile indicates the name of the configuration file.

 

 

Iv. Example of standard log4net Configuration documentation (web. config)

 

XML Code Replication
<?xmlversion="1.0"encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionname="log4net"
             type="log4net.Config.Log4NetConfigurationSectionHandler" />
  </configSections>
  <log4net>
    <root>
      <levelvalue="WARN" />
      <appender-refref="LogFileAppender" />
      <appender-refref="ConsoleAppender" />
    </root>
    <loggername="testApp.Logging">
      <levelvalue="DEBUG"/>
    </logger>
    <appendername="LogFileAppender"  type="log4net.Appender.FileAppender" >
      <paramname="File"value="log-file.txt" />
      <paramname="AppendToFile"value="true" />
      <layouttype="log4net.Layout.PatternLayout">
        <paramname="Header"value="[Header]&#13;&#10;"/>
        <paramname="Footer"value="[Footer]&#13;&#10;"/>
        <paramname="ConversionPattern"  value="%d [%t] %-5p %c[%x]  - %m%n" />
      </layout>
      <filtertype="log4net.Filter.LevelRangeFilter">
        <paramname="LevelMin"value="DEBUG" />
        <paramname="LevelMax"value="WARN" />
      </filter>
    </appender>
    <appendername="ConsoleAppender"   type="log4net.Appender.ConsoleAppender" >
      <layouttype="log4net.Layout.PatternLayout">
        <paramname="ConversionPattern"  value="%d [%t] %-5p %c [%x] -%m%n" />
      </layout>
    </appender>
  </log4net>
</configuration>

 

V. configuration file node description

 

1. Define section nodes in the configuration section. The node name must be log4net and case sensitive.

<ConfigSections>

<Sectionname = "log4net"

Type = "log4net. Config. Log4NetConfigurationSectionHandler"/>

</ConfigSections>

 

2. root Node description

 

(1) Root logger, which is inherited by all other logger by default. The root element has no attribute.

 

(2) supported child elements

Appender-ref: the name of the appender to be referenced.

The level can be at most one. Only events at this level or above will be recorded.

Param 0 or multiple. Set some parameters.

(3) 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.

 

3. Logger node description

 

(1) supported attributes: name and additi.pdf 

Required by name. logger name

Optional. The value is true or false. The default value is true. If it is set to false, the appender in the parent logger will be blocked.

 

(2) supported child elements

Appender-ref: the name of the appender to be referenced.

The evel can be at most one. Only events at this level or above will be recorded.

Param 0 or multiple. Set some parameters.

(3) The <logger> element predefines the setting of a specific log object.

Then, by calling the LogManager. GetLogger ("testAPP. Logging") function, you can retrieve logs with this name. If LogManager. GetLogger (...) If the log object is not a predefined log object, the log object inherits the attributes of the root log object. With this in mind, we can say that the <logger> label is not necessary.

 

4. Description of Appender nodes

 

(1) define the log output mode, which can only be used as log4netChild Element. The name attribute must be unique and the type attribute must be specified. The name and type attributes are supported.

Required by name. name of the Appender object

Required. The output type of the Appender object.

 

(2) supported child elements

Appender-ref: 0 or more. This appender can reference other appender types.

Filter 0 or more, which defines the filters used by this app.

Layout can be at most one. Define the output format used by the appender.

Param 0 or multiple. Set the value of the corresponding attribute in the Appender class.

 

(3) The Appender object in the <root> label or a single <logger> label can be defined using the <appender> label.

<Appender> the basic format of the tag is shown above. It defines the appender name and type. What's more important is other labels inside the <appender> tag. Different appender have different <param> labels. Here, to use FileAppender, you need a file name as the parameter. You also need to define a Layout object within the <appender> tag. The Layout object is defined in its own <layout> label. <Layout> the type attribute of a tag defines the Layout type (in this example, PatternLayout) and the parameter values to be provided. The Header and Footer labels provide the text output at the beginning and end of a log session (logging session. Examples of specific configurations for each appender can be obtained in the log4net \ doc \ manual \ example-config-appender.html.

 

5. Filter node description

 

Filter, which can only be a child element of <appender>.

Supported attributes:

Required. The Filter type.

Supported sub-elements: param 0 or more. Set some parameters.

 

6. Layout node description

Layout, which can only be a child element of <appender>.

Supported attributes:

Required. Layout type.

 

Supported Child elements: param 0 or more.

 

ConversionPattern in log4net. Layout. PatternLayout)

 

% M (message): the output Log message, such as ILog. Debug (...) Output Message

% N (new line): line feed

% D (datetime): time when the current statement is output

% R (run time): number of milliseconds consumed by the output program from running to executing to the current statement

% T (thread id): ID of the thread where the current statement is located

% P (priority): Current Log priority level, namely DEBUG, INFO, WARN... And so on

% C (class): name of the current log object, for example:

% L: the row number of the output statement

% F: File Name of the output statement

%-Number: indicates the minimum length of the item. If not, fill it with spaces.

 

For example

If the conversion mode is % r [% t] %-5 p % c-% m % n, PatternLayout generates output similar to the following:

176 [main] INFO org. foo. Bar-Located nearest gas station.

 

7. Param

 

<Param> How can an element be a child element.

 

Supported attributes:

Required. The value is the parameter name of the parent object.

(Optional) values and types must have an attribute specified. Value is a string that can be converted into a parameter value.

(Optional) values and types must have an attribute specified. Type is a type name. If type is not defined in the log4net program, you need to use the full name.


How to Use Log4Net in C ??

1. First, you must reference log4net.
2. Add log4net. config.
3. Add configuration items in log4net. config.
4. Use it in a program
ILog log = LogManager. GetLogger (typeof (Program ));
Log. Debug ("log information ");

C # When the class library uses log4net, the program calls the log4net configuration file path.

In assemblyInfo. cs of the class library, change:
[Assembly: log4net. Config. XmlConfigurator (Watch = true)]
Indicates that log4net obtains the configuration from the. config file of the application.

Assume that a TestApp application references the class library above, log4net obtains the configuration from the TestApp. config file according to the above modification. In this way, you can move the content of app. config of the original class library to app. confg of the TestApp Project (TestApp is automatically generated after the TestApp project is compiled ).

Hope to help you!
 

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.