Search code examples
c#.netnlog

How to capture controller name when it actually not controller in nlog .net core?


NLog can capture the controller name and action using {aspnet-mvc-controller} and {aspnet-mvc-action} configuration options, it works fine.

In my case, there is an action that not using a controller pattern (tusdotnet). When I want to log activity on that action, the values in {aspnet-mvc-controller} and {aspnet-mvc-action} are empty.

Is there a way to manually set {aspnet-mvc-controller} and {aspnet-mvc-action}?


Solution

  • ${aspnet-mvc-controller} and ${aspnet-mvc-action} extracts their values (controller + action) from HttpContext.Current.GetRouteData.

    If there is no HttpContext, then you can consider implementing a fallback-value using whenEmpty=. Ex. Logging like this:

    logger.WithProperty("MvcAction", "myAction")
          .WithProperty("MvcController", "myController")
          .Info("Hello World");
    

    And then configure the layout like this:

    • ${event-properties:MvcAction:whenEmpty=${aspnet-mvc-action}}
    • ${event-properties:MvcController:whenEmpty=${aspnet-mvc-controller}}

    Instead of using ${event-properties} then you could also use ScopeContext / BeginScope. See also: https://github.com/NLog/NLog/wiki/Context

    See also: https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-properties-with-Microsoft-Extension-Logging