Mar*_*rkD 5 logging .net-core-2.0
我有一个控制台应用程序,它将使用 DI 为应用程序内的服务提供配置(选项模式)、日志记录和其他服务引用。
我有一个问题,即日志记录适用于 Info/Warning/Error/Critical,但没有显示Debug和Trace。我已将控制台级别设置为 Trace。如果我只是创建一个记录器工厂,则会显示所有日志。
听起来它正在使用默认值。对于在 DI 服务集合中创建的记录器,是否还有其他方法可以配置日志级别?
我已尝试在本文中提到的服务集合上添加处置,编辑 2 链接,但没有运气。
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using System;
namespace DownloadClientData.App
{
class Program
{
static int Main(string[] args)
{
//***if I use this way to create the logger in the DI container, debug and trace messages are not displayed
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging();
//tried this alternative too - no change...
//serviceCollection.AddLogging(LoggingBuilder => LoggingBuilder.AddFilter<ConsoleLoggerProvider>("All Categories", LogLevel.Trace));
var serviceProvider = serviceCollection.BuildServiceProvider();
var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
//***If I comment out the above lines and uncomment the below line, all 6 logs are displayed.
//var loggerFactory = new LoggerFactory();
loggerFactory
.AddConsole(LogLevel.Trace)
.AddDebug(LogLevel.Trace);
var logger = loggerFactory.CreateLogger(typeof(Program));
logger.LogInformation("Information");
logger.LogTrace("Trace");
logger.LogDebug("Debug");
logger.LogWarning("Warning");
logger.LogCritical("Critical");
logger.LogError("Error");
Console.ReadKey();
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
}
在 上使用AddLogging()扩展方法时,最小日志级别的默认值不同ServiceCollection。你可以这样设置:
static void Main(string[] args)
{
var serviceCollection = new ServiceCollection()
.AddLogging(builder => {
builder.SetMinimumLevel(LogLevel.Trace);
builder.AddConsole();
builder.AddDebug();
});
var serviceProvider = serviceCollection.BuildServiceProvider();
var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger(typeof(Program));
logger.LogInformation("Information");
logger.LogTrace("Trace");
logger.LogDebug("Debug");
logger.LogWarning("Warning");
logger.LogCritical("Critical");
logger.LogError("Error");
Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)