Log4NET简介
log4net库是Apache log4j框架在Microsoft .NET平台的实现,是一个帮助程序员将日志信息输出到各种目标(控制台、文件、数据库等)的工具。
前提
最近做项目需要记录系统日志和用户操作日志,就想起来了log4net,但是业务需要需要加入自定义属性,并把自定义属性日志数据插入到数据库中,看好趁这个机会学习总结下。
详细步骤
一、首先下载:log4net.dll 下载地址:http://logging.apache.org/log4net/download_log4net.cgi
二、在项目中进行引用。这个不多说了,相信大家都很熟悉这个过程。
三、在web.config,加入以下代码:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
四、然后在与web.config同目录下面新建个配置文件,我这建了个log4net.config,如下图
五、在log4net.config加入以下代码,里面注释和详细 ,大家可以看如下代码:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections> <log4net>
<logger name="myLogger">
<level value="INFO"/>
<appender-ref ref="AdoNetAppender_SqlServer"/>
<!--sql server数据库1-->
<appender-ref ref="AdoNetAppender_SqlServer1"/>
<!--sql server数据库2-->
<appender-ref ref="AdoNetAppender_Sqllite"/>
<!--sqlite数据库-->
<appender-ref ref="InfoAppender"/>
<!--记录到文件-->
</logger> <!--sql server数据库1-->
<appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender">
<!-- BufferSize 为缓冲区大小,只有日志记录超5 条才会一块写入到数据库 -->
<!-- 或写为<param name="BufferSize" value="" /> -->
<bufferSize value=""/>
<!-- 引用 -->
<!--.0这是对应sql2008 如是2000或2005另外配置-->
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089"/> <!-- 连接数据库字符串 -->
<connectionString value="Data Source=.;Initial Catalog=Log;User ID=sa;Password=sa123;" />
<!-- 插入到表Log -->
<commandText value = "INSERT INTO Mylogger ([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"/>
<!--<dbType value = "String"/>
<size value = ""/>-->
<!-- LogComponent 是类所在的命名空间,MyLayout 是自定义属性所在的类,这是我们自己要写的部分,将在下面介绍。 -->
<layout type = "Log4netExpand.MyLayout,log4nettest">
<!-- 当用到property 时,就表明这是用户自定义的字段属性啦,是log4net 中所没有提供的字段。 -->
<conversionPattern value = "%property{Event_Type} "/>
</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 = ""/>
<layout type = "Log4netExpand.MyLayout,log4nettest">
<conversionPattern value = "%property{EventCategory}"/>
</layout>
</parameter> <!-- 日志分类号 -->
<parameter>
<parameterName value = "@Event_ID"/>
<dbType value = "Int32"/>
<layout type = "Log4netExpand.MyLayout,log4nettest">
<conversionPattern value = "%property{Event_ID}"/>
</layout>
</parameter> <!-- 计算机IP -->
<parameter>
<parameterName value = "@ComputerName"/>
<dbType value = "String"/>
<size value = ""/>
<layout type = "Log4netExpand.MyLayout,log4nettest">
<conversionPattern value = "%property{ComputerName}"/>
</layout>
</parameter> <!-- 计算机Mac 信息 -->
<parameter>
<parameterName value = "@Mac_Address"/>
<dbType value = "String"/>
<size value = "50 "/>
<layout type = "Log4netExpand.MyLayout, log4nettest">
<conversionPattern value = "%property{Mac_Address}"/>
</layout>
</parameter> <!-- 登陆系统用户名 -->
<parameter>
<parameterName value = "@UserName"/>
<dbType value = "String"/>
<size value = ""/>
<layout type = "Log4netExpand.MyLayout,log4nettest">
<conversionPattern value = "%property{UserName}"/>
</layout>
</parameter> <!-- 事件来源类型,这里默认为Rier -->
<parameter>
<parameterName value = "@SourceType"/>
<dbType value = "String"/>
<size value = ""/>
<layout type = "Log4netExpand.MyLayout,log4nettest">
<conversionPattern value = "%property{SourceType}"/>
</layout>
</parameter> <!-- 事件来源 -->
<parameter>
<parameterName value = "@Source "/>
<dbType value = "String"/>
<size value = ""/>
<layout type = "Log4netExpand.MyLayout,log4nettest">
<conversionPattern value = "%property{Source}"/>
</layout>
</parameter> <!-- 事件描述 -->
<parameter>
<parameterName value = "@Description "/>
<dbType value = "String"/>
<size value = ""/>
<layout type = "Log4netExpand.MyLayout, log4nettest">
<conversionPattern value = "%property{Description}"/>
</layout>
</parameter> <!-- 日志收集时间 -->
<parameter>
<parameterName value = "@CollectDate"/>
<dbType value = "DateTime"/>
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
</appender> <!--记录到文件-->
<appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <param name="File" value="Log\\INFO\\"/>
<param name="AppendToFile" value="true"/>
<param name="MaxFileSize" value="" />
<param name="MaxSizeRollBackups" value=""/>
<param name="StaticLogFileName" value="false"/>
<param name="DatePattern" value="yyyyMMdd".txt""/>
<param name="RollingStyle" value="Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="记录时间:%date 线程ID:[%thread] 日志级别:%-5level 记录类:%logger 操作者ID:%property{Operator} 操作类型:%property{Action}%n 当前机器名:%property%n当前机器名及登录用户:%username %n 记录位置:%location%n 消息描述:%property{Message}%n 异常:%exception%n 消息:%message%newline%n%n" />
</layout>
</appender> <!--sql server数据库2-->
<appender name="AdoNetAppender_SqlServer1" type="log4net.Appender.AdoNetAppender">
<bufferSize value=""/>
<!--.0这是对应sql2008 如是2000或2005另外配置-->
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089"/> <!-- 连接数据库字符串 -->
<connectionString value="Data Source=.;Initial Catalog=Log;User ID=sa;Password=sa123;" /> <!-- 插入到表Log -->
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message,@exception)"/> <parameter>
<parameterName value="@log_date"/>
<dbType value="DateTime"/> <layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
</layout>
<!-- <layout type="log4net.Layout.RawTimeStampLayout"/>-->
</parameter>
<parameter>
<parameterName value="@thread"/>
<dbType value="String"/>
<size value=""/>
<!-- LogComponent 是类所在的命名空间,MyLayout 是自定义属性所在的类,这是我们自己要写的部分,将在下面介绍。 -->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread"/>
</layout>
</parameter>
<parameter>
<parameterName value="@log_level"/>
<dbType value="String"/>
<size value=""/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level"/>
</layout>
</parameter>
<parameter>
<parameterName value="@logger"/>
<dbType value="String"/>
<size value=""/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger"/>
</layout>
</parameter>
<parameter>
<parameterName value="@message"/>
<dbType value="String"/>
<size value=""/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message"/>
</layout>
</parameter>
<parameter>
<parameterName value="@exception" />
<dbType value="String" />
<size value="" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender> <!--sqlite数据库-->
<appender name="AdoNetAppender_Sqllite" type="log4net.Appender.AdoNetAppender">
<bufferSize value=""/>
<!--.0这是对应sql2008 如是2000或2005另外配置-->
<!--<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089"/>-->
<connectionType value="System.Data.SQLite.SQLiteConnection, System.Data.SQLite, Version=1.0.66.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
<!-- 连接数据库字符串 -->
<!--<connectionString value="Data Source=.;Initial Catalog=Log;User ID=sa;Password=123;" />-->
<connectionString value="C:\\Users\\Administrator\\Desktop\\log4net\\Log4netExpand\\Test.db3;" />
<!-- 插入到表Log -->
<commandText value="INSERT INTO MAIN.[Log] ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message,@exception)"/> <parameter>
<parameterName value="@log_date"/>
<dbType value="DateTime"/> <layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
</layout>
<!-- <layout type="log4net.Layout.RawTimeStampLayout"/>-->
</parameter>
<parameter>
<parameterName value="@thread"/>
<dbType value="String"/>
<!--<size value=""/>-->
<!-- LogComponent 是类所在的命名空间,MyLayout 是自定义属性所在的类,这是我们自己要写的部分,将在下面介绍。 -->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread"/>
</layout>
</parameter>
<parameter>
<parameterName value="@log_level"/>
<dbType value="String"/>
<!--<size value=""/>-->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level"/>
</layout>
</parameter>
<parameter>
<parameterName value="@logger"/>
<dbType value="String"/>
<!--<size value=""/>-->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger"/>
</layout>
</parameter>
<parameter>
<parameterName value="@message"/>
<dbType value="String"/>
<!--<size value=""/>-->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message"/>
</layout>
</parameter>
<parameter>
<parameterName value="@exception" />
<dbType value="String" />
<!--<size value="" />-->
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
</log4net> <system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web> </configuration>
我主要说下里面自定义属性的代码的分别代表意义:
<parameter>
96 <parameterName value = "@UserName"/>
97 <dbType value = "String"/>
98 <size value = "50"/>
99 <layout type = "Log4netExpand.MyLayout,log4nettest">
100 <conversionPattern value = "%property{UserName}"/>
101 </layout>
102 </parameter>
其中MyLayout,是我们自己定义的类,下面有介绍;Log4netExpand是这个类的命名空间;log4nettest这个代表是aspx页面的命名空间。注意在此区分。
六、自定义类,这些类呢包含将要插入数据库中的自定义字段
命名空间为 Log4netExpand包含3个类:LogContent.cs、 MyLayout.cs 、MyMessagePatternConverter .cs
1)第一个LogContent类如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace Log4netExpand
{
/// <summary>
/// 包含了所有的自定字段属性
/// </summary>
public class LogContent
{
/// <summary>
/// 时间类型 均为3
/// </summary>
public int Event_Type { get; set; } /// <summary>
/// 日志分类描述,自定义
/// </summary>
public string EventCategory { get; set; } /// <summary>
/// 日志分类号
/// </summary>
public int Event_ID { get; set; } /// <summary>
/// 计算机IP
/// </summary>
public string ComputerName { get; set; } /// <summary>
/// 计算机Mac 地址
/// </summary>
public string Mac_Address { get; set; } /// <summary>
/// 系统登陆用户
/// </summary>
public string UserName { get; set; } /// <summary>
/// Rier
/// </summary>
public string SourceType { get; set; } /// <summary>
/// Rier Recorder audit
/// </summary>
public string Source { get; set; } /// <summary>
/// 日志描述信息
/// </summary>
public string Description { get; set; } }
}
2)第二个类MyLayout代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using log4net.Layout; namespace Log4netExpand
{
class MyLayout : PatternLayout
{
public MyLayout()
{
this.AddConverter("property", typeof(MyMessagePatternConverter));
}
}
}
3)第三个类MyMessagePatternConverter 代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using log4net.Layout.Pattern; namespace Log4netExpand
{
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; } }
}
七、代码页,实现通过log4net把日志(含自定一生属性)添加到数据库
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; using System.Management;
using Log4netExpand; namespace Log4netExpand
{
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"); LogContent logmodel = new LogContent();
logmodel.Event_Type = ;
logmodel.EventCategory = "登陆系统";
logmodel.Event_ID = ;
logmodel.ComputerName = Request.UserHostAddress;
logmodel.Mac_Address = GetMacAddress();
logmodel.Source = "SS";
logmodel.SourceType = "";
logmodel.UserName = "ADMIN";
logmodel.Description = "TEST";//在记录数据库操作时,可以在petapoco底层将sql语句放入其中。
LogHelper.WriteLog(logmodel); lbMsg.Text = "数据记录成功!";
} public string GetMacAddress()
{
string mac = "";
try
{
//获取网卡硬件地址
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances(); List<string> list = new List<string>(); foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
mac = mo["MacAddress"].ToString(); list.Add(mac);
}
}
moc = null;
mc = null; mac = list[list.Count - ]; return mac;
}
catch
{
return "unknow";
}
}
}
}
代码例子源代码: Demo下载