且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将NLog属性设置为JSON?

更新时间:2023-02-16 16:04:30

好吧,NLog中似乎有一个错误,所以我有点自己制作了渲染器.这就是我所做的.首先,我使用JSON.NET进行了扩展:

Well, it looks like there's a bug in NLog, so I kinda made my own renderer. Here's what I did. First, I made an extension method using JSON.NET:

public static string ToJson(this object obj, bool format = false, string dateFormat = null)
{
    var settings = new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    };

    if (!String.IsNullOrWhiteSpace(dateFormat))
    {
        settings.Converters = new List<JsonConverter>
        {
            new IsoDateTimeConverter {DateTimeFormat = dateFormat}
        };

        return JsonConvert.SerializeObject(obj, format ? Formatting.Indented : Formatting.None, settings);
    }

    return JsonConvert.SerializeObject(obj, format ? Formatting.Indented : Formatting.None, settings);
}

...接下来,我像这样创建了一个LayoutRenderer:

...next, I created a LayoutRenderer like so:

[LayoutRenderer("json-event-properties")]
public class JsonEventPropertiesLayoutRenderer : LayoutRenderer
{
    /// <summary>
    /// Renders the specified environmental information and appends it to the specified <see cref="T:System.Text.StringBuilder" />.
    /// </summary>
    /// <param name="builder">The <see cref="T:System.Text.StringBuilder" /> to append the rendered data to.</param>
    /// <param name="logEvent">Logging event.</param>
    protected override void Append(StringBuilder builder, LogEventInfo logEvent) {
        if (logEvent.Properties == null || logEvent.Properties.Count == 0)
            return;
        var serialized = logEvent.Properties.ToJson();
        builder.Append(serialized);
    }
}

在我的应用程序中,启动时,我这样注册了LayoutRenderer:

In my application, when starting up, I registered my LayoutRenderer like so:

LayoutRenderer.Register<JsonEventPropertiesLayoutRenderer>("json-event-properties");

...最后,我像这样配置NLog目标:

... and finally, I configured the NLog target like this:

    <layout xsi:type="JsonLayout">
    <attribute name="timestamp" layout="${longdate}"/>
    <attribute name="level" layout="${level:uppercase=true}"/>
    <attribute name="exception" layout="${onexception:${exception:format=tostring}}" />
    <attribute name="message" layout="${message}" />
    <attribute name="properties" layout="${json-event-properties}" encode="false"/>
  </layout>

以这种方式运行,JSON格式正确,并且可以访问我的LogEventInfo对象中的属性.

Running like this, the JSON properly formatted and I got access to the properties in my LogEventInfo object.