简体   繁体   English

.NET5 工作者服务模板的 NLog 设置

[英]NLog setup for .NET5 worker service template

I am trying to get NLog working in a .NET5 worker service template for a while now.我现在正在尝试让 NLog 在 .NET5 工作服务模板中工作一段时间。 But whatever I try there are no logs at all.但无论我尝试什么,都没有日志。 Unfortunatly nor the website, github or google brought me any clues why.不幸的是,网站、github 或 google 也没有给我任何线索。

I using我用

  • the .NET5 worker service template .NET5 工作者服务模板
  • NLog.Extensions.Logging version 1.7.4 NLog.Extensions.Logging 版本 1.7.4

Just to make sure, the target directory for the log file is created upfront.只是为了确保,日志文件的目标目录是预先创建的。

The appsettings.json used: 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"
    }
  }
}

The full code of the setup (all still the basic templates) but something must be missing:设置的完整代码(所有仍然是基本模板)但必须缺少一些东西:

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

Try specifying LoggingConfigurationSectionName = "NLog" and replace logging.Services.Clear() with logging.ClearProviders() .尝试指定LoggingConfigurationSectionName = "NLog"并将logging.Services.Clear()替换为logging.ClearProviders() Like this:像这样:

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

See also: https://stackoverflow.com/a/67780779/193178另见: https : //stackoverflow.com/a/67780779/193178

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM