简体   繁体   中英

.Net Core 6 Worker Service not writing to Logs when running as a Windows Service

I have created a Worker Service using C# / .Net Core 6 (Visual Studio 2022).

It writes to a log file as expected if run via Visual Studio or started directly from Windows Explorer / PowerShell. However, when installed as a Windows Service, it does not create or write to a log file.

This is my 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();
}

I have this in 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" ]
  }

If I include the "SetBasePath" part, the service fails to start (although it still runs via Visual Studio).

I am publishing the service from Visual Studio with Target Framework = net6.0, Deployment Mode = Framework Dependent, Target runtime = win-x64.

Note: I have created a Logger in Program.cs because I wanted to log the start and stop / crash of the service.

As others have noted, services run with a working directory different than the process location. One old trick I like to use is to set the working directory to the process' binary directory first thing:

Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

In my case, I just changed Deployment mode to Self-Contained and choose the Produce single file . Although it will create a large file but now compiler embed all dependent libraries into a single file.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM