1

In several questions, people already experienced problems with Serilog in .NET 6 when writing logs to log file, such as here and here. I also experience such problems but when using an absolute file path. This should work because for absolute file paths, things are just right or wrong regardless of where the application is positioned or executed. In theory, if it works in my IDE, it works as a published app too. Unfortunately, the reality is not like that.

Here is my C# code.

using System.Reflection;
using Serilog;
using WorkerService1;


IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services => { services.AddHostedService<Worker>(); })
    .UseSerilog((context, _, config) =>
    {
        config.ReadFrom.Configuration(context.Configuration)
            .Enrich.FromLogContext();

        if (args.Contains("--console"))
        {
            config.WriteTo.Console();
        }
    })
    .UseWindowsService()
    .Build();
    
await host.RunAsync();

AND

namespace WorkerService1;

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.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(1000, stoppingToken);
        }
    }
}

Here is my appsettings:

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "restrictedToMinimumLevel": "Information",
          "path": "C:\\temp\\logs\\JustLog.log",
          "rollingInterval": "Day",
          "rollOnFileSizeLimit": true,
          "fileSizeLimitBytes": 10487600,
          "retainedFileCountLimit": 30
        }
      }
    ]
  }
}

Here is my csproj:

<Project Sdk="Microsoft.NET.Sdk.Worker">

    <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
        <OutputType>exe</OutputType>
        <PublishSingleFile Condition="'$Configuration' == 'Release'">true</PublishSingleFile>
        <RuntimeIdentifier>win-x64</RuntimeIdentifier>
        <PlatformTarget>x64</PlatformTarget>
        <PublishTrimmed>false</PublishTrimmed>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
        <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
        <PackageReference Include="Serilog.Extensions.Hosting" Version="4.2.0" />
        <PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" />
        <PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
        <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
    </ItemGroup>
</Project>

When running the code from Rider, everything works perfectly fine. Even the logging works. But when publishing and running the published app, the logging does not work. Here are my publishing settings.

enter image description here

How can I fix this? I just want the logging to work. Not just when running from my IDE but also when running the published executable.

Daan
  • 2,478
  • 3
  • 36
  • 76
  • Your problem almost certainly doesn't have anything to do with Serilog *or* .NET, but rather with Windows Services. First, you need to verify your configuration is being loaded properly (i.e., relative paths can be troublesome because Windows Services do *not* have their working directory set to their application location). If the configuration file is actually being loaded, then ensure the Windows Service has permissions to write to the log file. – Stephen Cleary Mar 07 '23 at 01:48

0 Answers0