log4net把自定义的变量写入数据库
log4net把自定义的变量写入数据库
一、log4net针对sqlserver,mysql及文本的配置方式:
(注:如果配置写入数据库,需要将System.Data.dll拷到bin目录下。)
文本和sqlserver-sqlclient连接库:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<!-- This section contains the log4net configuration settings -->
<log4net>
<root>
<level value="All" />
<appender-ref ref="RollingFileAppender"/>
<appender-ref ref="AdoNetAppender"/>
</root>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender" >
<file value="testlog.txt" />
<appendToFile value="true" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="100" />
<rollingStyle value="Date" />
<datePattern value="yyyy-MM-dd"/>
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level %date %logger - %message%newline" />
</layout>
</appender>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<!--表示是记录1 条到缓冲区,满1条后再写入SQL server。调试时可以改为1,实际应用建议为100-->
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=.;database=testdb;user id=sa;password=123456;integrated security=false;persist security info=True;" />
<commandText value="INSERT INTO test_log([LogTime],[level],Message,Exception,Reason) VALUES (@LogTime,@level,@Message,@Exception,@Reason)" />
<parameter>
<parameterName value="@LogTime" />
<dbType value="DateTime" />
<layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
</parameter>
<!--<layout type="log4net.Layout.RawTimeStampLayout" />-->
<parameter>
<parameterName value="@level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout" value="%level" />
</parameter>
<parameter>
<parameterName value="@Message" />
<dbType value="String" />
<size value="1000" />
<layout type="log4net.Layout.PatternLayout" value="%message" />
</parameter>
<parameter>
<parameterName value="@Exception " />
<dbType value="String" />
<size value="1000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
<!--自定义变量-->
<parameter>
<parameterName value="@Reason" />
<dbType value="String" />
<size value="1000" />
<layout type="log4net.Layout.PatternLayout" >
<param name="ConversionPattern" value="%property{Reason}"/>
</layout>
</parameter>
</appender>
mysql-odbc方式连接库:
<connectionType value="System.Data.Odbc.OdbcConnection, System.Data" />
<connectionString value="DRIVER={MySQL ODBC 3.51 Driver};SERVER=服务器ip地址;DATABASE=数据库名;UID=用户名;PASSWORD=密码;OPTION=3" />
<commandText value="INSERT INTO ads_log(LogTime,Operator) VALUES (?,?)" />
<parameter>
<parameterName value="@LogTime" />
<dbType value="DateTime" />
<layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
</parameter>
二、log.info(object messageObject)传入自定义对象
比如说插入数据库时需要将该业务操作的原因也记录,假设数据库中该字段名称为Reason。
1.自定义一个业务对象,LogContent
public class LogContent
{
public LogContent(string reason)
{
_Reason = reason;
}
private string _reason;
public string Reason
{
get { return _reason; }
set { _reason = value; }
}
}
2.自定义一个Layout(在该类的构造方法中将自定义的Converter加进去,以处理property{}中的自定义字段)和一个PatternConverter:
public class MyLayout : PatternLayout
{
public MyLayout()
{
this.AddConverter("property", typeof(MyMessagePatternConverter));
}
}
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());
}
//if (Option != null)
//{
// // Write the value for the specified key
// WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty(Option));
//}
//else
//{
// // Write all the key value pairs
// WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
//}
}
/// <summary>
/// 通过反射获取传入的日志对象的某个属性的值
/// </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;
}
3.配置文件中相应节点:
<parameter>
<parameterName value="@Reason" />
<dbType value="String" />
<size value="100" />
<layout type="Component.MyLayout, Component" >
<param name="ConversionPattern" value="%property{Reason}"/>
</layout>
</parameter>
4.调用代码:
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();//使用单独配置文件时无需此方法
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
log.Info("log4net测试");
log.Info(new LogContent("reason-because……"));
}