[英]log4net - Custom property logging
我使用以下類使用log4net打印出消息:
public class Message
{
public String Text { get; set; }
public int Id { get; set; }
public override string ToString()
{
return Text;
}
}
我使用Logger.Info(MessageInstance)
,所以log4net只是調用ToString
方法並打印出消息。 我也想記錄消息對象的Id
屬性,但是我不知道該如何實現。
我的轉換模式與此類似:
<conversionPattern value="%date %-5level %message%newline" />
我嘗試添加%message{Id}
但這只會將整個消息打印兩次。
有什么建議么?
我剛剛編寫了一個自定義模式,該模式允許讀取消息對象的屬性。
public class ReflectionReader : PatternLayoutConverter
{
public ReflectionReader()
{
_getValue = GetValueFirstTime;
}
protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
{
writer.Write(_getValue(loggingEvent.MessageObject));
}
private Func<object, String> _getValue;
private string GetValueFirstTime(object source)
{
_targetProperty = source.GetType().GetProperty(Option);
if (_targetProperty == null)
{
_getValue = x => "<NULL>";
}
else
{
_getValue = x => String.Format("{0}", _targetProperty.GetValue(x, null));
}
return _getValue(source);
}
private PropertyInfo _targetProperty;
}
與此結合:
public class ReflectionLayoutPattern : PatternLayout
{
public ReflectionLayoutPattern()
{
this.AddConverter("item", typeof(ReflectionReader));
}
}
配置看起來像這樣:
<layout type="MyAssembly.MyNamespace.ReflectionLayoutPattern, MyAssembly">
<conversionPattern value="[%item{Id}]	%message%newline" />
</layout>
您可以使用從XmlLayoutBase派生的CustomXmlLayout類,並重寫FormatXml方法。 此方法將LoggingEvent對象作為參數,該對象將包含傳遞給log方法的MessageObject。
public class SpecialXmlLayout : XmlLayoutBase
{
protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent)
{
Message message = loggingEvent.MessageObject as Message;
writer.WriteStartElement("LoggingEvent");
writer.WriteElementString("Message", GetMessage(message));
// ... write other things
writer.WriteEndElement();
}
}
在GetMessaage方法內,根據您希望從消息中創建字符串。
然后在log4net配置中使用此布局類:
<log4net>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<applicationName value="My Application" />
<layout type="Namespace.SpecialXmlLayout">
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="ERROR" />
<param name="LevelMax" value="FATAL" />
</filter>
</appender>
</log4net>
這是主意。 有關更多特定的詳細信息,您將必須查閱log4Net SDK文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.