.net-core - 在 .NET Core 3 中使用 NLog 管理日志记录配置
问题描述
我在 .NET Core 3.1 辅助服务应用程序中使用 NLog。按照 NLog 的教程,我插入了一个 nlog.config 文件来管理配置。
现在我很困惑,因为我有三点配置日志记录:
在我需要在依赖注入上下文中创建记录器的代码中
// Other code... services.AddScoped<IApplyJcdsCommandsJob, ApplyJcdsCommandsJob>(provider => { var loggerFactory = LoggerFactory.Create(builder => { builder .ClearProviders() .AddFilter("Microsoft", Microsoft.Extensions.Logging.LogLevel.Trace) .AddFilter("System", Microsoft.Extensions.Logging.LogLevel.Trace) .AddFilter("ApplyJcdsCommandsJob", Microsoft.Extensions.Logging.LogLevel.Trace) //.AddConsole() //.AddEventLog(); .AddNLog(configuration); }); Microsoft.Extensions.Logging.ILogger logger = loggerFactory.CreateLogger<CommandsJob>(); return new CommandsJob(logger); }) // Other code...
在 appSettings.json
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Trace", "System": "Trace", "Microsoft": "Trace" } } }
在 NLog.config 中
nuget包安装产生的默认配置文件:
<!-- a section of the config --> <targets> <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" /> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="f" /> </rules> <!-- ... -->
我看到的是,如果我删除 Nlog.config 文件,将不会创建日志文件。其他更改接缝没有效果。
这些配置有什么关系?打开/关闭日志记录和设置级别的最佳方法是什么?
解决方案
决定使用 NLog 的人通常还希望禁用所有 MEL 过滤以避免与两个过滤系统混淆。所以NLog wiki-tutorial是针对这些用户的。
我猜首先是 MEL 用户的人可能只会使用new HostBuilder().CreateDefaultBuilder().Build()
(将在启用所有枪支的情况下设置所有内容)。
但是,如果继续使用简单示例,则需要删除:
loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
并添加:
loggingBuilder.AddConfiguration(config.GetSection("Logging"));
所以它看起来像这样:
serviceCollection.AddLogging(loggingBuilder =>
{
loggingBuilder.ClearProviders();
loggingBuilder.AddConfiguration(config.GetSection("Logging"));
loggingBuilder.AddNLog(config);
})
ILoggingBuilder.AddConfiguration
可以在 Nuget 中找到:Microsoft.Extensions.Logging.Configuration
推荐阅读
- java - 在过滤器中测量请求时间
- c# - BouncyCastle PrivateKey 到 X509Certificate2 PrivateKey (ECC)
- android - 如何在 Google Play 管理中心事先准备新的“主要商品详情”
- apache-kafka-streams - GlobalKTable 中的数据会过期吗?
- jquery - 为什么空的 JQuery Datable 加载时间这么长?
- python - Django Rest Framework 给出错误:您无权执行此操作
- java - 求解过程中内存指纹应该如何变化
- php - 为什么我在数组 spatie laravel-permission 上调用成员函数 contains() 时出现此错误
- excel - Powershell Excel 添加 ConditionalFormatting
- php - 使用 Twig 在数组的值上添加逗号