本文介绍了Log4net可以输出Json吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我见过两个log4net的扩展,它们声称要在日志文件中创建json,但格式从来不是有效的json,这意味着集合不在数组中,也不是Coma分隔的。我用错了吗?还是没有办法将log4net与json一起使用?
<appender name="SessionFileAppender" type="log4net.Appender.FileAppender">
<file value="Session.log" />
<appendToFile value="false" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type='log4net.Layout.SerializedLayout, log4net.Ext.Json'>
<decorator type='log4net.Layout.Decorators.StandardTypesDecorator, log4net.Ext.Json' />
<default />
<remove value='message' />
<member value='message:messageobject' />
</layout>
</appender>
输出为:
{"date":"2017-01-29T13:45:50.7345813-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Loading new UI instance"}
{"date":"2017-01-29T13:45:50.7380842-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Loading internal localization file"}
{"date":"2017-01-29T13:45:50.7510970-05:00","level":"DEBUG","appname":"MyApp.vshost.exe","logger":"MainWindow","thread":"9","ndc":"(null)","message":"Initializing UI"}
这很接近,但不是真正有效的json。
推荐答案
解决方案很简单,我编写了自己的Appender
将数据存储在集合中,然后根据需要使用Json.net序列化该集合。这也让我能够在应用程序中查看日志并绑定到它,这也增加了额外的好处。
public class CollectionAppender : AppenderSkeleton
{
public static ObservableCollection<LogItem> logData = new ObservableCollection<LogItem>();
protected override void Append(LoggingEvent loggingEvent)
{
logData.Add(new LogItem(loggingEvent));
}
}
public class LogItem
{
public string Logger { get; private set; }
public string Level { get; private set; }
public string Message { get; private set; }
public DateTime Timestamp { get; private set; }
public Exception ExceptionData { get; private set; }
public bool ShouldSerializeExceptionData() //This keeps things tidy when using Json.net for non exemption entries.
{
return ExceptionData != null;
}
public LogItem(LoggingEvent data)
{
Logger = data.LoggerName;
Level = data.Level.DisplayName;
Message = data.RenderedMessage;
Timestamp = data.TimeStamp;
ExceptionData = data.ExceptionObject;
}
}
这篇关于Log4net可以输出Json吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!