时间:2021-07-01 10:21:17 帮助过:8人阅读
(三)定义自己的 Layout 布局类 和 MyMessagePatternConverter类
namespace Util { public class MyLogLayout : PatternLayout { public MyLogLayout() { this.AddConverter("property", typeof(MyMessagePatternConverter)); } } }
namespace Util { 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()); } } /// <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; } } }
(四)最后可以调用了,我这里写了一个公共的类Log
[assembly: log4net.Config.XmlConfigurator(Watch = false)]
namespace Util { public class Log { #region 记录操作日志到数据库 /// <summary> /// 记录操作日志到数据库 /// </summary> /// <param name="user"></param> /// <param name="msg"></param> /// <param name="className"></param> /// <param name="method"></param> public static void OperateDB(string user, string msg, string className, string method) { ILog logger = LogManager.GetLogger("OperateDB"); logger.Info(new LogContent() { Msg = msg, Cby = user, ClassName = className, Method = method });//将异常信息写到磁盘上. } /// <summary> /// 记录操作日志到数据库 /// </summary> /// <param name="user"></param> /// <param name="msg"></param> public static void OperateDB(string user, string msg) { ILog logger = LogManager.GetLogger("OperateDB"); logger.Info(new LogContent() { Msg = msg, Cby = user, ClassName = null, Method = null });//将异常信息写到磁盘上. } #endregion } }
log4net 添加自定义日志到数据库
标签: