.NET Core 2.0 日志记录损坏了吗? [英] Is .NET Core 2.0 logging broken?

查看:28
本文介绍了.NET Core 2.0 日志记录损坏了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can't seem to get Trace level log information outputted after upgrading to .NET Core 2.0 (+ASP.NET Core 2.0).

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

In fact, if I do a dotnet new webproject and add the code below in Startup for Configure, I do not get any trace or debug log messages, but I get the Information and Error messages twice. Commenting out the .AddConsole()call will output these (Information and Error) only once - suggesting that it gets configured automatically with a console provider by default. Keep in mind, this is a "File -> New" project experience, there is nothing setup in Program.cs for logging or configuration at all for this - except for what I've added. Anyone seen things? Or should I register a GitHub issue for it.

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!");
    });
}

推荐答案

日志记录的配置方式发生了一些变化……推荐的方式(在 这个GitHub issue/announcement现在要做的是在AddLogging方法上配置loggers,比如>

The way logging is configured has changed a little... The recommended way (and it's pretty well documented in this GitHub issue/announcement to do it now is to configure the loggers on the AddLogging method, such as

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

并有一个 appsettings.json

好像有些人搞糊涂了,因为这个例子只展示了Console provider的配置,并不是所有的loggers.

Seems a few people are confused, because the example only demonstrates the configuration of Console provider and not all loggers.

LogLevel 部分为所有命名空间(Default 键)或特定命名空间(System 覆盖所有命名空间的默认值)配置日志记录级别命名空间以 System.*.

The LogLevel section configures logging level for all namespaces (Default key) or for a specific namespace (System overrides the default value for all classes logging whose namespace starts with System.*.

这是用于 ILogger 中的 T 中使用的类.这允许为此命名空间中的记录器设置高于或低于默认日志记录级别.

This is for the class used in T in ILogger<T>). This allows to set a higher or lower than default logging level for loggers from this namespace.

{
  "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 条目不同现在有记录器提供者名称,它允许您配置每个记录提供者的记录级别.

Please note that the structure of the appsettings.json changed from what it used to be in .NET Core 1.x and that Logging entry in the appsettings.json now has logger provider names in it, which allows you to configure logging levels per logging provider.

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

Previously, the entry in appsettings.json would only be applicable to the console logger.

或者,现在可以在 WebHostBuilder 中移动日志记录.

Alternatively, the logging can now be moved within the WebHostBuilder instead.

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,也可以在代码中注册过滤器.

Update

In case one doesn't want to use the appsettings.json, one can register the filters in code too.

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();
});

这篇关于.NET Core 2.0 日志记录损坏了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