0
votes

I have looked at numerous configurations for nLog in .net core, all is working, except that I cannot get a debug message to log. If I write an information message or error message those work just fine. So this seems like a logging level problem, but try as I might I can't seem to get the level low enough to write out debug messages.

I have also looked at this: Missing trace\debug logs in ASP.NET Core 3?

Nlog.Web.AspNetCore 4.11 .Net Core 3.1

Here is my configuration:

nothing logging specific in startup.cs

program.sc

  public static void Main(string[] args)
    {
        var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        try
        {
            logger.Debug("init main");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception exception)
        {
            //NLog: catch setup errors
            logger.Error(exception, "Stopped program because of exception");
            throw;
        }
        finally
        {
            // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
            NLog.LogManager.Shutdown();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
          .ConfigureLogging(logging =>
          {
              logging.ClearProviders();
              logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
          })
          .UseNLog();  

appsettings.json

  "Logging": {
"LogLevel": {
  "Default": "Trace",
  "Microsoft": "Warning",
  "Microsoft.Hosting.Lifetime": "Information"
}

nlog.config

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    autoReload="true"
    throwConfigExceptions="true"
    internalLogLevel="info"
    internalLogFile="c:\temp\Nlog.log">

  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>
  <targets>
    <target name="database" xsi:type="Database" connectionString="${appsettings:name=ConnectionStrings.applog}" >
      <commandText>
        INSERT INTO [NLog] (
        [ApplicationName],
        [AppUserIdentity],
        [LogDate] ,
        [LogLevel] ,
        [LogSource],
        [LogAssembly] ,
        [LogMessage] ,
        [MachineName] ,
        [DomainUser],
        [CallSite],
        [LogThread] ,
        [LogException]  ,
        [ClientIp]
        )
        VALUES     (
        @ApplicationName,
        @AppUserIdentity,
        @LogDate ,
        @LogLevel ,
        @LogSource,
        @LogAssembly,
        @LogMessage ,
        @MachineName ,
        @DomainUser ,
        @CallSite ,
        @LogThread ,
        @LogException,
        @ClientIp
        );

      </commandText>

      <parameter name="@ApplicationName" layout="${appsettings:name=AppName:default=Missing-Config}" />
      <parameter name="@AppUserIdentity" layout="${aspnet-user-identity}" />
      <parameter name="@LogDate" layout="${date:format=yyyy-MM-dd HH\:mm\:ss.fff}" />
      <parameter name="@LogLevel" layout="${level}" />
      <parameter name="@LogSource" layout="${logger} " />
      <parameter name="@LogAssembly" layout="${assembly-version}" />
      <parameter name="@LogMessage" layout="${message}" />
      <parameter name="@MachineName" layout="${machinename}" />
      <parameter name="@DomainUser" layout="${windows-identity:domain=true}" />
      <parameter name="@CallSite" layout="${callsite}" />
      <parameter name="@LogThread" layout="${threadid}" />
      <parameter name="@LogException" layout="${exception}" />
      <parameter name="@ClientIp" layout="${aspnet-request-ip}" />


      
    </target>
  </targets>

  <rules>
    <logger name="*"  minlevel="Trace" maxlevel="Error" final="true" writeTo="database" />
  </rules>
</nlog>

injected into a service. This call will not log, but if it were _logger.LogInformation("xx"), it will log. This ILogger reference is Microsoft.Extensions.Logging.ILogger

     public TaxCalculationService(IUnderwritingRepository repository, ILogger<TaxCalculationService> logger)
        {
            _repository = repository;
            _logger = logger;
        }
        public TaxCalculationResponseDto CalculateTaxes(TaxCalculationRequestDto request)
        {
          
            _logger.LogDebug("calculateTaxes request: " + JsonConvert.SerializeObject(request));
1
When you looked at Missing Debug/Trace Messages in NetCore did you remember to check the environment-specific appsettings.json ? (Ex. appsettings.Development.json and appsettings.Production.json) - Rolf Kristensen
Yes I had looked at that. Thanks - kwcolson98

1 Answers

2
votes

Please try to upgrade to NLog.Web.AspNetCore v4.12.0, and then change UseNLog() to use RemoveLoggerFactoryFilter = true like this:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
          .ConfigureLogging(logging =>
          {
              logging.ClearProviders();
              logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
          })
          .UseNLog(new NLogAspNetCoreOptions() { RemoveLoggerFactoryFilter = true });

See also: https://github.com/NLog/NLog.Extensions.Logging/pull/482

You might want to update the NLog-LoggingRules to ignore noise from Microsoft-Loggers:

<rules>
   <!-- Block output from noisy loggers -->
   <logger name="Microsoft.*" maxlevel="Info" final="true" />
   <logger name="System.Net.Http.*" maxlevel="Info" final="true" />
   
   <!-- Write the good stuff to the databse -->
   <logger name="*"  minlevel="Debug" writeTo="database" />
</rules>