Home > Blockchain >  Using GlobalDiagnosticsContext in NLog internalLogFile
Using GlobalDiagnosticsContext in NLog internalLogFile

Time:06-12

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?

CodePudding user response:

Never mind, I found the docs, it seems it's not possible as of NLog 5:

When you configure NLog using Configuration File, you can enable internal logging by setting the following attribute on the element:

  • internalLogFile="file.txt" - adding internalLogFile cause NLog to write its internal debugging messages to the specified file. This includes any exceptions that may be thrown during logging.
    • Note: only a few layouts are supported, as the internal log needs to be as stable as possible.
    • NLog 4.6 : Environment Variables are also supported: e.g. %appdata% or %HOME%
    • NLog 4.6 : Supports renderers (without options): ${currentdir}, ${basedir}, ${tempdir}
    • NLog 4.7.1 : Supports renderer (without options): ${processdir}
    • NLog 5.0 : Supports renderers (without options): ${commonApplicationDataDir}, ${userApplicationDataDir}, ${userLocalApplicationDataDir}

CodePudding user response:

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

  • Related