Explain the use of log4net in detail

Time:2019-8-7

Only the log4net.dll file needs to be referenced in the program.

Reference to configuration


log4net.Config.XmlConfigurator.Configure();

First add the above code.

CS program: add in Maine method;

BS program: Application_Start method added;

Or both can add the following statement to the AssemblyInfo.cs (Properties) file:

// Set up a standalone configuration file, log4net.config
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config" , Watch = true )]
// Or the default configuration file
[assembly: log4net. Config. Xml Configurator (Watch = true)] (configured in web. config file)

Detailed configuration

Log4net, you can output the log to the console program, file, database, mail. The following four output configuration codes are pasted. The other output such as window log is not described.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <! - First add the configSections configuration node - >.
 <configSections>
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
 </configSections>
 <log4net><br>
  <root>
   <! - (High) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (Low) - - >
   <! - Restrict logging level - >
   <level value="all" />
   <! - Export the log to a file - >.
   <appender-ref ref="FileAppender"/>
   <! - Export logs to the application console - >
   <appender-ref ref="ConsoleAppender"/>
   <! - Write a log in an email - >.
   <!--<appender-ref ref="LogSmtpAppender"/>-->
   <! - Log to the database. You can use SQL and stored procedures in two ways - >.
   <appender-ref ref="AdoNetAppender"/>
   <! - Multiple output objects can be set at the same time, no comment can be used - >.
   <! -- Write the log to the local syslog service (for UNIX only). >
   <!--<appender-ref ref="LocalSyslogAppender"/>-->
  </root><br>
  <! - Send an email - >.
  <appender name="LogSmtpAppender" type="log4net.Appender.SmtpAppender">
   <authentication value="Basic" />
   <! - Mailbox for mail receipt - > E-mail for mail receipt, e-mail receipt, e-mail receipt, e-mail receipt, e-mail receipt, e-mail receipt.
   <to value="[email protected]" />
   <! - mailbox for sending mail
   <from value="[email protected]" />
   <! - mailbox for sending mail
   <username value="[email protected]" />
   <! - mailbox password for sending mail - >
   <password value="123456" />
   <! - Title - >
   <subject value="XXX application error log message"/>
   <!--smtp.qq.com-->
   <smtpHost value="smtp.126.com" />
   <bufferSize value="2048" />
   Whether the super-long part is discarded or not
   <lossy value="true" />
   <! - Email only if the log level is higher than WARN - >
   <evaluator type="log4net.Core.LevelEvaluator">
    <threshold value="ERROR"/>
   </evaluator>
   <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value=" %level :: %message %newlineLogger: %logger%newline Date: %date%newline" />
   </layout>
  </appender><br>
  <! - Console Log - >
  <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
   <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%n%d{yyyy-MM-dd HH:mm:ss} %m%n" />
   </layout>
   <! - Ranks within a specified range can only be recorded - >.
   <!--<filter type="log4net.Filter.LevelRangeFilter">
    <param name="LevelMin" value="Info" />
    <param name="LevelMax" value="Fatal" />
   </filter>-->
  </appender >
 
  <! - Specify the journal recording mode, scrolling the file (file recording)-->
  <appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
   <! - Log Path - >
   <param name= "File" value= "log/"/>
   <! - Is it adding a log to the file?
   <param name= "AppendToFile" value= "true"/>
   <! - log retention days - >
   <param name= "MaxSizeRollBackups" value= "10"/>
   <! - Maximum 1M per file
   <param name="maximumFileSize" value="1MB" />
   Whether the log file name is fixed or not
   <param name= "StaticLogFileName" value= "false"/>
   <! - The format of the log file name is: 2008-08-31.log-->.
   <param name= "DatePattern" value= "yyyy-MM-dd".log""/>
   <! - Log scrolls according to date - >
   <param name= "RollingStyle" value= "Date"/>
   <! - Layout - >
   <layout type="log4net.Layout.PatternLayout">
    <param name="Conversion pattern" value="% N recording time:% d{yyyyyy-MM-dd HH:m m:ss} thread name: [% t] level:% P Class name:% C information:% m% n" />
    <param name="Header" value="----------------------------------------------------------- "/>
   </layout>
  </appender><br>
  <! - Database Diary - >
  <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
   <! - Set it to 1 for easy viewing results. In performance considerations, the value here should be slightly larger. The official default value is 100, BufferSize is the size of the buffer, and only the log record overset value can be written to the database in one piece.
   <bufferSize value="1" />
   <! - SQL Server reference - >
   <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
   <! - Connect database string - >
   <connectionString value="data source=.;initial catalog=test;integrated security=false;persist security info=True;User ID=sa;Password=sqlserver;" />
   <! - Insert into table Log - >.
   <commandText value="INSERT INTO LogTest ([Date],[Level],[Logger],[Message],[Exception],[Description],[ObjType]) VALUES (@log_date,@log_level, @logger, @message, @exception,@Description,@ObjType)" />
   <! - All parameters - >
   <parameter>
    <parameterName value="@log_date" />
    <dbType value="DateTime" />
    <layout type="log4net.Layout.RawTimeStampLayout" />
   </parameter>
   <parameter>
    <parameterName value="@log_level" />
    <dbType value="String" />
    <size value="50" />
    <layout type="log4net.Layout.PatternLayout">
     <conversionPattern value="%level" />
    </layout>
   </parameter>
   <! - Where the class is located - >
   <parameter>
    <parameterName value="@logger" />
    <dbType value="String" />
    <size value="255" />
    <layout type="log4net.Layout.PatternLayout">
     <conversionPattern value="%logger" />
    </layout>
   </parameter>
   <parameter>
    <parameterName value="@message" />
    <dbType value="String" />
    <size value="4000" />
    <layout type="log4net.Layout.PatternLayout">
     <conversionPattern value="%message" />
    </layout>
   </parameter>
   <parameter>
    <parameterName value="@exception" />
    <dbType value="String" />
    <size value="2000" />
    <layout type="log4net.Layout.ExceptionLayout" />
   </parameter>
   <! - Custom input fields - >
   <parameter>
    <parameterName value = "@Description"/>
    <dbType value = "String"/>
    <size value = "50"/>
    <layout type = "log4_Test.Log4netExpand.ExpandLayout">
    <conversionPattern value = "%property{Description}"/>
    </layout>
   </parameter>
   <parameter>
    <parameterName value = "@ObjType"/>
    <dbType value = "String"/>
    <size value = "50"/>
    <layout type = "log4_Test.Log4netExpand.ExpandLayout">
     <conversionPattern value = "%property{ObjType}"/>
    </layout>
   </parameter>
  </appender>
 
 </log4net>
