Log4Net添加自定义日志信息 [转帖]
一、 前言
该文章是针对在Log4Net中添加自定义日志信息。我们在写日志的时候并不是只写消息(Message),有些情况需要记录自定义的日志信息等。下面将说明在Log4Net中增加自定义字段UserName(用户名),Category(类别)这两个字段。
二、 建立数据库
[Id] [int] IDENTITY (1, 1) NOT NULL ,
[Date] [datetime] NOT NULL ,
[Thread] [varchar] (255) NOT NULL ,
[Level] [varchar] (50) NOT NULL ,
[Logger] [varchar] (255) NOT NULL ,
[Message] [varchar] (4000) NOT NULL ,
[Exception] [varchar] (2000) NULL ,
[User] [varchar] (50) NULL ,
[Category] [varchar] (50) NULL
)
其中Date,Thread,Level,Logger,Message,Exception是log4net内置的信息。User与Category是自定义的字段。
三、 编写配置文件
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<log4net>
<logger name="AA">
<level value="All" />
<appender-ref ref="ADONetAppender" />
</logger>
<!--<root>
<level value="All" />
<appender-ref ref="ADONetAppender" />
</root>-->
<appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
<!--BufferSize为缓冲区大小-->
<param name="BufferSize" value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="database=aa;server=(local);User ID=sa;Password=;" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception],[User],[Category]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception,@User,@Category)" />
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<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>
<parameter>
<parameterName value="@User" />
<dbType value="String" />
<size value="50" />
<layout type="Log4NetToDatabase.CustomLayout">
<conversionPattern value="%UserName" />
</layout>
</parameter>
<parameter>
<parameterName value="@Category" />
<dbType value="String" />
<size value="50" />
<layout type="Log4NetToDatabase.CustomLayout">
<conversionPattern value="%Category" />
</layout>
</parameter>
</appender>
</log4net>
</configuration>
一、 编写代码
1. 编写自定义PatternLayoutConverter类
{
override protected void Convert(TextWriter writer, LoggingEvent loggingEvent)
{
LogMessage logMessage = loggingEvent.MessageObject as LogMessage;
if (logMessage != null)
// 将UserName作为日志信息输出
writer.Write(logMessage.UserName);
}
}
internal sealed class CategoryPatternConverter : PatternLayoutConverter
{
override protected void Convert(TextWriter writer, LoggingEvent loggingEvent)
{
LogMessage logMessage = loggingEvent.MessageObject as LogMessage;
if (logMessage != null)
writer.Write(logMessage.Category);
}
}
2. 编写自定义日志输出类
{
private string m_UserName;
private string m_Category;
public LogMessage()
{
}
public LogMessage(string userName, string category)
{
m_UserName = userName;
m_Category = category;
}
public string UserName
{
get
{
return m_UserName;
}
set
{
m_UserName = value;
}
}
public string Category
{
get
{
return m_Category;
}
set
{
m_Category = value;
}
}
}
3. 编写由log4net.Layout.LayoutSkeleton继承的类CustomLayout
由于内容过多,将在附件中给出源代码。
在此对该类做一些说明:
如果要添加自定义的字段,可以在静态构造函数static CustomLayout()中加入s_globalRulesRegistry.Add("UserName", typeof(UserNamePatternConverter));其中UserNamePatternConverter是继承于PatternLayoutConverter的类。注册完之后就可以在配置文件中使用%UserName使用了。在此只要做这些修改就能使用了,其它的代码如果有趣,可以一起交流。
4. 加载配置文件并记录日志
在AssemblyInfo.cs文件中添加[assembly: XmlConfigurator()]。它的作用同于log4net.Config.XmlConfigurator.Configure();用来读取配置文件信息。
log4net.ILog log;
在form1中添加下列代码:
public Form1()
{
InitializeComponent();
// 如果配置文件中存在名称为AA的logger,则加载
log = LogManager.Exists("AA");
}
private void button1_Click(object sender, EventArgs e)
{
++count;
LogMessage message = new LogMessage();
message.UserName = "xds"+count.ToString();
message.Category = count.ToString();
// 输出日志信息
log.Error(message);
}
解决方案二:
与上面的方案只需做以下的更改:将CustomLayout类继承自log4net.Layout.PatternLayout并在构造函数中调用AddConverter()方法。该方法将占用较多的系统内存,但它代码简单易于理解。它的代码如下:
{
public CustomLayout2()
{
this.AddConverter("UserName", typeof(UserNamePatternConverter));
this.AddConverter("Category", typeof(CategoryPatternConverter));
}
}
参考信息:
Log4Net使用指南:http://www.tongyi.net/develop/.net/1053472.html
log4net 文章集:http://myx.cnblogs.com/archive/2005/06/28/182617.html
转自:http://www.cnblogs.com/xds/archive/2007/03/06/665124.html
如果山不向我走来,我就向山走去!