如何在ASP.NET Core中启用跟踪日志记录?

时间:2017-05-28 11:04:07

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

我的应用程序无法获得basice LogTrace(...)输出。这是一个复制品:

  1. 使用Visual Studio 2017创建新的ASP.NET核心应用程序。
  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. 运行并查看Debug输出

  6. 这导致:

    • 实际输出:

      only ERROR, WARN, and INFO

    • 预期的输出将是“TRACE!”消息以及

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

    奇怪的是,将任一文件中的值更改为"Error"也无效。

    底线/问题

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

    脚注

    以下是使用上述repro自动生成的一些相关代码:

    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"
        }
      }
    }
    

3 个答案:

答案 0 :(得分:12)

  

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

将其绑定到您的配置。

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

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

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

(故意遗漏。很明显,它提供了这两种方法之间的紧密关系。)我赞成其中一个极端,而不是半途而废)

方法3:Go Manual(使用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 Enum

仅供参考,以下是有效的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

答案 1 :(得分:7)

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

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

答案 2 :(得分:0)

我试过了:

services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Trace));
<块引用>

问题出在哪里...

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

在我更改 Information => Trace 后,我可以看到严重性为 Trace 的日志。

相关问题