小编dav*_*d w的帖子

作为服务运行时,Serilog 文件日志记录未从 Worker Service 写入

我正在编写一个工作服务,需要使用 Serilog 并写入日志文件。(.net core 6 和 Windows 服务)。当使用 Microsoft.Extensions.Logging 并按照 aspsettings.json 中配置写入事件日志时,相同的服务可以很好地记录到事件日志中。另外,我已经证明我有权访问写入日志的目录。

当我将项目配置为使用 Serilog 写入日志文件时,日志文件永远不会被写入(如果它不存在,则不会创建它)。我希望您能提供有关未创建日志文件的原因的任何意见。

Nuget 包

<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="5.0.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
Run Code Online (Sandbox Code Playgroud)

程序.cs

<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="5.0.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
Run Code Online (Sandbox Code Playgroud)

我的应用程序设置配置为写入控制台和文件,其中文件使用 Json 格式化程序。正在加载应用程序设置。在添加 Serilog 之前,我正在加载配置事件日志记录的应用程序设置,结果成功。SetBasePath 是实现这一目标的关键。

appsettings.json 中的片段

using Serilog;
using WorkerServiceAndSerilog;

IHost host = Host.CreateDefaultBuilder(args)
    .UseWindowsService()
    .ConfigureAppConfiguration((builderContext, config) =>
    {
        config.SetBasePath(System.AppDomain.CurrentDomain.BaseDirectory);
    })
    .ConfigureServices(services =>
    {
        services.AddHostedService<Worker>();
        services.AddLogging(configure => configure.AddSerilog()); …
Run Code Online (Sandbox Code Playgroud)

c# windows-services serilog asp.net-core-6.0

5
推荐指数
1
解决办法
6304
查看次数

标签 统计

asp.net-core-6.0 ×1

c# ×1

serilog ×1

windows-services ×1