使用后台服务日志的 Serilog .NET 8 Windows 服务(工作线程)未找到

问题描述 投票:0回答:1

我的目标是使用 Serilog 在使用 .NET 8 Worker 模板的 Windows 服务中进行文件日志记录。

我可以看到控制台日志。我只是找不到日志文件。

appsettings.json

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Information",
        "System": "Information"
      }
    },
    "Using": ["Serilog.Sinks.Console", "Serilog.Sinks.File"],
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "log.txt",
          "rollingInterval": "Day"
        }
      }
    ]
  }
}

Program.cs

using GettingStartedSvc;
using Serilog;

var builder = Host.CreateApplicationBuilder(args);

// The initial bootstrap logger is able to log errors during start-up.
// It's fully replaced by the logger configured in `UseSerilog()`.
Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateBootstrapLogger();

Log.Information("Starting up...");

try
{
    builder.Logging.AddSerilog();
    // configures the app to work as a Windows Service.
    builder.Services.AddWindowsService(ops =>
    {
        ops.ServiceName = "DotNet Joke Service";
    });
    builder.Services.AddSingleton<JokeService>();
    builder.Services.AddHostedService<WindowsBackgroundService>();

    var host = builder.Build();
    host.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "An unhandled exception occured during bootstrapping");
}
finally
{
    Log.CloseAndFlush();
}

JokeService.cs

namespace GettingStartedSvc;

public sealed class JokeService
{
    public string GetJoke()
    {
        Joke joke = _jokes.ElementAt(Random.Shared.Next(_jokes.Count));
        return $"{joke.Setup}{Environment.NewLine}{joke.Punchline}";
    }

    private readonly HashSet<Joke> _jokes = new()
    {
        new Joke("What's the best thing about a Boolean?", "Even if you're wrong, you're only off by a bit."),
        new Joke("What's the object-oriented way to become wealthy?", "Inheritance"),
        new Joke("Why did the programmer quit their job?", "Because they didn't get arrays.")
    };

}

readonly record struct Joke(string Setup, string Punchline);

WindowsBackgroundService.cs

namespace GettingStartedSvc;

public sealed class WindowsBackgroundService : BackgroundService
{
    private readonly ILogger<WindowsBackgroundService> _logger;
    private readonly JokeService _jokeService;

    public WindowsBackgroundService(
        ILogger<WindowsBackgroundService> logger,
        JokeService jokeService
    )
    {
        _logger = logger;
        _jokeService = jokeService;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                string joke = _jokeService.GetJoke();
                _logger.LogWarning("{Joke}", joke);

                await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
            }
        }
        catch (OperationCanceledException opCanceledEx)
        {

        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "{Message}", ex.Message);
            Environment.Exit(1);
        }
        while (!stoppingToken.IsCancellationRequested)
        {
            var joke = _jokeService.GetJoke();
            _logger.LogWarning("{Joke}", joke);
            await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
        }
    }
}
asp.net-core .net-core serilog .net-8.0
1个回答
0
投票

您可以尝试这个包

Serilog.AspNetCore
并使用“Services.Addxxx”而不是“logging.Addxxx”

var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)   //read config from appsettings
    .CreateLogger();
builder.Services.AddSerilog(logger);

测试结果

© www.soinside.com 2019 - 2024. All rights reserved.