Windows microservice created from .net core using does not write logs to path

86 views Asked by At

Windows microservice created from .net core using does not write logs to path

I have created a windows service from c# .net core which uses Serilog.Sinks.Async.File in appsettings.json as below

"Serilog": {
"Using": [
"Serilog.Sinks.Async"
],
"WriteTo": [
{
"Name": "Async",
"Args": {
"configure": [
{
"Name": "File",
"Args": {
"restrictedToMinimumLevel": "Information",
"path": "%PROGRAMDATA%/logs/file.log",
"rollingInterval": "Day",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
}
}
]
}
},

The above config is just a snippet from appsettings.json but it also includes other standard parameters set in it.

Please let me know if a windows service running as local system can write logs into %PROGRAMDATA% path configured through appsettings.json. The same log file works if it configured as part of the service in Program.cs

Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.Destructure.UsingAttributes()
.WriteTo.Async(a =>
a.File(Environment.ExpandEnvironmentVariables("%PROGRAMDATA%\logs\file.log"))
.WriteTo.Console()
.CreateBootstrapLogger()
1

There are 1 answers

0
Qiang Fu On

This logging works.
package Serilog.AspNetCore Microsoft.Extensions.Hosting.WindowsServices

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();
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "%PROGRAMDATA%/Logs/log.txt",
          "rollingInterval": "Day",
          "restrictedToMinimumLevel": "Information"
        }
      },

Test
enter image description here