Search code examples
.net-coreasp.net-core-webapinlog

NLOG - Redirect single webapi controller method logs to specific file


I have a .NET Core 5 Web API that utilizes NLog, currently capturing all the logs in a single file, which is archived daily.

I aim to redirect only the logs generated by a specific controller method to a dedicated file. Is this possible?

I've conducted some tests, but the configuration I've attempted doesn't seem to work:

{
  "logger": "XXX.WebAppApiTest.Controllers.MyController.MyMethod",
  "minLevel": "Info",
  "writeTo": "singleMethodLogFile"
}

other section:

"singleMethodLogFile": {
  "type": "File",
  "fileName": "${aspnet-appbasepath}/Logs/MyMethod_${shortdate}.log",
  "archiveFileName": "${aspnet-appbasepath}/Logs/Archive/MyMethod_${shortdate}.log",
  "maxArchiveFiles": "1",
  "archiveEvery": "Day"
}

Would anyone be able to provide guidance on how to achieve this? Thank you. Thanks to support


Solution

  • Maybe create the _methodLogger for the controller like this:

    public class MyController
    {
        private readonly ILogger _logger;
        private readonly ILogger _methodLogger;
    
        public MyController(ILogger<MyController> logger, ILoggerFactory loggerFactory)
        {
           _logger = logger;
           _methodLogger = loggerFactory.CreateLogger($"{GetType()}.{nameof(MyMethod)}");
        }
    
        public void MyMethod()
        {
           _methodLogger.LogInfo("Hello from method");
        }
    }
    

    Then you can explicit redirect the output from the _methodLogger like this:

    {
      "logger": "MyNameSpace.MyController.MyMethod",
      "minLevel": "Info",
      "writeTo": "singleMethodLogFile"
    }