wpf log4net可以输出Json吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41924684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:59:57  来源:igfitidea点击:

Can log4net output Json?

c#jsonwpflog4net

提问by Wobbles

I've seen a couple extensions for log4net that claim to create json to the log file, but the format is never valid json, meaning the collection is not in an array and not coma separated. Am I using it wrong or is there just no way to use log4net with json?

我已经看到了 log4net 的几个扩展,它们声称为日志文件创建 json,但格式永远不是有效的 json,这意味着集合不在数组中,也没有以昏迷分隔。是我用错了还是没有办法在 json 中使用 log4net?

<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>

Output is:

输出是:

{"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"}

which is close, but not really valid json.

这是接近的,但不是真正有效的json。

采纳答案by Wobbles

The solution is basic enough, I wrote my own Appenderthat stored data in a collection, then serialized the collection with Json.net as needed. This also gives me the ability to view the log in the app and bind to it aswell so added bonus.

解决方案足够基本,我自己编写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;
    }
}

回答by oetzi

download log4net.Ext.Json nuget package

下载log4net.Ext.Json nuget 包

add following config settings to app.config/web.config files

将以下配置设置添加到 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>

here is a sample call with ninject

这是 ninject 的示例调用

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

回答by MoustafaS

It outputs each line as separate JSON record, as it does with 1 line logs. You can take line by line and parse, or you can add your surrounding [] and a comman after each } and that would do it.

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

回答by JEuvin

Yes, do this in the log4net.config file.

是的,在 log4net.config 文件中执行此操作。

    <conversionPattern

        value="{&quot;EntryDate&quot;:&quot;%date{ddd MMM dd HH:mm:ss zzz yyyy}&quot;,

        &quot;Level&quot;:&quot;%level&quot;,

        &quot;Logger&quot;:&quot;%logger&quot;,

        &quot;Message&quot;:&quot;%message&quot;}

        %newline" />