【问题标题】:Is .NET Core 2.0 logging broken?.NET Core 2.0 日志记录是否损坏?
【发布时间】:2018-01-28 15:06:00
【问题描述】:

升级到 .NET Core 2.0 (+ASP.NET Core 2.0) 后,我似乎无法获得输出的 Trace 级别日志信息。

事实上,如果我执行 dotnet new webproject 并在 Startup for Configure 中添加以下代码,我不会收到任何跟踪或调试日志消息,但我会收到两次信息和错误消息。注释掉.AddConsole()call 只会输出这些(信息和错误)一次——这表明它默认使用控制台提供程序自动配置。请记住,这是一个“文件 -> 新建”项目体验,Program.cs 中没有任何设置用于记录或配置 - 除了我添加的内容。有人看过东西吗?或者我应该为它注册一个 GitHub 问题。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Microsoft.Extensions.Logging.LogLevel.Trace);

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.Run(async (context) =>
    {
        var logger = loggerFactory.CreateLogger("Blah");
        logger.LogTrace("Hello world : Trace");
        logger.LogDebug("Hello world : Debug");
        logger.LogInformation("Hello world : Information");
        logger.LogError("Hello world : Error");

        await context.Response.WriteAsync("Hello World!");
    });
}

【问题讨论】:

  • will give me them once 你这是什么意思?
  • 已编辑;我得到两次 Info 和 Error - 但如果我取出 AddConsole() 行 - 我得到一次 Info 和 Error - 但没有 Trace 或 Debug 消息,而我们没有明确的行来说明控制台和 Trace 级别。
  • 你在开发吗?现在默认环境是生产环境..你可以试试set ASPNETCORE_ENVIRONMENT=Development; dotnet run
  • 我遇到了类似的问题。在日志语句后添加await Task.Delay(1) 让控制台显示日志。如果将其取出,则控制台上仅显示部分日志。接受的答案实际上并没有做任何事情。这似乎是一个线程问题。

标签: c# .net asp.net-core .net-core


【解决方案1】:

配置日志记录的方式发生了一些变化...推荐的方式(在this GitHub issue/announcement 中有很好的记录,现在这样做是在AddLogging 方法上配置记录器,例如

services.AddLogging(builder =>
{
    builder.AddConfiguration(Configuration.GetSection("Logging"))
        .AddConsole()
        .AddDebug();
});

还有appsettings.json 喜欢

通知

似乎有些人感到困惑,因为该示例仅演示了Console提供程序的配置,而不是所有记录器。

LogLevel 部分为所有命名空间(Default 键)或特定命名空间(System 覆盖所有命名空间以 System.* 开头的日志记录类的默认值。

这是用于TILogger<T> 中的类)。这允许为来自此命名空间的记录器设置高于或低于默认日志记录级别。

{
  "ApplicationInsights": {
    "InstrumentationKey": ""
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Information",
      "System": "Warning",
      "Microsoft": "Information"
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning",
        "System": "Information",
        "Microsoft": "Information"
      }
    }
  }
}

请注意,appsettings.json 的结构与以前在 .NET Core 1.x 中的结构有所不同,appsettings.json 中的 Logging 条目现在包含记录器提供程序名称,这使您可以为每个日志记录提供程序配置日志记录级别。

以前,appsettings.json 中的条目仅适用于控制台记录器。

或者,现在可以在WebHostBuilder 内移动日志记录。

public static void Main()
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;

            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddJsonFile("hosting.json", optional: false)
                .AddEnvironmentVariables();
        })
        .ConfigureLogging((webhostContext, builder) => {
            builder.AddConfiguration(webhostContext.Configuration.GetSection("Logging"))
            .AddConsole()
            .AddDebug();
        })
        .UseIISIntegration()
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .Build();

    host.Run();
}

更新

如果不想使用appsettings.json,也可以在代码中注册过滤器。

services.AddLogging(builder =>
{
    builder.AddConfiguration(Configuration.GetSection("Logging"))
        // filter for all providers
        .AddFilter("System", LogLevel.Debug)
        // Only for Debug logger, using the provider type or it's alias
        .AddFilter("Debug", "System", LogLevel.Information)
        // Only for Console logger by provider type
        .AddFilter<DebugLoggerProvider>("System", LogLevel.Error)
        .AddConsole()
        .AddDebug();
});

【讨论】:

  • 谢谢.. 事实上,只添加一个带有日志配置的 appsettings.json 文件,而没有任何日志设置似乎给了我我需要的东西。
  • 或只是builder.SetMinimumLevel(LogLevel.Trace);
  • 请注意,使用AddConfiguration 需要Microsoft.Extensions.Configuration 包。
  • 这是否允许将实际调试消息写入日志?也就是说,使用“LogLevel Default: Debug”,Debug.WriteLine 的输出最终会出现在日志中。因为如果不是,它没有多大用处,因为 1)我不想将 Microsoft 的日志记录类注入我的应用程序中的每个低级组件并用 _log.LogDebug 替换每个 WriteLine,2)如果我正在使用第三方组件我可能无法将 Microsoft 的日志记录类注入这些组件。
  • 我发现您的 appsettings.json 示例对于 .NET Core 2.1 不正确,这个对我有用 docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/…
【解决方案2】:

我花了将近 20 分钟才意识到,由于 Startup.cs 文件中的 Configuration.GetSection("Logging")appsettings.json 文件的配置中读取了 "Logging" 部分,配置为"Error"。将其更改为 "Information" 或任何更低的值,即可解决此问题。

这是 appsettinsg.json 文件现在的样子:

{
  "Logging": {
    "IncludeScopes": true,
    "Debug": {
      "LogLevel": {
        "Default": "Information"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Information"
      }
    }
  }
}

要了解有关日志记录级别的更多信息(例如在"Information" 中),请查看this 链接,该链接还提供了有关 ASP.NET Core 日志记录的一般信息。

我只是在这里发帖,以防万一您在使日志记录正常工作时遇到任何问题,请确保您已通过该 JSON 文件。

【讨论】:

    【解决方案3】:

    以上都不适合我 唯一的解决方法是编写一个方法

    private void ConfigLogging( ILoggingBuilder builder ) {
        builder.SetMinimumLevel( LogLevel.Trace );
        //... additional configuration...
    }
    

    并且在使用 AddLogging 扩展方法时将其写为

    services.AddLogging( ConfigLogging );
    

    【讨论】:

    • 您确定您的 appsettings.json 格式正确吗?或者,如果该值被其他配置源之一(开发设置、环境变量等)覆盖?
    • 我通过添加这一行来解决它:.ConfigureLogging((hostingContext, logging) =&gt; { ... logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); ... })
    • 几乎就好像“Trace”被特殊对待,并且如果在声明的代码而不是配置文件中,只会被视为日志级别。但我没有看到任何文件。
    【解决方案4】:

    appsettings.json 的以下结构似乎可以正常工作:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "System": "Information",
          "Microsoft": "Information"
        },
        "Console":
        {
          "IncludeScopes": true
        }
      }
    }
    

    取自https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.1

    另外,看看你的启动电话是什么,我发现以下对我有用:

    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
    
            var logger = new LoggerConfiguration()
                    .MinimumLevel.Information()
                    .WriteTo.Sink(jsonSink)
                    .Enrich.WithExceptionDetails()
                    .CreateLogger();
    
            Log.Logger = logger;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 2018-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多