How to Use the log4Net custom property configuration function to record the complete log information, log4net custom
As a professional log record control, log4Net is familiar with its powerful functions. The following describes in detail how to use its custom attributes to make log information more complete.
1. Create a test project. The log4Net component can be downloaded from the Internet or installed through Nuget.
2. Create a log model and a database table because our log information can be output as text or to the database.
3. Add the MyLayout and MyPatternConverter class extension PatternLayout.
4. Add the Log4Net. config file and define the input mode.
<? Xml version = "1.0" encoding = "UTF-8"?>
<Configuration>
<ConfigSections>
<Section name = "log4net" type = "log4net. Config. Log4NetConfigurationSectionHandler, log4net"/>
</ConfigSections>
<Log4net>
<! -- ConversionPattern
% M (message): the output Log message, such as ILog. Debug (...) Output Message
% N (new line): bytes row
% 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
% 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.
-->
<! -- Define output to console command line -->
<Logger name = "myLogger">
<Level value = "ALL"/>
<Appender-ref = "leleappender"/>
</Logger>
<! -- Define output to console command line -->
<Appender name = "leleappender" type = "log4net. Appender. ConsoleAppender">
<Layout type = "Log4NetTest. MyLayout">
<Param name = "ConversionPattern" value = "log time: % d % n log level: %-5 p % n user ID: % Property {UserID} % n User name: % Property {UserName} % n log information: % Property {Message} % n exception information: % exception % n "/>
</Layout>
</Appender>
<! -- Define output to windows events -->
<Appender name = "WindowsAppender" type = "log4net. Appender. EventLogAppender">
<Layout type = "Log4NetTest. MyLayout">
<Param name = "ConversionPattern" value = "log time: % d % n log level: %-5 p % n user ID: % Property {UserID} % n User name: % Property {UserName} % n log information: % Property {Message} % n exception information: % exception % n "/>
</Layout>
</Appender>
<! -- Define output to file -->
<Appender name = "TextAppender" type = "log4net. Appender. RollingFileAppender">
<Param name = "File" value = "Log \"/>
<Param name = "AppendToFile" value = "true"/>
<Param name = "MaxFileSize" value = "10240"/>
<Param name = "MaxSizeRollBackups" value = "100"/>
<Param name = "StaticLogFileName" value = "false"/>
<Param name = "DatePattern" value = "yyyyMMdd"/>
<Param name = "RollingStyle" value = "Date"/>
<Layout type = "Log4NetTest. MyLayout">
<Param name = "ConversionPattern" value = "log time: % d % n log level: %-5 p % n user ID: % Property {UserID} % n User name: % Property {UserName} % n log information: % Property {Message} % n exception information: % exception % n "/>
</Layout>
</Appender>
<! -- Define output to database -->
<Appender name = "DataBaseAppender" type = "log4net. Appender. AdoNetAppender">
<! -- Number of log cache writes -->
<BufferSize value = "1"/>
<! -- Log database connection string -->
<ConnectionType value = "System. Data. SqlClient. SqlConnection, System. Data, Version = 1.0.3300.0, Culture = neutral, PublicKeyToken = b77a5c561934e089"/>
<ConnectionString value = "data source =. \ SQL2008; initial catalog = Demo; integrated security = false; persist security info = True; User ID = sa; Password = 1qaz"/>
<! -- Log database script -->
<CommandText value = "insert into LogInfo ([LogDate], [LogLevel], [UserId], [UserName], [Message], [Exception]) VALUES (@ LogDate, @ LogLevel, @ UserId, @ UserName, @ Message, @ Exception) "/>
<! -- Log time LogDate -->
<Parameter>
<ParameterName value = "@ LogDate"/>
<DbType value = "String"/>
<Size value = "30"/>
<Layout type = "log4net. Layout. PatternLayout">
<ConversionPattern value = "% date {yyyy-MM-dd HH: mm: ss}"/>
</Layout>
</Parameter>
<! -- Log Level -->
<Parameter>
<ParameterName value = "@ LogLevel"/>
<DbType value = "String"/>
<Size value = "10"/>
<Layout type = "log4net. Layout. PatternLayout">
<ConversionPattern value = "% level"/>
</Layout>
</Parameter>
<! -- Custom UserId -->
<Parameter>
<ParameterName value = "@ UserId"/>
<DbType value = "String"/>
<Size value = "20"/>
<Layout type = "Log4NetTest. MyLayout">
<ConversionPattern value = "% Property {UserID}"/>
</Layout>
</Parameter>
<! -- Custom UserName -->
<Parameter>
<ParameterName value = "@ UserName"/>
<DbType value = "String"/>
<Size value = "50"/>
<Layout type = "Log4NetTest. MyLayout">
<ConversionPattern value = "% Property {UserName}"/>
</Layout>
</Parameter>
<! -- Custom Message -->
<Parameter>
<ParameterName value = "@ Message"/>
<DbType value = "String"/>
<Size value = "200"/>
<Layout type = "Log4NetTest. MyLayout">
<ConversionPattern value = "% Property {Message}"/>
</Layout>
</Parameter>
<! -- Exception information Exception -->
<Parameter>
<ParameterName value = "@ Exception"/>
<DbType value = "String"/>
<Size value = "4000"/>
<Layout type = "log4net. Layout. ExceptionLayout"/>
</Parameter>
</Appender>
</Log4net>
</Configuration>
5. Add the LogHelper. cs class to write their respective information.
Using System;
Using System. Diagnostics;
Using System. IO;
Using System. Windows. Forms;
Using log4net;
[Assembly: log4net. Config. XmlConfigurator (Watch = true)]
Namespace Log4NetTest
{
Public class LogHelper
{
/// <Summary>
/// LoggerName
/// </Summary>
Public static string LoggerName = string. Empty;
/// <Summary>
/// User ID
/// </Summary>
Public static string UserID = string. Empty;
/// <Summary>
/// User Name
/// </Summary>
Public static string UserName = string. Empty;
Private static ILog iLog;
Private static LogEntity logEntity;
/// <Summary>
/// Interface
/// </Summary>
Private static ILog log
{
Get
{
String path = Application. StartupPath + @ "\ Log4Net. config ";
Log4net. Config. XmlConfigurator. Configure (new FileInfo (path ));
If (iLog = null)
{
ILog = log4net. LogManager. GetLogger (LoggerName );
}
Else
{
If (iLog. Logger. Name! = LoggerName)
{
ILog = log4net. LogManager. GetLogger (LoggerName );
}
}
Return iLog;
}
}
/// <Summary>
/// Construct the message entity
/// </Summary>
/// <Param name = "message"> </param>
/// <Returns> </returns>
Private static LogEntity BuildMessageMode (string message)
{
If (logEntity = null)
{
LogEntity = new LogEntity ();
LogEntity. UserID = UserID;
LogEntity. UserName = UserName;
LogEntity. Message = message;
}
Else
LogEntity. Message = message;
Return logEntity;
}
/// <Summary>
/// Debug
/// </Summary>
/// <Param name = "message"> message </param>
Public static void Debug (string message)
{
If (log. IsDebugEnabled)
Log. Debug (BuildMessageMode (message ));
}
/// <Summary>
/// Debug
/// </Summary>
/// <Param name = "message"> message </param>
/// <Param name = "exception"> exception </param>
Public static void Debug (string message, Exception ex)
{
If (log. IsDebugEnabled)
Log. Debug (BuildMessageMode (message), ex );
}
/// <Summary>
/// Information
/// </Summary>
/// <Param name = "message"> message </param>
Public static void Info (string message)
{
If (log. IsInfoEnabled)
Log. Info (BuildMessageMode (message ));
}
/// <Summary>
/// Information
/// </Summary>
/// <Param name = "message"> message </param>
/// <Param name = "exception"> exception </param>
Public static void Info (string message, Exception ex)
{
If (log. IsInfoEnabled)
Log. Info (BuildMessageMode (message), ex );
}
/// <Summary>
/// General error
/// </Summary>
/// <Param name = "message"> message </param>
Public static void Error (string message)
{
If (log. IsErrorEnabled)
Log. Error (BuildMessageMode (message ));
}
/// <Summary>
/// General error
/// </Summary>
/// <Param name = "message"> message </param>
/// <Param name = "exception"> exception </param>
Public static void Error (string message, Exception exception)
{
If (log. IsErrorEnabled)
Log. Error (BuildMessageMode (message), exception );
}
/// <Summary>
/// Warning
/// </Summary>
/// <Param name = "message"> message </param>
Public static void Warn (string message)
{
If (log. IsWarnEnabled)
Log. Warn (BuildMessageMode (message ));
}
/// <Summary>
/// Warning
/// </Summary>
/// <Param name = "message"> message </param>
/// <Param name = "exception"> exception </param>
Public static void Warn (string message, Exception ex)
{
If (log. IsWarnEnabled)
Log. Warn (BuildMessageMode (message), ex );
}
/// <Summary>
/// Serious
/// </Summary>
/// <Param name = "message"> message </param>
Public static void Fatal (string message)
{
If (log. IsFatalEnabled)
Log. Fatal (BuildMessageMode (message ));
}
/// <Summary>
/// Serious
/// </Summary>
/// <Param name = "message"> message </param>
/// <Param name = "exception"> exception </param>
Public static void Fatal (string message, Exception ex)
{
If (log. IsFatalEnabled)
Log. Fatal (BuildMessageMode (message), ex );
}
}
}
6. To test the log performance, you only need to modify Log4Net. config to implement various input methods.
Output to the console:
<Logger name = "myLogger">
<Level value = "ALL"/>
<Appender-ref = "leleappender"/>
</Logger>
Output to file:
<Logger name = "myLogger">
<Level value = "ALL"/>
<Appender-ref = "TextAppender"/>
</Logger>
Output to database:
<Logger name = "myLogger">
<Level value = "ALL"/>
<Appender-ref = "DataBaseAppender"/>
</Logger>