在 .NetCore 控制台应用程序中使用 Nlog 和 ILoggerFactory 时未打印调试和跟踪日志

Debug and trace logs not printed when using Nlog and ILoggerFactory in .NetCore console app

虽然在 appsettings.json 上将最小级别设置为 Trace,但未打印调试和跟踪日志。 实际输出:

FATAL|ConsoleAppLogging.Program|LogCritical
ERROR|ConsoleAppLogging.Program|LogError
INFO|ConsoleAppLogging.Program|LogInformation
WARN|ConsoleAppLogging.Program|LogWarning

我创建了一个示例项目存储库,可以在此处找到 https://github.com/yaniv120892/ApplicationLogging

使用 .NetCore 3.1 和软件包:

appsettings.Json:

{
  "NLog": {
    "targets": {
      "logConsole": {
        "type": "ColoredConsole",
        "layout": "${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"
      }
    },
    "rules": [
      {
        "name": "*",
        "minLevel": "Trace",
        "writeTo": "logConsole"
      }
    ]
  }
}

ApplicationLogging.cs:

 public static class ApplicationLogging
    {
        public static ILogger CreateLogger<T>() =>
            s_loggerFactory.CreateLogger<T>();

        private static readonly ILoggerFactory s_loggerFactory = LoggerFactory.Create(AddNLog);

        private static void AddNLog(ILoggingBuilder builder)
        {
            var configJson = new ConfigurationBuilder()
                .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
            LogManager.Configuration = new NLogLoggingConfiguration(configJson.GetSection("NLog"));
            builder.AddNLog();
        }
    }

Program.cs:

public class Program
    {
        private static readonly ILogger s_logger = ApplicationLogging.CreateLogger<Program>();

        static void Main()
        {
            s_logger.LogCritical("LogCritical");
            s_logger.LogDebug("LogDebug");
            s_logger.LogError("LogError");
            s_logger.LogInformation("LogInformation");
            s_logger.LogTrace("LogTrace");
            s_logger.LogWarning("LogWarning");
        }
    }

觉得你少了SetMinimumLevel:

public static class ApplicationLogging
{
    public static ILogger CreateLogger<T>() => s_loggerFactory.CreateLogger<T>();

    private static readonly ILoggerFactory s_loggerFactory = LoggerFactory.Create(AddNLog);

    private static void AddNLog(ILoggingBuilder builder)
    {
        var configJson = new ConfigurationBuilder()
            .SetBasePath(System.IO.Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
        var nlogConfig = new NLogLoggingConfiguration(configJson.GetSection("NLog"));
        builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
        builder.AddNLog(nlogConfig);
    }
}