72 lines
1.8 KiB
C#
72 lines
1.8 KiB
C#
using log4net.Layout;
|
|
using log4net.Layout.Pattern;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using System.Text;
|
|
|
|
namespace Lskj.Util
|
|
{
|
|
public class MyLayout : PatternLayout
|
|
{
|
|
|
|
public MyLayout()
|
|
{
|
|
|
|
this.AddConverter("property", typeof(MyPatternConverter));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
public class MyPatternConverter : 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>
|
|
/// <param name="loggingEvent"></param>
|
|
/// <returns></returns>
|
|
private object LookupProperty(string property, log4net.Core.LoggingEvent loggingEvent)
|
|
{
|
|
object propertyValue = default(object);
|
|
PropertyInfo propertyInfo = null;
|
|
Type objtype = loggingEvent.MessageObject.GetType();
|
|
propertyInfo = objtype.GetProperty(property);
|
|
|
|
propertyValue = propertyInfo != null ? propertyInfo.GetValue(loggingEvent.MessageObject, null) : loggingEvent.LookupProperty(property);
|
|
if (property == "msg" && objtype == typeof(String))
|
|
{
|
|
return loggingEvent.MessageObject;
|
|
}
|
|
|
|
return propertyValue ?? "";
|
|
|
|
}
|
|
|
|
}
|
|
}
|