Search code examples
c#scopeazure-application-insightsnlogcustom-dimensions

Why is NLog not logging scope data to Application Insights custom Dimensions


I am currently logging to Application Insights using NLog configured in an nlog.config file. I don't have IncludeScopes set anywhere (it is true by default).

I am trying to log custom properties using scope. It works when logging to a file or the console but not when logging to the Application Insights customDimensions.

This is how I am logging my scope:

using (_logger.BeginScope(new Dictionary<string, object> { ["ActivityId"] = Guid.NewGuid()})
{
    _logger.LogInformation("Logging from with scope");
}

and this is the nlog.config file:

<target name="applicationInsights" xsi:type="ApplicationInsightsTarget" >
    <instrumentationKey>8d9f67d5-fe36-45cf-935f-2f87bb240b12</instrumentationKey>
    <!-- Only required if not using ApplicationInsights.config -->
    <contextproperty name="threadId" layout="${threadid}" />
    <contextproperty name="processName" layout="${processname}" />
    <!-- Can be repeated with more context -->
</target>

Unfortunately I don't see the ActivityId when I look in the customDimensions in Application Insights.

I am running my Console app in Azure so have registered a worker service (which processes messages) like this:

services.AddHostedService<PositionMessageProcessor>()

What do I need to do get the logging scope to log my ActivityId in Application Insights?

Update

I have managed to it logging the ActivityId by adding it as a specific contextProperty. I don't really want to have to update the config file everytime I call BeginScope(...) with different properties.

Is there a generic way to get it to work for all scope properties?


Solution

  • Is there a generic way to get it to work for all scope properties?

    I assume you mean that it sends all the scoped properties to application insights without specifying which keys.

    Currently this isn't supported by the target, see source.

    In NLog 4, the scope properties are pushed to the NestedDiagnosticsLogicalContext.

    You could do that by creating your own target:

    1. Copy the target from source
    2. Loop over NestedDiagnosticsLogicalContext.GetAllObjects() in BuildPropertyBag inside ApplicationInsightsTarget.
    3. Register your target, see NLog-Register your custom component