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

查看:44
本文介绍了如何在 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 更改为:

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

  • 运行并查看调试输出

  • 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 遵守日志记录设置,包括 Trace 级别?

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

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

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

    推荐答案

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

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

    方法二:使用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 值:

    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

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

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