【问题标题】:How to enable Trace logging in ASP.NET Core?如何在 ASP.NET Core 中启用跟踪日志记录?
【发布时间】:2017-05-28 11:04:07
【问题描述】:

我无法在我的应用程序中获得基本的LogTrace(...) 输出。这是一个再现:

  1. 使用 Visual Studio 2017 创建一个新的 ASP.NET Core 应用程序。
  2. (可选)注释掉 .UseApplicationInsights() 以便重现更清晰
  3. 将ValuesController.cs中的代码替换为:

    using System.Collections.Generic;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    
    namespace WebApplication1.Controllers
    {
        [Route("api/[controller]")]
        public class ValuesController : Controller
        {
            private readonly ILogger<ValuesController> logger;
    
            public ValuesController(ILogger<ValuesController> logger)
            {
                this.logger = logger;
            }
    
            [HttpGet]
            public IEnumerable<string> Get()
            {
                logger.LogError("ERROR!");
                logger.LogWarning("WARN!");
                logger.LogInformation("INFO!");
                logger.LogTrace("TRACE!");
                return new string[] { "value1", "value2" };
            }
        }
    }
    
  4. 将appsettings.Development.json 更改为:

    {
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Trace",
          "System": "Information",
          "Microsoft": "Information"
        }
      }
    }
    
  5. 运行并查看调试输出

这导致:

  • 实际输出:

  • 预期的输出将是“TRACE!”也发消息

我也尝试过调整 appsettings.json 文件中的值,但这也没有效果。

奇怪的是,将任一文件中的值更改为 "Error" 也没有任何作用。

底线/问题

我需要做什么才能使注入的ILogger&lt;ValuesController&gt; 尊重日志记录设置,包括Trace 级别?


脚注

下面是一些相关代码,这些代码将通过上述重现自动生成:

Startup.cs

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseMvc();
    }
}

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();

        host.Run();
    }
}

appsettings.json 默认:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

【问题讨论】:

  • 请注意...从 2.0 开始,此问题将发生重大变化(感谢 @Tseng )。我相应地更新了我的答案。

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


【解决方案1】:

自 2.0 起的重大变化
正如 Tseng 在下面评论的那样,此答案将成为 自 2.0 起已过时,您可以在此处找到有关此公告的更多信息: https://github.com/aspnet/Announcements/issues/238


问题出在哪里……

根据您的Configure() 方法,我发现了一个问题:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
    ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug(); // ⇦ you're not passing the LogLevel!

    app.UseMvc();
}

这就是为什么您对appsettings.json 文件中的配置集所做的任何更改都不起作用的原因。

.AddDebug() 不传递任何参数的默认行为是
添加为 LogLevel.Information 或更高版本启用的调试记录器。

如果您想显式设置它以使用特定的最小 LogLevel,则可以将其直接传递给 AddDebug(ILoggerFactory, LogLevel) 方法。

loggerFactory.AddDebug(LogLevel.Trace);

更多信息可以在here找到。


将其绑定到您的配置。

方法一:从配置中获取值。

LogLevel foo = this.Configuration.GetSection("Logging:LogLevel")
    .GetValue<LogLevel>("Default");
loggerFactory.AddDebug(foo);

方法二:使用LogLevel的内置对象

(故意遗漏。显然它介于所提供的这两种方法之间。)我更喜欢极端之一,而不是半途而废)

方法3:手动(使用ConfigurationBinder)

花哨的ConfigurationBinder

var obj = new MyObject();
ConfigurationBinder.Bind(_configuration.GetSection("Logging:LogLevel"), obj);

这将映射到像这样的对象

public class MyObject
{
    public LogLevel Default { get; set; }
    public LogLevel System { get; set; }
    public LogLevel Microsoft { get; set; }
}

这样你就可以通过了:

loggerFactory.AddDebug(obj.Default);

关于节点和 appsettings.json 的特别说明

请注意,配置的分隔符使用:。

例如:"Logging:LogLevel" 会去:

"Logging": {
  "IncludeScopes": false,
  "LogLevel": {             ⇦⇦⇦⇦⇦ Here
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
  }
}

LogLevel 枚举

仅供参考,以下是有效的LogLevel 值:

public enum LogLevel
{
    Trace = 0,
    Debug = 1,
    Information = 2,
    Warning = 3,
    Error = 4,
    Critical = 5,
    None = 6,
}

来源:
https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.extensions.logging.loglevel#Microsoft_Extensions_Logging_LogLevel

【讨论】:

  • @Jeroen 你试过Debug 还是Verbose.. 没有Trace 这样的选项
  • 曾经有过Verbose,但在 ASP.NET Core 1.0 RC1 和 RC2 之间有一段时间改变了
  • 您更改的答案是有道理的,并且正在工作。您是否碰巧知道重用配置部分的好方法? AddDebug 似乎没有过载,或者有吗?
  • 可能值得注意的是,这将在 2.0 中发生变化(已经在 2.0 预览版中生效):Breaking Logging changes and new additions 这将允许通过 appsettings.json 配置所有日志记录提供程序
  • @Tseng - 这是一个很好的说明。感谢您发现这一点。
【解决方案2】:

这对我有用。在ConfigureServices(IServiceCollection services)方法中添加:

services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Trace));

【讨论】:

    【解决方案3】:

    我试过了:

    services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Trace));
    

    问题出在哪里……

    这些都没有帮助我。就我而言,我在带有 exe 的文件夹中有 appsettings.Development.json。此文件已将默认设置为信息。这就是我看不到 Trace 日志的原因。此文件隐藏在 Visual Studio 的解决方案资源管理器中。我必须展开 appsettings.json 才能看到这个文件。

    更改信息 => 跟踪后,我可以看到严重性跟踪的日志。

    【讨论】:

    • 很好,现在我很尴尬,因为我以某种方式错过了它
    猜你喜欢
    • 1970-01-01
    • 2016-09-09
    • 2013-11-13
    • 1970-01-01
    • 2017-01-17
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多