问题描述
我在.NET Core 3.1辅助服务应用程序中使用NLog.在NLog教程之后,我插入了一个nlog.config文件来管理配置.
I'm using NLog in a .NET Core 3.1 worker service application.Following the tutorial of NLog I inserted an nlog.config file to manage the configuration.
现在我很困惑,因为我在配置日志记录的三个方面:
Now I'm confused because I have three points where I configure the logging:
1. In the code where I need to create a logger in a dependency injection
context
// 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...
2. In appSettings.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Trace",
"System": "Trace",
"Microsoft": "Trace"
}
}
}
3. in NLog.config
The default config file produced by the nuget package installation:
<!-- 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文件,将不会创建日志文件.其他更改接缝无效.
What I see is that if I remove the Nlog.config file, the log file will not be created.Other changes seam to have no effect.
此配置如何关联?开启/关闭日志记录并设置级别的最佳方法是什么?
How are this configurations related?What is the best way to switch on/off the logging and set the level?
推荐答案
决定使用NLog的人们通常还希望禁用所有MEL过滤,以避免与两个过滤系统混淆.因此, NLog Wiki-教程是针对这些用户的.
People that decide to use NLog usually also want to disable all MEL-filtering to avoid the confusion with two filtering systems. So the NLog wiki-tutorial is targeted those users.
我想首先是MEL用户的人可能只会使用new HostBuilder().CreateDefaultBuilder().Build()
(将在启用所有枪支的情况下设置所有内容).
I guess people who are MEL-users first will probably just use new HostBuilder().CreateDefaultBuilder().Build()
(Will setup everything with all guns enabled).
但是如果只考虑简单的示例,则需要删除:
But if staying with the simple example, then you need to remove:
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);
})
可以在Nuget上找到
ILoggingBuilder.AddConfiguration
: Microsoft.Extensions.Logging .配置
ILoggingBuilder.AddConfiguration
can be found at Nuget: Microsoft.Extensions.Logging.Configuration
这篇关于在.NET Core 3中使用NLog管理日志记录配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!