如何在ASP.NET Core中启用跟踪日志记录? [英] How to enable Trace logging in ASP.NET Core?

查看:143
本文介绍了如何在ASP.NET Core中启用跟踪日志记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在应用程序中获得基本LogTrace(...)输出.这是一个复制品:

I cannot get basice LogTrace(...) output in my application. Here's a repro:

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

  1. Create a new ASP.NET Core application using Visual Studio 2017.
  2. (Optional) comment out .UseApplicationInsights() so the repro is clearer
  3. Replace the code in ValuesController.cs with this:

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

  • appsettings.Development.json更改为此:

  • Change appsettings.Development.json to this:

    {
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Trace",
          "System": "Information",
          "Microsoft": "Information"
        }
      }
    }
    

  • 运行并查看Debug输出

  • Run and view the Debug output

    这导致:

    • 实际输出:

    • Actual output:

    预期输出为"TRACE!"消息

    Expected output would be the "TRACE!" message as well

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

    I've tried tweaking the values in the appsettings.json file as well, but that had no effect either.

    奇怪的是,将两个文件中的值都更改为"Error"都没有任何作用.

    Weirdly, changing the value in either file to "Error" doesn't do anything either.

    我该怎么做才能使注入的ILogger<ValuesController>遵守日志记录设置,包括Trace级别?

    What do I need to do to make my injected ILogger<ValuesController> respect the logging settings, including Trace level?

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

    Here's some of the relevant code that would be auto-generated with the above 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"
        }
      }
    }
    

    推荐答案

    BREAK自2.0起的变化
    正如Tseng在下面所评论的那样,此答案将在从2.0版本起失效,您可以在此处找到有关此公告的更多信息:

    BREAKING CHANGES AS OF 2.0
    As Tseng commented below, this answer will become obsolete as of 2.0 you can find more on this annoucement here: https://github.com/aspnet/Announcements/issues/238


    问题出在哪里...

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


    Where the problem lies...

    Based on your Configure() method, I have spotted an issue:

    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文件中的配置设置所做的所有更改均不起作用的原因.

    This is the reason why none of your changes to the configuration set in the appsettings.json files is not working.

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

    The default behaviour of .AddDebug() without any arguments passed is
    Adds a debug logger that is enabled for LogLevel.Information or higher.

    如果要明确地将其设置为使用特定的最低LogLevel,则可以将其直接传递给AddDebug(ILoggerFactory, LogLevel)方法.

    If you want to explicitly set it to use a particular minimum LogLevel, then you can pass it directly to the AddDebug(ILoggerFactory, LogLevel) method.

    loggerFactory.AddDebug(LogLevel.Trace);
    

    更多信息可以在此处.

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

    方法2:将内置对象用于LogLevel

    (故意遗漏了.显然,它位于这两种提供的方法之间.)我更喜欢其中一种极端情况,而不是半途而废.

    奇特的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

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

    这篇关于如何在ASP.NET Core中启用跟踪日志记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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