How to enable Trace logging in ASP.NET Core?

穿精又带淫゛_ 提交于 2019-12-05 09:26:29

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


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

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

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

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

More information can be found here.


Binding it to your configuration.

Method 1: Grab the value from the configuration.

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

Method 2: Use the built-in object for LogLevel

(Intentionally left out. Obviously it sits snug between these two methods offered.) I would favor one of the extremes than to go halfway)

Method 3: Go Manual (use ConfigurationBinder)

The fancy ConfigurationBinder

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

which will map to an object like

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

so you could then pass:

loggerFactory.AddDebug(obj.Default);

Special note about nodes and appsettings.json

Note that the delimiter for the configuration uses :.

Example: "Logging:LogLevel" will go:

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

LogLevel Enum

Just for reference, here are the valid LogLevel values:

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

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

This worked for me. Add it in the ConfigureServices(IServiceCollection services) method:

services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Trace));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!