SoFunction
Updated on 2025-05-09

Detailed introduction to the configuration file configuration items of C# log4net (configuration example)

log4netIt is a powerful logging tool. Through configuration files, you can flexibly control the output method, format, level, etc. of the log. The following is correctlog4netDetailed introduction to common configuration items in configuration files:

Root element <log4net>

This islog4netThe root element of the configuration file, all configuration items must be included in this element.

&lt;log4net&gt;
    &lt;!-- Other configuration items --&gt;
&lt;/log4net&gt;

Appenders<appender>

The appender is used to specify the output target of the log, such as files, consoles, databases, etc.log4netA variety of built-in add-ons are provided, and you can also customize them. Each appendix has a unique name, which can be passednameProperties are specified.

1. ConsoleAppender

Output the log to the console.

<appender name="ConsoleAppender" type="">
    <layout type="">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
</appender>
  • type: Specify the type of the appendix, here is
  • <layout>: Define the output format of the log, usePatternLayoutCan customize the format,conversionPatternSpecify the specific format string.
  • existIn  , the format of log output can be customized with the conversion mode string, which is composed of a series of markers. The following is a detailed introduction to the commonly used marks and their uses:

Basic information marking

  • %date: The date and time of the output log record, the default format isyyyy-MM-dd HH:mm:ss,fff, can be passed%date{format}To specify the format, like%date{HH:mm:ss}%level: The level of output log (for exampleDEBUGINFOWARNERRORFATAL)。
  • %logger: Output the logger name of the log.%message: Output the specific message content of the log.
  • %newline: Output a newline character.

Thread and context tags

  • %thread: Output the name of the thread that generates the logging.
  • %property{name}: Output the value of the specified name in the thread context property. For example, you can set it in the code["UserName"] = "John";, then use%property{UserName}Output.

Class and method tags

  • %class: Output the fully qualified name of the class that records the log.
  • %method: Output the method name of the log record.

Location information mark

  • %file: Output the source file name of the log record.
  • %line: Output the line number where the code that records the log is located.

Stack trace tags

  • %exception: Output exception stack trace information, usually used forERRORorFATALLevel log.

2. File appender (FileAppender and RollingFileAppender)

Output the log to a file.RollingFileAppenderSupports file scrolling, and when the file reaches a certain size or date changes, a new log file will be created.

<appender name="RollingFileAppender" type="">
    <file value="logs\" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="10MB" />
    <staticLogFileName value="true" />
    <layout type="">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
</appender>
  • <file>: Specify the path and name of the log file.
  • <appendToFile>: Set whether to append logs to existing files.
  • <rollingStyle>: Specify the file scrolling method, optional values ​​areSize(Scroll by file size),Date(Scroll by date) etc.
  • <maxSizeRollBackups>: Specifies the maximum number of old log files to be retained.
  • <maximumFileSize>: Specify the maximum size of each log file.
  • <staticLogFileName>: Set whether to use static log file names.

3. Database Attacher (AdoNetAppender)

Store logs into the database.

&lt;appender name="AdoNetAppender" type=""&gt;
    &lt;bufferSize value="1" /&gt;
    &lt;connectionType value=", , Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /&gt;
    &lt;connectionString value="Data Source=SERVER_NAME;Initial Catalog=DATABASE_NAME;User ID=USERNAME;Password=PASSWORD" /&gt;
    &lt;commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" /&gt;
    &lt;parameter&gt;
        &lt;parameterName value="@log_date" /&gt;
        &lt;dbType value="DateTime" /&gt;
        &lt;layout type="" /&gt;
    &lt;/parameter&gt;
    &lt;parameter&gt;
        &lt;parameterName value="@thread" /&gt;
        &lt;dbType value="String" /&gt;
        &lt;size value="255" /&gt;
        &lt;layout type=""&gt;
            &lt;conversionPattern value="%thread" /&gt;
        &lt;/layout&gt;
    &lt;/parameter&gt;
    &lt;!-- Other parameters --&gt;
&lt;/appender&gt;
  • <bufferSize>: Specifies the buffer size of the log record.
  • <connectionType>: Specify the database connection type.
  • <connectionString>: Specify the database connection string.
  • <commandText>: Specifies the SQL statement to insert log records.
  • <parameter>: Define parameters in SQL statements, including parameter names, data types, and layout.

Loggers<logger>and<root>

Loggers are used to control the log output levels and the appendix used for different namespaces or classes.

1. Root Logger<root>

The root logger is the parent logger of all loggers, setting the default log level and add-on for the entire application.

<root>
    <level value="ALL" />
    <appender-ref ref="ConsoleAppender" />
    <appender-ref ref="RollingFileAppender" />
</root>
  • <level>: Specify the output level of the log, optional values ​​areALLDEBUGINFOWARNERRORFATALOFF
  • <appender-ref>: Refer to the appendix to be used, throughrefThe attribute specifies the name of the appendix.

2. Custom Logger<logger>

Setting log levels and appenders for a specific namespace or class overrides the settings of the root logger.

<logger name="">
    <level value="DEBUG" />
    <appender-ref ref="ConsoleAppender" />
</logger>
  • name: Specifies the name of the logger, usually the fully qualified name of the namespace or class.
  • <level>and<appender-ref>The function is the same as in the root recorder.

Filters<filter>

Filters are used to filter log records based on specific conditions, allowing only log records that meet the conditions to pass. Common filters areLevelMatchFilterLevelRangeFilterwait.

<appender name="ConsoleAppender" type="">
    <filter type="">
        <levelMin value="INFO" />
        <levelMax value="ERROR" />
    </filter>
    <layout type="">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
</appender>
  • <filter>: Specify the type of filter.
  • <levelMin>and<levelMax>: Specify the range of the log level, and only log records within that range will be output.

Configuration example

Here is a complete onelog4netConfiguration file example:

<log4net>
    <appender name="ConsoleAppender" type="">
        <layout type="">
            <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
        </layout>
    </appender>
    <appender name="RollingFileAppender" type="">
        <file value="logs\" />
        <appendToFile value="true" />
        <rollingStyle value="Size" />
        <maxSizeRollBackups value="10" />
        <maximumFileSize value="10MB" />
        <staticLogFileName value="true" />
        <layout type="">
            <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
        </layout>
    </appender>
    <root>
        <level value="ALL" />
        <appender-ref ref="ConsoleAppender" />
        <appender-ref ref="RollingFileAppender" />
    </root>
</log4net>

This configuration file outputs logs to the console and file at the same time, and the log level isALL, that is, output logs of all levels.

Through reasonable configurationlog4netThe configuration file can meet the logging needs in different scenarios.

This is the end of this article about the detailed introduction of C# log4net configuration items (configuration examples). For more related C# log4net configuration files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!