我使用C#/.Net Core 6(Visual Studio 2022)创建了一个Worker Service。
如果通过Visual Studio运行或直接从Windows资源管理器/PowerShell启动,它将按预期写入日志文件。但是,当安装为Windows服务时,它不会创建或写入日志文件。
以下是我的program.cs:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.File("./logs/log-.txt", rollingInterval:RollingInterval.Day)
.CreateBootstrapLogger();
try
{
Log.Information("Starting the Service");
IHost host = Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureAppConfiguration((hostContext, configBuilder) =>
{
configBuilder
//.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.MachineName}.json", true, true)
.Build();
})
.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext())
.ConfigureServices((hostContext, services) =>
{
...
})
.Build();
await host.RunAsync();
}
catch (Exception ex)
{
Log.Fatal(ex, "There was a problem starting the service");
}
finally
{
Log.Information("Service successfully stopped");
Log.CloseAndFlush();
}
我有一个appsettings.json文件:
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Debug" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": ".\\logs\\log-.txt",
"rollingInterval": "Day"
}
}
],
"Enrich": [ "FromLogContext" ]
}
如果我包含“SetBasePath”部分,服务将无法启动(尽管它仍然可以通过Visual Studio运行)。
我正在使用Target Framework = net6.0,Deployment Mode = Framework Dependent,Target runtime = win-x64从Visual Studio发布服务。
注意:我在Program.cs中创建了一个Logger,因为我想记录服务的启动、停止/崩溃。
svchost
进程执行。你的日志很可能在System32中。最好使用基于配置设置的绝对路径。 - Panagiotis Kanavos