我在.NET Core 3.1 Worker Service项目中记录调试级别消息时遇到问题。我的文件目标或控制台都没有记录调试级别的消息。信息级事件按预期编写。我已经审核过older question with the same title,以确保所有这些框均已选中。
NLog.config
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="%appdata%\FileTransferService\nlog-internal.log">
<variable name="logdir" value="${specialfolder:folder=ApplicationData}/FileTransferService"/>
<variable name="stdlayout" value="${longdate}|${level:uppercase=true}|${message:exceptionSeparator=|}${exception:format=ToString}"/>
<targets>
<target name="default" xsi:type="AsyncWrapper" overflowAction="Block">
<target name="defaultlog" xsi:type="File"
fileName="${logdir}/dftslog.txt"
layout="${stdlayout}"
archiveEvery="Month" concurrentWrites="false"/>
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="default"/>
</rules>
</nlog>
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
我尝试将Microsoft和Microsoft.Hosting.Lifetime都设置为Debug,但这没有效果。
Program.CreateHostBuilder方法
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureLogging((context, logBuilder) => {
logBuilder.ClearProviders();
logBuilder.AddConfiguration(context.Configuration.GetSection("Logging"));
logBuilder.SetMinimumLevel(LogLevel.Debug);
logBuilder.AddConsole();
logBuilder.AddNLog();
})
.ConfigureServices((hostContext, services) => {
services.AddHostedService<Worker>();
services.AddTransient(typeof(ITransferService), typeof(TransferService));
});
以下是一些其他说明:
答案 0 :(得分:1)
问题似乎出在Visual Studio 2019上。
尽管问题仍然存在,但是当我在Visual Studio外部运行应用程序时,调试级别的事件将同时写入控制台和平面文件。这不是由于调试器所引起的,因为如果我在Visual Studio中没有调试器的情况下运行该调试器,则会表现出相同的行为。
我查看了Visual Studio的设置并进行了快速搜索,但找不到任何相关内容。就是说,知道事件将记录在Visual Studio外部将在一定程度上解决我的问题。
答案 1 :(得分:1)
要添加到接受的答案中(没有足够的评论要点):
同样的问题。但是当我使用VS2019时它也可以正常工作
private static Logger _logger = LogManager.GetCurrentClassLogger();
与DI相比,我更喜欢使用它来获取记录器(主要是因为我喜欢在.LogWarning(...)上编写.Warn(...)
我仍然为NLog设置DI,以便外部/ ms库将使用它
答案 2 :(得分:1)
将NLog与Microsoft-Extension-Logging(MEL)一起使用时,NLog成为MEL-LoggerFactory中的LoggingProvider。
这意味着在MEL-LoggerFactory中配置的任何过滤总是获胜,而与NLog.config无关。
MEL-LoggerFactory将自动从appsettings.json
(以及任何特定于环境的appsettings.development.json
或appsettings.production.json
)加载其过滤。
即使调用了SetMinimumLevel(LogLevel.Debug)
,appsettings.json
中的任何配置也会覆盖它。
另请参阅:https://github.com/NLog/NLog.Web/wiki/Missing-trace%5Cdebug-logs-in-ASP.NET-Core-3%3F