[英]NLog setup for .NET5 worker service template
我现在正在尝试让 NLog 在 .NET5 工作服务模板中工作一段时间。 但无论我尝试什么,都没有日志。 不幸的是,网站、github 或 google 也没有给我任何线索。
我用
只是为了确保,日志文件的目标目录是预先创建的。
appsettings.json 使用:
{
"NLog": {
"throwConfigExceptions": true,
"targets": {
"async": true,
"logfile": {
"type": "File",
"fileName": "c:/temp/nlog/nlog-${shortdate}.log"
},
"logconsole": {
"type": "Console"
}
},
"rules": [
{
"logger": "*",
"minLevel": "Info",
"writeTo": "logconsole"
},
{
"logger": "*",
"minLevel": "Debug",
"writeTo": "logfile"
}
]
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
设置的完整代码(所有仍然是基本模板)但必须缺少一些东西:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace NLogSample
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((hostContext, logging) =>
{
// ensure just use NLog
logging.Services.Clear();
logging.SetMinimumLevel(LogLevel.Trace);
//logging.AddNLog(hostContext.Configuration);
logging.AddNLog(hostContext.Configuration.GetSection("NLog"));
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
})
//.UseNLog()
;
}
}
尝试指定LoggingConfigurationSectionName = "NLog"
并将logging.Services.Clear()
替换为logging.ClearProviders()
。 像这样:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((hostContext, logging) =>
{
// ensure just use NLog
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
logging.AddNLog(hostContext.Configuration, new NLogProviderOptions() { LoggingConfigurationSectionName = "NLog" });
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.