Serilog File Sink not logging to file when ran as WindowService

106 views Asked by At

I'm running a workservice as a window service, the log to eventlog is working, but it's not logging to file.

When ran in visual studio, it logs to both eventlog and to file.

What could explain this? Why is the behavior different when ran as a window service? I've also checked to ensure the path is valid and the service user has sufficient permissions to write to the path.

here are my appsettings:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    },
  },
  "WorkerSetting": {
    "Urls": [ "https://google.com" ],
    "TimeIntervalMins": 1
  },
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "logs/log.log",
          "rollingInterval": "Day",
          "restrictedToMinimumLevel": "Information"
        }
      },
      {
        "Name": "EventLog",
        "Args": {
          "source": "The Ping Service",
          "logName": "Application",
          "manageEventSource": true,
          "restrictedToMinimumLevel": "Information"
        }
      }
    ]
  }
}
2

There are 2 answers

0
Lee On BEST ANSWER

When ran as a window service, the working directory is the system32 folder, to write to a log file either

  1. Use an absolute path
  2. To use a path relative to the exe directory, att the top of the builder, set the current directory to the exe directory with Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
0
Qiang Fu On

You could try this which works for window service logging.
Create a "worker service" project from visual studio.
Install package Serilog.AspNetCore Microsoft.Extensions.Hosting.WindowsServices program.cs

var builder = Host.CreateDefaultBuilder(args);
builder.UseSerilog((hostingContext, services, loggerConfiguration) => loggerConfiguration
                        .ReadFrom.Configuration(hostingContext.Configuration));
builder.ConfigureServices(services =>
    {
        services.AddHostedService<Worker>();
        services.AddWindowsService();
    });

var host =builder.Build();
host.Run();

After publish to folder,create windows service.

sc create testWinService binPath=E:\TESTS\WorkerService2\WorkerService2\bin\Release\net7.0\WorkerService2.exe

Start the service. It will log to file.
enter image description here