log4net可以输出Json吗?

Can log4net output Json?

我见过 log4net 的几个扩展,它们声称可以创建 json 日志文件,但格式永远无效 json,这意味着集合不在数组中,也不在数组中昏迷分离。我是用错了还是没有办法将 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。

它将每一行输出为单独的 JSON 记录,就像它对 1 行日志所做的那样。 您可以逐行进行解析,或者您可以在每个 } 之后添加周围的 [] 和一个命令,这样就可以了。

解决方案很基本,我自己写了 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.Ext.Json nuget package

将以下配置设置添加到 app.config/web.config 文件

<log4net>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
  <file value="logs\log-file-name.json" />
  <rollingStyle value="Date" />
  <datePattern value="yyyy-MM-dd" />
  <PreserveLogFileNameExtension value="true" />
  <staticLogFileName value="false" />
  <appendToFile value="true" />
  <maxSizeRollBackups value="10" />
  <dateTimeStrategy 
  type="log4net.Appender.RollingFileAppender+UniversalDateTime" />

  <!--text formatted log4net logging-->
  <!--<layout type="log4net.Layout.PatternLayout">
    --><!--check conversion patterns from 
   https://logging.apache.org/log4net/--><!--
    --><!--<conversionPattern value="%utcdate{ABSOLUTE} UTC %c{1} - %m%n" 
  />--><!--
    <conversionPattern value="%date [%thread] %-5level %logger - 
  %message%newline" />
  </layout>-->

  <!--json formatted log4net logging-->
  <layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
    <decorator type="log4net.Layout.Decorators.StandardTypesDecorator, 
  log4net.Ext.Json" />
    <member value="date:date" />
    <member value="level:level" />
    <member value="logger:logger" />
    <member value="message:messageObject" />
    <member value="exception:exception" />
  </layout>
</appender>
<root>
  <!--Options are "ALL", "DEBUG", "INFO", "WARN", "ERROR", "FATAL" and 
"OFF".-->
  <level value="DEBUG" />
  <appender-ref ref="RollingFile" />
</root>
</log4net>

这里是 ninject

的示例调用
Kernel = new StandardKernel(); 
Kernel.Bind<ILog>().ToMethod(c => 
LogManager.GetLogger(typeof(YourClassName))).InSingletonScope();
var log = Kernel.Get<ILog>();
log.debug("testing log4net json");