使用log4net记录日志到数据库(含有自定义属性)
记录日志是管理系统中对用户行为的一种监控与审核,asp.net中记录日志的方式有很多种,这里我只介绍一下最近用到的log4net,关于他的具体介绍网上有很多,我讲一下他的用法。 第一步:在配置文件中的<configSections>节添加下面一句话 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> 第二步:在<configuration>节中添加如下内容 < log4net> <root > <level value="Debug"/> <appender-ref ref="ADONetAppender"/> </root> <logger name="myLogger"> <level value="Debug"/> <appender-ref ref="ADONetAppender"/> </logger> //关于上边root到logger这块,如果同时出现,有可能会出现重复插入记录的情况,那么就需要改一下代码,把上面两段代码改成如下一段代码,如下: <root > <level value="Debug" name="myLogger"/> <appender-ref ref="ADONetAppender"/> </root> //下面就是对插入到数据库一些基本设置和基本字段设置 <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender,log4net"> <!--BufferSize为缓冲区大小,只有日志记录超10条才会一块写入到数据库--> <bufferSize value="10"/> <!--或写为<param name="BufferSize" value="10" />--> <!--引用--> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <!--连接数据库字符串--> <connectionString value="Data Source=.;Initial Catalog=audit;Persist Security Info=True;User ID=sa;Password=123;MultipleActiveResultSets=True"/> <!--插入到表Log--> <commandText value="INSERT INTO T_AUDITINFO ([EVENTTYPE],[TIMESTAMP],[EVENTCATEGORY],[EVENT_ID],[COMPUTERNAME],[MAC_ADDRESS],[USERNAME],[SOURCETYPE],[SOURCE],[DESCRIPTION],[COLLECTDATE]) VALUES (@Event_Type,@log_date, @EventCategory, @Event_ID, @ComputerName,@Mac_Address,@UserName,@SourceType,@Source,@Description,@CollectDate)"/> <!--日志类型,这里均为3--> <parameter> <parameterName value="@Event_Type"/> <dbType value="Int32"/> <layout type="LogComponent.MyLayout, LogComponent"> <param name="ConversionPattern" value="%property{Event_Type}"/>//注意这里,当用到property时,就表明这是用户自定义的字段属性啦,是log4net中所没有提供的字段。其中MyLayout是自定义属性所在的类, LogComponent是类所在的命名空间,这是我们自己要写的部分,将在下面介绍。 </layout> </parameter> <!--日志记录时间,RawTimeStampLayout为默认的时间输出格式 --> <parameter> <parameterName value="@log_date"/> <dbType value="DateTime"/> <layout type="log4net.Layout.RawTimeStampLayout"/>//这里呢是获取log4net中提供的日志时间 </parameter> <!--日志分类描述--> <parameter> <parameterName value="@EventCategory"/> <dbType value="String"/> <size value="50"/> <layout type="LogComponent.MyLayout, LogComponent"> <param name="ConversionPattern" value="%property{EventCategory}"/> </layout> </parameter> <!--日志分类号--> <parameter> <parameterName value="@Event_ID"/> <dbType value="Int32"/> <layout type="LogComponent.MyLayout, LogComponent"> <param name="ConversionPattern" value="%property{Event_ID}"/> </layout> </parameter> <!--计算机IP--> <parameter> <parameterName value="@ComputerName"/> <dbType value="String"/> <size value="50"/> <layout type="LogComponent.MyLayout, LogComponent"> <param name="ConversionPattern" value="%property{ComputerName}"/> </layout> </parameter> <!--计算机Mac信息--> <parameter> <parameterName value="@Mac_Address"/> <dbType value="String"/> <size value="50"/> <layout type="LogComponent.MyLayout, LogComponent"> <param name="ConversionPattern" value="%property{Mac_Address}"/> </layout> </parameter> <!--登陆系统用户名--> <parameter> <parameterName value="@UserName"/> <dbType value="String"/> <size value="50"/> <layout type="LogComponent.MyLayout, LogComponent"> <param name="ConversionPattern" value="%property{UserName}"/> </layout> </parameter> <!--事件来源类型,这里默认为Rier--> <parameter> <parameterName value="@SourceType"/> <dbType value="String"/> <size value="20"/> <layout type="LogComponent.MyLayout, LogComponent"> <param name="ConversionPattern" value="%property{SourceType}"/> </layout> </parameter> <!--事件来源--> <parameter> <parameterName value="@Source"/> <dbType value="String"/> <size value="50"/> <layout type="LogComponent.MyLayout, LogComponent"> <param name="ConversionPattern" value="%property{Source}"/> </layout> </parameter> <!--事件描述--> <parameter> <parameterName value="@Description"/> <dbType value="String"/> <size value="500"/> <layout type="LogComponent.MyLayout, LogComponent"> <param name="ConversionPattern" value="%property{Description}"/> </layout> </parameter> <!--日志收集时间--> <parameter> <parameterName value="@CollectDate"/> <dbType value="DateTime"/> <layout type="log4net.Layout.RawTimeStampLayout"/> </parameter> </appender> </log4net> 第三步:自定义类,这些类呢包含将要插入数据库中的自定义字段 命名空间为 LogComponent 包含3个类:LogContent.cs、 MyLayout.cs 、MyMessagePatternConverter .cs 第一个类 LogContent.cs 包含了所有的自定字段属性 using System; using System.Data; using System.Configuration; using System.Web; /// <summary> /// LogContent 的摘要说明 /// </summary> public class LogContent { public LogContent(int eventType,string eventCategory,int eventID,string computerName,string macAddress,string userName,string sourceType,string source,string description) { _event_Type = eventType; _eventCategory = eventCategory; _event_ID = eventID; _computerName = computerName; _mac_Address = macAddress; _userName = userName; _sourceType = sourceType; _source = source; _description = description; } int _event_Type; /// <summary> /// 时间类型 均为3 /// </summary> public int Event_Type { get { return _event_Type; } set { _event_Type = value; } } string _eventCategory; /// <summary> /// 日志分类描述,自定义 /// </summary> public string EventCategory { get { return _eventCategory; } set { _eventCategory = value; } } int _event_ID; /// <summary> /// 日志分类号 /// </summary> public int Event_ID { get { return _event_ID; } set { _event_ID = value; } } string _computerName; /// <summary> /// 计算机IP /// </summary> public string ComputerName { get { return _computerName; } set { _computerName = value; } } string _mac_Address; /// <summary> /// 计算机Mac地址 /// </summary> public string Mac_Address { get { return _mac_Address; } set { _mac_Address = value; } } string _userName; /// <summary> /// 系统登陆用户 /// </summary> public string UserName { get { return _userName; } set { _userName = value; } } string _sourceType; /// <summary> /// Rier /// </summary> public string SourceType { get { return _sourceType; } set { _sourceType = value; } } string _source; /// <summary> /// Rier Recorder audit /// </summary> public string Source { get { return _source; } set { _source = value; } } string _description; /// <summary> /// 日志描述信息 /// </summary> public string Description { get { return _description; } set { _description = value; } } } 第二个类 MyLayout.cs 把我们定义的属性转换为log4net所能识别的属性 using System; using System.Collections.Generic; using System.Text; using log4net.Layout.Pattern; using log4net.Layout; using log4net.Core; using System.Reflection; namespace LogComponent { class MyLayout:PatternLayout { public MyLayout() { this.AddConverter("property", typeof(MyMessagePatternConverter)); } } } 第三个类 using System; using System.Collections.Generic; using System.Text; using log4net.Layout.Pattern; using log4net.Layout; using log4net.Core; using System.Reflection; namespace LogComponent { 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; } } } 代码页 记得在该项目中添加log4net引用 using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using LogComponent; [assembly: log4net.Config.XmlConfigurator(Watch = true)] public partial class Test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { log4net.ILog log = log4net.LogManager.GetLogger("myLogger"); log.Info(new LogContent(3,"登陆系统",1,"127.0.0.1","111111","mhy","11111","11111111","登陆成功")); } }