.net core 7 logging with nlog does not working

63 Views Asked by At

I try to setup logging with nlog on .net 7 background service. I've managed this, bo no log file written. Whats wrong with my code?

program.cs

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureLogging((hostContext, logging) =>
    {
        logging.ClearProviders();
        logging.SetMinimumLevel(LogLevel.Trace);
        logging.AddNLog(hostContext.Configuration);
    })
    .ConfigureServices((hostContext, services) =>
    {
        services.AddHostedService<Worker>();
    })
    .Build();
host.Run();

worker.cs

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.LogTrace("test");
            await Task.Delay(1000, stoppingToken);
        }
    }
}

nlog.config (with copy always)

<?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" throwExceptions="true" autoReload="true">
    <targets async="true" >
        <target name="file" xsi:type="File" fileName="c:/logs/service/log.txt" layout="${longdate} ${message}"/>
    </targets>
    <rules>
        <logger name="*" minlevel="Trace" writeTo="file"/>
    </rules>
</nlog>
0

There are 0 best solutions below