园子里面有很多关于log4net保存到数据库的帖子,但是要动手操作还是比较不易,从头开始学习log4net数据库日志一、WebConfig中配置log4net
下面先一点一点来学习如果进行配置
1.下载,请参考log4net保存到数据库系列一:WebConfig中配置log4net
2.数据库脚本
CREATE TABLE [dbo].[Logs] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[Level] NVARCHAR (MAX) NULL,
[Logger] NVARCHAR (MAX) NULL,
[Message] NVARCHAR (MAX) NULL,
[Date] DATETIME NOT NULL,
[Exception] NVARCHAR (MAX) NULL,
[ModName] NVARCHAR (MAX) NULL,
[UserName] NVARCHAR (MAX) NULL,
[Mac] NVARCHAR (MAX) NULL,
[IP] NVARCHAR (MAX) NULL,
[Url] NVARCHAR (MAX) NULL,
[ActionName] NVARCHAR (MAX) NULL,
[Name] NVARCHAR (MAX) NULL
);
3.消息类
public class JimMessage : IRequiresSessionState
{
public JimMessage()
{
IP = Util.getLocalIP();
Mac = Util.getLocalMac();
Url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
}
public string IP { get; set; }
public string Mac { get; set; }
public string Url { get; set; }
public string ModName { get; set; }
public string ActionName { get; set; }
public string Message { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
}
4.自定义字段解析类
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)
{
WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
}
else
{
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;
}
}
5..测试代码
ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
AdoNetAppender adoNetAppender = new AdoNetAppender();
adoNetAppender.BufferSize = -1;
adoNetAppender.ConnectionType = "System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
adoNetAppender.ConnectionString = "data source=.;initial catalog=test;persist security info=True;user id=sa;password=Jiehui@2016;MultipleActiveResultSets=True;";
adoNetAppender.CommandText = "INSERT INTO Logs ([Date],[Level],[Logger],[Message],[Exception],[UserName],[ModName],[Mac],[IP],[Url],[ActionName],[Name]) VALUES (@log_date, @log_level, @logger, @Message, @exception,@UserName,@ModName,@Mac,@IP,@Url,@ActionName,@Name)";
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@log_date", DbType = System.Data.DbType.DateTime, Layout = new log4net.Layout.RawTimeStampLayout() });
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@log_level", DbType = System.Data.DbType.String, Size = 50, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%level")) });
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@logger", DbType = System.Data.DbType.String, Size = 255, Layout = new Layout2RawLayoutAdapter(new PatternLayout("%logger")) });
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@exception", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(new ExceptionLayout()) });
PatternLayout layout = new MyLayout() {ConversionPattern = "%property{UserName}"};
layout.ActivateOptions();
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@UserName", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter( layout)});
layout = new MyLayout() { ConversionPattern = "%property{ModName}" };
layout.ActivateOptions();
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@ModName", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(layout) });
layout = new MyLayout() { ConversionPattern = "%property{Mac}" };
layout.ActivateOptions();
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@Mac", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(layout) });
layout = new MyLayout() { ConversionPattern = "%property{IP}" };
layout.ActivateOptions();
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@IP", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(layout) });
layout = new MyLayout() { ConversionPattern = "%property{Url}" };
layout.ActivateOptions();
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@Url", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(layout) });
layout = new MyLayout() { ConversionPattern = "%property{ActionName}" };
layout.ActivateOptions();
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@ActionName", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(layout) });
layout = new MyLayout() { ConversionPattern = "%property{Name}" };
layout.ActivateOptions();
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@Name", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(layout) });
layout = new MyLayout() { ConversionPattern = "%property{Message}" };
layout.ActivateOptions();
adoNetAppender.AddParameter(new AdoNetAppenderParameter { ParameterName = "@Message", DbType = System.Data.DbType.String, Size = 4000, Layout = new Layout2RawLayoutAdapter(layout) });
adoNetAppender.ActivateOptions();
BasicConfigurator.Configure(rep, adoNetAppender);
ILog log = LogManager.GetLogger(rep.Name, "NoBufferingTest");
JimMessage message = new JimMessage();
message.Message = "审核成功";
message.UserName = "金朝钱";
message.Url = Request.Url.ToString();
message.ModName = "其他入库";
message.ActionName = "审核";
message.Name = "Bill20150505";
log.Debug(message);
6.测试成功