我有以下log4net配置:

<log4net>
    <appender name="Console" type="log4net.Appender.ConsoleAppender">
        <layout type='log4net.Layout.SerializedLayout, log4net.Ext.Json'>
            <renderer type='log4net.ObjectRenderer.JsonDotNetRenderer, log4net.Ext.Json.Net'>
                <DateFormatHandling value="IsoDateFormat" />
                <NullValueHandling value="Ignore" />
            </renderer>
            <converter>
              <name value="preparedMessage" />
              <type value="JsonLogs.CustomLayoutConverter" />
            </converter>
            <default />
            <remove value='message' />
            <remove value='ndc' />
            <member value='message:messageObject' />
            <member value='details:preparedMessage' />
        </layout> 
    </appender>

    <appender name="Console2" type="log4net.Appender.ConsoleAppender">
        <layout type="log4net.Layout.PatternLayout">
            <converter>
              <name value="preparedMessage" />
              <type value="JsonLogs.CustomLayoutConverter" />
            </converter>
            <conversionPattern value="%level %thread %logger - %preparedMessage%newline" />
        </layout>
    </appender>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="Console" />
        <appender-ref ref="Console2" />
    </root>
</log4net>

使用我的自定义 PatternLayoutConverter 的以下实现:

namespace JsonLogs
{
    using System.IO;

    using log4net.Core;
    using log4net.Layout.Pattern;

    public class CustomLayoutConverter : PatternLayoutConverter
    {
        #region Methods

        protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            if (loggingEvent.MessageObject is string stringMessage)
            {
                writer.Write(new { message = stringMessage });
            }
            else
            {
                writer.Write(loggingEvent.RenderedMessage);
            }
        }

        #endregion
    }
}

出于某种原因,转换器与Console2 appender(不是JSON驱动)完美配合,但它不适用于输出为JSON的Console appender . 输出示例:

Console -> {"date":"2018-12-09T12:25:28.0529041+03:00","level":"INFO","appname":"JsonLogs.exe","logger":"JsonLogs.Program","thread":"1","message":"Test","details":"preparedMessage"}
Console2 -> INFO 1 JsonLogs.Program - { message = Test }

我的目标是让 details 始终使用JSON,这就是为什么我引入自己的转换器来捕获原始值并将它们包装在自定义对象中的原因 .

我的配置错了吗?或者我错过了什么?你能帮帮我解决这个问题吗?

谢谢