Search code examples
c#jsonnlogstackdriver

How to use NLog with JsonPayload in Stackdriver Programmatically


I'm attempting to send logs to Stackdriver using NLog with a JsonLayout and JsonPayload. However, my JsonAttributes aren't showing up as separate fields/labels in the JsonPayload. The only attribute showing up in the payload currently is "message."

Here's my target code:

            var stackdriverTarget = new GoogleStackdriverTarget
            {
                ProjectId = "development-212820",
                Name = "stackdriver",
                LogId = "science",
                IncludeEventProperties = true, 
                Layout = new JsonLayout
                {
                    Attributes =
                    {
                        new JsonAttribute("message", "${message}",false),
                        new JsonAttribute("exception", "${exception:format=toString}",false)
                    }
                },
                SendJsonPayload = true
            };

which ends up in GCP as this

I'm assuming I'm doing something wrong here, but I can't - for the life of me - figure out what that is. I've used the GCP Logging Client Library before, and these types of things would have normally just been labels, but I'd like to leverage NLog and the JsonPayload. I've seen the stack article Using Nlog to write structured logs to Google Stackdriver, which hasn't answered my question.


Solution

  • Try using ContextProperties like this:

            var stackdriverTarget = new GoogleStackdriverTarget
            {
                ProjectId = "development-212820",
                Name = "stackdriver",
                LogId = "science",
                Layout = "${message}",
                SendJsonPayload = true,
                IncludeEventProperties = true, 
                ContextProperties = { new TargetPropertyWithContext("exception", "${exception:format=toString}") },
            };
    

    If you want to completely override the JsonPayload (has a performance hit), then you can upgrade to Google.Cloud.Logging.NLog ver. 3.2.0 and activate EnableJsonLayout.