</configuration>

<layout type = log4_Test.Log4netExpand.ExpandLayout> log4_Test.Log4netExpand is the namespace

Layout, Format Character Description:

% p: Priority of output log information, namely DEBUG, INFO, WARN, ERROR, FATAL.
% d: The date or time of the output log time point, the default format is ISO8601, can also be specified later, such as:% D {yyyyy/MM/d D HH: mm: ss, SSS}.
% r: The number of milliseconds it takes to output the log information from the start of the application.
% t: Output the thread name that generated the log event.
% l: The location where the output log event occurs is equivalent to a combination of% C.% M (% F:% L), including the full class name, method, file name, and the number of lines in the code. For example: test. TestLog4j. main (TestLog4j. java: 10).
% c: The category to which the output log information belongs is usually the full name of the class in which it belongs.
% M: Output the name of the method that generates log information.
% F: The name of the file where the output log message was generated.
% L:: Line numbers in the output code.
% m:: Output the specific log information specified in the code.
% n: Output a return line break, Windows platform is ” r n”, Unix platform is ” n”.
% x: Output NDC (nested diagnostic environment) associated with the current thread, especially for multi-client, multi-threaded applications such as Java servlets.
%% Output a “%” character.
In addition, modifiers can be added between% and format characters to control their minimum length, maximum length, and text alignment. Such as:
1)% 20c: Specify the name of the output category. The minimum length is 20. If the name length of the category is less than 20, align it right by default.
2)%-20c:”-” indicates left alignment.
3)%. 30c: Specify the name of the output category. The maximum length is 30. If the name of the category is longer than 30, the extra characters on the left will be truncated, but no spaces will be filled if the name is less than 30.

Custom database insert fields (from network collection, collation)

1. Define a LogData class first:

namespace log4_Test.Log4netExpand
{
  public class LogData
  {
    /// <summary>
    /// Log Description Information
    /// </summary>
    public string Description { get; set; }
    /// <summary>
    /// Log Description Information
    /// </summary>
    public string ObjType { get; set; }
  }
}

2. Layout extension class


namespace log4_Test.Log4netExpand
{
  public class ExpandLayout : PatternLayout
  {
    public ExpandLayout()
    {
       this.AddConverter("property", typeof(MyMessagePatternConverter));
    }
  }
}

3. MyMessagePatternConverter class

namespace log4_Test.Log4netExpand
{
  public class MyMessagePatternConverter: PatternLayoutConverter
  {
    protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
    {

      if (Option != null)
      {

        // Write the value for the specified key

        WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));

      }
      else
      {

        // Write all the key value pairs

        WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());

      }
    }
    /// <summary>
    /// Getting the value of an attribute of the incoming log object by reflection
    /// </summary>
    /// <param name="property"></param>
    /// <returns></returns>
    private object LookupProperty(string property, log4net.Core.LoggingEvent loggingEvent)
    {
      object propertyValue = string.Empty;
      PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);
      if (propertyInfo != null)
      {
        propertyValue = propertyInfo.GetValue(loggingEvent.MessageObject, null);
      }
      return propertyValue;

    }
  }
}

4. The code is as follows:

public class Program
  {
    static void Main(string[] args)
    {
      
      // You can see the output of that class.
      ILog logger = log4net.LogManager.GetLogger(typeof(Program));

      logger.Info(new LogData { Description="123", ObjType="123"})
     
      Logger. Info ("Message 11111111111111111111111111111");
      Logger. Warn ("Warning");
      Logger. Error ("exception");
      Logger. Fatal ("error");
     
    }
  }

The above is a detailed integration of the use of log4net introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support to developpaer.