Send object as json to Sentry.io

1.9k views Asked by At

We're using Sentry.AspNetCore NuGet package on our web site and we are injecting ILogger<T>s here and there. Is there any way to use "structured logging syntax" and make Sentry log objects as JSON instead of just calling ToString()?

_logger.LogError("testObj = {@testObj}", new TestClass());
// (The @ forces NLog to serialize object as JSON. Looks like it's used in some of the other logging frameworks as well.)

public class TestClass
{
    public string SomeProp { get; } = "SomeValue";
    public int AnotherProp { get; } = 1337;
}

// Preferred message: testObj = {"SomeProp":"SomeValue","AnotherProp":1337}
// Actual Message: testObj = MyNameSpace.TestClass

EDIT:
Some clarification. We still use NLog to write to file and we just added UseSentry in Program.cs and kept all our ILogger<T> usages as is. It works as expected apart from the fact that Sentry(?) only uses ToString to serialize objects passed to the message string.
A solution to our problem could be to somehow inject a custom formatter into the Sentry logger. Otherwise we will have to override ToString on every class that we might want to log, or add serialization ourselves or create anonymous objects when logging.

(Logging of anonymous objects "works" since the compiler generates a custom .ToString() override that lists all properties and their stringified values. Example: https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA+ABATARgLABQGAzAATakDCpA3oaQ+WRiqQLIAUAlLfY/wDcAhlFIJSAXlIA7GAHdapACowAzgBdJpAETq167aQC+Abj4MjhI0A= )

1

There are 1 answers

5
Bruno Garcia On

Even though I see @ is in NLog's docs, try to remove the @ from your string format:

Instead of _logger.LogError("testObj = {@testObj}", new TestClass());

Write: _logger.LogError("testObj = {testObj}", new TestClass());

I'm suspecting it might be a NLog backing changing the formatter?

If I run this sample of Sentry.Extensions.Logging, without NLog, adding:

logger.LogCritical("{number} - An event with a complex object: {object}", 1, new
{
    Name = "Zealot",
    Health = "100%",
});

I see in Sentry:

1 - An event with a complex object: { Name = Zealot, Health = 100% }

It might be a limitation when using Sentry.NLog.