【问题标题】:NLog setup for .NET5 worker service template.NET5 辅助服务模板的 NLog 设置
【发布时间】:2021-12-04 05:42:27
【问题描述】:

我现在正在尝试让 NLog 在 .NET5 辅助服务模板中工作一段时间。但无论我尝试什么,都没有日志。不幸的是,网站、github 或 google 也没有给我带来任何线索。

我用

  • .NET5 辅助服务模板
  • NLog.Extensions.Logging 版本 1.7.4

只是为了确保日志文件的目标目录是预先创建的。

使用的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()
                ;
    }
}

【问题讨论】:

  • 尝试将logging.AddNLog(hostContext.Configuration.GetSection("NLog")); 替换为logging.AddNLog(hostContext.Configuration, new NLog.Extensions.Logging.NLogProviderOptions() { LoggingConfigurationSectionName = "NLog" });。另见stackoverflow.com/a/67780779/193178
  • 引发ILogger无法注入Worker的异常
  • 你应该用logging.ClearProviders();替换logging.Services.Clear();

标签: c# .net .net-5 nlog


【解决方案1】:

尝试指定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>();
        });

另请参阅:https://stackoverflow.com/a/67780779/193178

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多