log4net 自定义字段保存日志到数据库
-
1、源代码
using log4net;
using log4net.Layout;
using log4net.Layout.Pattern;
using System.Reflection;
namespace Logger
{
///
/// 包含了所有的自定字段属性
///
public class LogContent
{
public LogContent(string userName, string actionClick, string logText)
{
UserName = userName;
ActionClick = actionClick;
Message = logText;
}
///
/// 系统登陆用户
///
public string UserName { get;set; }
///
/// 动作事件
///
public string ActionClick { get; set; }
///
/// 日志描述信息
///
public string Message { get; set; }
}
public class CustomLayout : PatternLayout
{
public CustomLayout()
{
this.AddConverter("property", typeof(LogInfoPatternConverter));
}
}
public class LogInfoPatternConverter : 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());
}
}
///
/// 通过反射获取传入的日志对象的某个属性的值
///
///
///
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;
}
}
public class DBLog
{
private static ILog log;
private static ILog DBLogger
{
get
{
if (log == null)
log = LogManager.GetLogger("AppToDB");
return log;
}
}
public static void Info(string userName,string actionClick,string logText)
{
DBLogger.Info(new LogContent(userName,actionClick,logText ) );
}
}
}
2、web.config中的配置
如果数据库中表结构字段类型为nvarchar(max)时,则注意size中value值为-1,如:
具体配置如下:
3、代码调用
Logger.DBLog.Info("张工","删除订单","删除订单:"+PONo);