2

NLog Property added to log in OnActionExecutedAsync() does not render in logs.

This is ActionFilterAttribute code


/// <summary>
/// After invoke the action method
/// </summary>
public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
     ScopeContext.PushProperty("Any-Executing-Property", "Value");
     return base.OnActionExecutingAsync(actionContext, cancellationToken);
}

/// <summary>
/// Before invoke the action method
/// </summary>
public override Task OnActionExecutedAsync(HttpActionExecutedContext ctx, CancellationToken cancellationToken)
{
     ScopeContext.PushProperty("Any-Executed-Property", "Value");
     return base.OnActionExecutedAsync(ctx, cancellationToken);
}

Here is the content of the configuration file NLog.config

<target name="jsonFile"
        xsi:type="File"
        fileName="${logDirectory}/api.jsonl"
        archiveFileName="${logDirectory}/archives/api{#####}.jsonl"
        archiveAboveSize="1000240" 
        archiveNumbering="Sequence" 
        maxArchiveFiles="1"
        keepFileOpen="true" 
        concurrentWrites="false"
        encoding="UTF-8">
    <layout xsi:type="JsonLayout"
        includeAllProperties="true"
        MaxRecursionLimit="2" 
        suppressSpaces="true"
        includeScopeProperties="true">
        <attribute name="context" encode="false">
        <layout type="JsonLayout">
            <attribute name="Any-Executing-Property" layout="${scopeproperty:item=Any-Executing-Property}"/>    
            <attribute name="Any-Executed-Property" layout="${scopeproperty:item=Any-Executed-Property}"/>          
        </layout>
        </attribute>
    </layout>
    </target>

Result

{"context":{ "Any-Executing-Property": "Value" },"Any-Executing-Property":"Value"}

1 Answers1

0

Maybe try this instead:

/// <summary>
/// After invoke the action method
/// </summary>
public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
     using (ScopeContext.PushProperty("Any-Executing-Property", "Value"))
     {
         await base.OnActionExecutingAsync(actionContext, cancellationToken).ConfigureAwait(false);
     }
}

/// <summary>
/// Before invoke the action method
/// </summary>
public override async Task OnActionExecutedAsync(HttpActionExecutedContext ctx, CancellationToken cancellationToken)
{
     using (ScopeContext.PushProperty("Any-Executed-Property", "Value"))
     {
         await base.OnActionExecutedAsync(ctx, cancellationToken).ConfigureAwait(false);
     }
}
Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70