3

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.
Julian
  • 33,915
  • 22
  • 119
  • 174
Anthony T.
  • 268
  • 2
  • 11
  • 1
    This sample application has no issue with logging to debug and trace: https://github.com/NLog/NLog.Extensions.Logging/blob/master/examples/NetCore2/HostingExample/Program.cs – Rolf Kristensen Feb 13 '20 at 20:54
  • 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. Feb 13 '20 at 22:34
  • 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. Feb 13 '20 at 22:51
  • Possible that you could create a new issue here https://github.com/NLog/NLog.Extensions.Logging/issues/new and attach the source code for your sample application that fails to log – Rolf Kristensen Feb 13 '20 at 23:38
  • 2
    Maybe the solution is in this answer?https://stackoverflow.com/a/59777331/201303 – Julian Feb 14 '20 at 05:16
  • As logBuilder.AddConsole() gives the same issue, it should be an issue outside NLog. Because that isn't the console of NLog. – Julian Feb 14 '20 at 05:19

4 Answers4

4

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

Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70
  • appsettings.development.json got me - it defaults in here to Information, not Trace/Debug – Rich Apr 27 '21 at 09:51
1

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.

Anthony T.
  • 268
  • 2
  • 11
  • 1
    Notice that your project might have multiple `appsettings.json` files. One for each environment. Ex. `appsettings.development.json`, `appsettings.Production.json` etc. See also https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments (There is also something called `launchSettings.json`) – Rolf Kristensen Feb 14 '20 at 22:28
  • Thanks. I always make sure my appsettings.development.json match. I don't see anything with launchSettings.json, but that article does mention ASP.NET Core and not .NET Core. – Anthony T. Feb 16 '20 at 00:24
  • Thank you very much! It took me a long time to find this out! – Patrick Koorevaar Apr 23 '20 at 19:53
1

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

0

Rolf has the correct answer. Here is a sample code that will allow you to add Trace level during DEBUG sessions.

_services.AddLogging(loggingBuilder =>
{
    #if DEBUG
    // Add Trace/Debug statements to the output.
    loggingBuilder.Services.TryAddEnumerable(                    
        ServiceDescriptor.Singleton<IConfigureOptions<LoggerFilterOptions>>(
            new ConfigureOptions<LoggerFilterOptions>(
                options => options.MinLevel = LogLevel.Trace)));
    #endif
    loggingBuilder.AddNLog(NLog.LogManager.Configuration);
});
Scyssion
  • 374
  • 5
  • 7