我的目标是使用 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);
}
}
}