2
votes

I'm having a problem with logging Debug level messages in a .NET Core 3.1 Worker Service project. Neither my file target or console are getting Debug level messages logged. Information level events are written as expected. I have reviewed an older question with the same title to ensure all those boxes are checked.

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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="%appdata%\FileTransferService\nlog-internal.log">

  <variable name="logdir" value="${specialfolder:folder=ApplicationData}/FileTransferService"/>
  <variable name="stdlayout" value="${longdate}|${level:uppercase=true}|${message:exceptionSeparator=|}${exception:format=ToString}"/>

  <targets>  
    <target name="default" xsi:type="AsyncWrapper" overflowAction="Block">
      <target name="defaultlog" xsi:type="File"
              fileName="${logdir}/dftslog.txt"
              layout="${stdlayout}"
              archiveEvery="Month" concurrentWrites="false"/>
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Debug" writeTo="default"/>
  </rules>
</nlog>

appsettings.json

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

I've tried setting both the Microsoft and Microsoft.Hosting.Lifetime also to Debug, but that had no effect.

Program.CreateHostBuilder method

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseWindowsService()
        .ConfigureLogging((context, logBuilder) => {
            logBuilder.ClearProviders();
            logBuilder.AddConfiguration(context.Configuration.GetSection("Logging"));
            logBuilder.SetMinimumLevel(LogLevel.Debug);
            logBuilder.AddConsole();
            logBuilder.AddNLog();
        })
        .ConfigureServices((hostContext, services) => {
            services.AddHostedService<Worker>();
            services.AddTransient(typeof(ITransferService), typeof(TransferService));
        });

Here are a few additional notes:

  • I tried calling SetMinimumLevel with no effect.
  • The NLog.config is set to Copy Always.
  • I get the same results without AddConsole. That was actually added after I saw that debug messages weren't getting logged.
3
This sample application has no issue with logging to debug and trace: github.com/NLog/NLog.Extensions.Logging/blob/master/examples/… - Rolf Kristensen
Unfortunately, the contents of the repository didn't solve any problems. I'll put in some details of what I tried in a follow-up comment. - Anthony T.
Although the repository is for .NET Core 2 that Rolf K. provided, I thought it might still help. I noticed right off that he was able to use UseNLog instead of AddNLog in the builder. That turned out to be because I had added the package NLog.Extensions.Logging instead of NLog.Extensions.Hosting. I also streamlined my configuration so all it did was call SetMinimumLevel. Problem still there. Next, I removed the contents of appsettings.json completely. That didn't solve the problem either. I also added a call to LogManager.Shutdown in a finally block, but I didn't expect that to be material. - Anthony T.
Possible that you could create a new issue here github.com/NLog/NLog.Extensions.Logging/issues/new and attach the source code for your sample application that fails to log - Rolf Kristensen
Maybe the solution is in this answer?stackoverflow.com/a/59777331/201303 - Julian

3 Answers

3
votes

When using NLog together with Microsoft-Extension-Logging (MEL), then NLog becomes a LoggingProvider in the MEL-LoggerFactory.

This means any filtering configured in MEL-LoggerFactory always wins, independent of NLog.config.

MEL-LoggerFactory will automatically load its filtering from appsettings.json (along with any environment-specific appsettings.development.json or appsettings.production.json).

Even if having called SetMinimumLevel(LogLevel.Debug), then any configuration in appsettings.json will override this.

See also: https://github.com/NLog/NLog.Web/wiki/Missing-trace%5Cdebug-logs-in-ASP.NET-Core-3%3F

1
votes

The problem appears to be with Visual Studio 2019.

Although the problem itself persists, the debug level events are written to both the console and the flat file when I run the application outside of Visual Studio. This is not due to the debugger as I might have expected, because it exhibits the same behavior if I run it without the debugger within Visual Studio.

I looked through Visual Studio settings and did a quick search, but I couldn't find anything related. That said, knowing that the events will be logged outside of Visual Studio solves my problem to the extent necessary.

1
votes

To add to the accepted answer (not enough points for a comment):

Same problem. But it also works correctly from within VS2019 when I use

private static Logger _logger = LogManager.GetCurrentClassLogger();

which I prefer over DI to get my logger (mainly because I like writing .Warn(...) over .LogWarning(...)

I still set up DI for NLog so external/ms libraries will use it