.net uses the log4net logging framework (logging to the database)

Posted by ramez_sever on Wed, 09 Feb 2022 00:29:06 +0100

Document the use of the log4net logging framework in your project:

1. Install Log4net package via Nuget

 

2. Add configuration files, configure the format of log records, etc.

Log4net. The config configuration information is as follows:

<?xml version="1.0" encoding="utf-8"?>

<log4net>

  <!--type Indicates what type of log to log with ADONetAppender Representational database records-->
  <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
    <!--Number of log cache writes to database immediately if 0-->
    <bufferSize value="0"/>

    <!--Log Database Connection String-->
    <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

    <!--Database Connection String-->
    <connectionString value="Data Source=.;Initial Catalog=stuDb;User ID=sa;password=123456"/>

    <!--Log database script-->
    <commandText value="insert into LogDetails (LogDate,LogLevel,Thread,Logger,LogMessage) values (@log_date,@log_level,@thread,@logger,@message)"/>

    <!--Log Time RawTimeStampLayout yes log4net Provided parameters-->
    <parameter>
      <parameterName value="@log_date"/>
      <dbType value="DateTime"/>
      <layout type="log4net.Layout.RawTimeStampLayout"/>
    </parameter>

    <!--log level-->
    <parameter>
      <parameterName value="@log_level"/>
      <dbType value="String"/>
      <size value="20"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%p" />
      </layout>
    </parameter>

    <!--thread ID-->
    <parameter>
      <parameterName value="@thread"/>
      <dbType value="String"/>
      <size value="100"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%thread" />
      </layout>
    </parameter>

    <!--Log Name-->
    <parameter>
      <parameterName value="@logger"/>
      <dbType value="String"/>
      <size value="500"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%logger" />
      </layout>
    </parameter>

    <!--Log Content-->
    <parameter>
      <parameterName value="@message"/>
      <dbType value="String"/>
      <size value="3000"/>
      <layout type="Log4NetToSqlServer.Utility.CustomLayout">
        <conversionPattern value="%property{Message}" />
      </layout>
    </parameter>

  </appender>


  <root>
    <appender-ref ref="AdoNetAppender" />
  </root>


</log4net>



Log content field, the value of the @message parameter is custom, refers to the log content to be logged, and the parameter value is passed in from where it was called. (The Log4NetToSqlServer.Utility.CustomLayout class needs to be created by itself, and the code is in the third step below)

The other fields are log4net encapsulated directly from log4net. Layout. Get in the PatternLayout class.

 

Remember to add the new log4net. The config file is set to always copy, which is a critical step. If not set, the program will not find the config file at run time. (

The SqlServer database is used in the configuration file above. Other database configurations can be referred to: http://logging.apache.org/log4net/release/config-examples.html

 

3. Methods needed to encapsulate custom field values

Start by creating a Utility folder in your project that holds the code for the associated help class.

Next, create the following four classes:

CustomLayout.cs

  public class CustomLayout : PatternLayout
    {
        //The constructor adds the specified fields that need to be written to the database
        public CustomLayout()
        {
            this.AddConverter("property", typeof(LogInfoPatternConverter));
        }
    }

LogContent.cs

 public class LogContent
    {
        public LogContent(string message)
        {
            Message = message;
        }

        /// <summary>
        ///Log Description Information
        /// </summary>
        public string Message { get; set; }
    }

LogHelper.cs

 public class LogHelper
    {
        public static readonly ILog ilog = LogManager.GetLogger("TestDataBase.Log");

        public static void Info(LogContent content)
        {
            ilog.Info(content);
        }

        public static void Error(LogContent content, Exception ex)
        {
            ilog.Error(content, ex);
        }

        public static void Warn(LogContent content)
        {
            ilog.Warn(content);
        }

        public static void Fatal(LogContent content)
        {
            ilog.Fatal(content);
        }

        public static void Debug(LogContent content)
        {
            ilog.Debug(content);
        }


    }

LogInfoPatternConverter.cs

 public class LogInfoPatternConverter : PatternLayoutConverter
    {
        protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            if (Option != null)
            {
                //Writes the value of the specified key
                WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
            }
            else
            {
                WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
            }
        }

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

    }

The above code implements log4net. Parameter passing function for @message field in config configuration file.

If you want to add other custom parameter fields, you can do so directly in LogContent. Add fields to cs, for example, to record the name of the operator, you can modify the code to:

Also requires log4net. Modify sql statements and add corresponding configuration nodes in config:


 

4. Edit Assemblyinfo in the Properties folder of the project. CS (AssemblyInfo.cs is generated automatically when a project is created, mainly to set some parameters of the generated dll file for general information about the assembly)

In Assemblyinfo. At the bottom of cs, add the following code:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Configs\\log4net.config", Watch = true)]

The purpose is to specify a configuration file to read log4net by reflecting, registering the configuration globally. (

 

5. Add log tables to the database:

create table LogDetails(
	logID int identity(1,1) not null,
	LogDate datetime not null,
	LogLevel nvarchar(20) not null,
	Thread nvarchar(20) not null,
	Logger nvarchar(20) not null,
	LogMessage nvarchar(3000) not null,
	constraint PK_LogDetails primary key NONCLUSTERED  (
	   logID asc
	)
)

 

6. Write different levels of logs

 

Start the program and you can see that the log tables in the database record relevant log information.

 

In addition to logging to the database, you can also log in text for reference: https://blog.csdn.net/liangmengbk/article/details/117187410

Topics: ASP.NET C# SQL Server log4net