Home > Software design >  NLog: Is it possible to render the Exception.Data dictionary the same way IncludeEventProperties doe
NLog: Is it possible to render the Exception.Data dictionary the same way IncludeEventProperties doe

Time:06-24

Is it possible to get NLog using JsonLayout to write out the Exception.Data dictionary as actual JSON instead of just a single attribute serialized with its toString?

The closest I have been able to get is this:

<attribute name='data' layout='${exception:format=data}' />

which becomes

    "exception": {
        "type": "System.IO.InvalidDataException",
        "message": "Invalid PERSON identifier: xyz",
        "data": "entity: PERSON;value: xyz",
        "stacktrace": "..."
    }

or this

<attribute name='exception' layout='${exception:format=@}'/>

which becomes

"exception": "{\"Type\":\"System.IO.InvalidDataException\", \"Message\":\"Invalid PERSON identifier: xyz\", \"Data\":{\"entity\":\"PERSON\",\"value\":\"xyz\"}, \"TargetSite\":\"Void MoveNext()\", \"StackTrace\":\"...\", \"HResult\":-2146233087}"

Ideally I would like to see a layout configuration that yields:

    "exception": {
        "type": "System.IO.InvalidDataException",
        "message": "Invalid PERSON identifier: xyz",
        "data": {
            "entity": "PERSON",
            "value": "xyz",
        }
        "stacktrace": "..."
    }

This configuration will output event properties the way I want:

<attribute name="properties" encode="false" >
  <layout type='JsonLayout' includeAllProperties="true" maxRecursionLimit="10"/>
</attribute>
    "properties": {
        "controllerName": "Person",
        "actionName": "Lookup"
    }

But I haven't found a valid configuration that does the same thing for Exception.Data. Has anyone been able to accomplish this without manually adding every possible dictionary key to the configuration as an attribute using ${exceptiondata:item=entity} etc?

CodePudding user response:

When using format=@ then it will output in json-format, but then you have to use encode="false" to avoid encoding as string-property:

<attribute name="exception" layout="${exception:format=@}" encode="false" />

Notice that some exceptions are dangerous, where the data-dictionary enumerates an entire database. You can use RegisterObjectTransformation to override the transformation of those exceptions.

See also: https://github.com/NLog/NLog/wiki/How-to-use-structured-logging#transform-captured-properties

  • Related