Skip to content

Documentation: Pushing properties to logevents #212

Closed
@svrooij

Description

@svrooij

This integration is great, it enables developers to just use the default ILogger in dotnet and configure the logging with serilog. I was however missing the following information, as found here

It would be great to have this added to the main readme of this module.

1. If the state argument is IEnumerable<KeyValuePair<string, object>>, the values are attached to the event directly
This may not be entirely intuitive, if you think of Scope as a trail of breadcrumbs. If you’ve dealt with correlating log events in a distributed application, you’ll recognize that often you’re interested in log events related to a specific transaction, customer, request, thread, machine or endpoint.

In the absence of any other API for the purpose, BeginScope() is how these correlation ids need to be attached in Microsoft.Extensions.Logging:

using (logger.BeginScope(new Dictionary<string, object>{
    ["CustomerId"] = 12345,
    ["OrderId"] = 54
}))
{
    logger.LogInformation("Processing credit card payment");
}
In this case, events created in the scope will have two additional properties attached: CustomerId and OrderId.

Types that implement IEnumerable<KeyValuePair<string, object>> rarely have any other useful representation; ToString() on a dictionary generally just provides the type name. These values therefore don’t result in a breadcrumb-like Scope property.

Something like:

Pushing properties to the logger

When using the ILogger from Microsoft.Extensions.Logging you cannot push properties like you would with the ILogger from Serilog. If you still want to push properties you can do with the following code:

using (logger.BeginScope(new Dictionary<string, object>
            {
                ["UserId"] = "xxx",
                ["ExtraProperty"] = "yyy",
            }))
{
   // UserId and ExtraProperty are set for all logging events in these brackets
}

The above code results in the same as if using the regular serilog ILogger with this code

using (logger.PushProperty("UserId", "xxx"))
using (logger.PushProperty("ExtraProperty", "yyy"))
{
    // UserId and ExtraProperty are set for all logging events in these brackets
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions