using Nlog and writing to file as json

我的梦境 提交于 2019-12-04 04:18:48

As of the release of NLog 4.0.0 it is possible to use a layout that renders events as structured JSON documents.

Example taken from NLog project site:

<target name="jsonFile" xsi:type="File" fileName="${logFileNamePrefix}.json">
    <layout xsi:type="JsonLayout">
        <attribute name="time" layout="${longdate}" />
        <attribute name="level" layout="${level:upperCase=true}"/>
        <attribute name="message" layout="${message}" />
    </layout>
</target>

Edit: You can also create it in code.

Here is the link to the specific part of documentation.

And here the copied example:

var jsonLayout = new JsonLayout
{
    Attributes =
    {
        new JsonAttribute("type", "${exception:format=Type}"),
        new JsonAttribute("message", "${exception:format=Message}"),
        new JsonAttribute("innerException", new JsonLayout
        {

            Attributes =
            {
                new JsonAttribute("type", "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
                new JsonAttribute("message", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
            }
        },
        //don't escape layout
        false)
    }
};

For more info read the docs.

Stan Bruce

As per NLog documentation: json-encode will only escape output of another layout using JSON rules. It will not "convert" the output to JSON. You'll have to do that yourself.

'{ "date":"${longdate}","level":"${level}","message":${message}}'

Take a look at this question for more details.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!