Search code examples
asp.net-corenlog.net-6.0

Using GlobalDiagnosticsContext in NLog internalLogFile


Is it possible to add a custom variable to the internalLogFile attribute in the nlog.config file, like ProjectName in internalLogFile="c:\logs\${gdc:ProjectName}\internal-nlog.txt"?

I tried this:

<nlog internalLogFile="c:\logs\${gdc:ProjectName}\internal-nlog.txt">
  ...
</nlog>

and

private static void ConfigureLogging(IServiceCollection services)
{
    GlobalDiagnosticsContext.Set("ProjectName", "some-project-name");
    LogManager.LoadConfiguration("nlog.config");

    services.AddLogging(loggingBuilder =>
    {
        loggingBuilder.AddConfiguration(Config.GetSection("Logging"));
        loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Debug);
        loggingBuilder.AddNLog();
    });
}

But LoadConfiguration throws an error (caught as first-chance exception in VS, so it's actually silently ignored):

System.IO.IOException: The directory name is invalid. : 'c:\logs\${gdc:ServiceRunnerFolder}'

I stepped through NLog code and it seems it only calls ExpandFilePathVariables to expand some known environment variables before setting the filename.

Is there a way to use a custom variable for this filename, without creating environment variables?


Solution

  • Instead of using ${gdc} and GlobalDiagnosticsContext.Set("ProjectName", "some-project-name"); then just update the InternalLogger directly:

    var projectName = "some-project-name";
    NLog.Common.InternalLogger.LogFile = $"c:\logs\{some-project-name}\internal-nlog.txt";
    

    See also: https://github.com/NLog/NLog/wiki/Internal-Logging#example-with-internal-logging-from-code