最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Serilog configuration for .NET 8 Windows service not logging to file when deployed - Stack Overflow

programmeradmin3浏览0评论

I have an ASP.NET Core 8 Web API that is installed as a service using the following method:

var processInfo = new ProcessStartInfo
        {
            FileName = "cmd.exe",
            Arguments = $"/c sc create \"{envServiceName}\" binPath= \"\\\"{environmnetPath}\\publish\\MyApi.Api.exe\\\" --environment={environment}\" DisplayName= \"MyApi {environment} API Service\" start= auto",
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = false
        };

using var process = Process.Start(processInfo);

In this .NET 8 application, I have added Serilog logging to Program.cs like this:

builder.Host.UseSerilog((ctx, cfg) => cfg.ReadFrom.Configuration(ctx.Configuration));

And in appsettings.json I have the following configuration:

{
    "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
    },
    "Serilog": {
        "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
        "MinimumLevel": "Debug",
        "WriteTo": [
          {
            "Name": "Console"
          },
          {
            "Name": "File",
            "Args": {
              "path": "D:\\deployments\\logs\\myapp\\log-.txt",
              "rollingInterval": "Day"
            }
          }
        ],
        "Enrich": [ "FromLogContext", "WithMachineName" ],
        "Properties": {
          "ApplicationName": "Your ASP.NET Core App"
        }
    },
    "AllowedHosts": "*"
}

The application is installed as a service on a windows server 2022 standard machine and the service is running under the local system account.

If I install the application directly on the server with the sc command or if I start the exe directly, I can see logs being generated but if I install it using the ProcessStartInfo method from above I don't see any logs and in the serilog self-logs I can see the following exception.

Failed to write event through SerilogLogger: System.IO.FileNotFoundException: Could not load file or assembly 'System.Diagnostics.DiagnosticSource, Version=9.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified. File name: 'System.Diagnostics.DiagnosticSource, Version=9.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' at Serilog.Extensions.Logging.SerilogLogger.PrepareWrite[TState](LogEventLevel level, EventId eventId, TState state, Exception exception, Func3 formatter) at Serilog.Extensions.Logging.SerilogLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)

The application is built using the following command

dotnet publish --configuration Release --output publish --runtime win-x64 --self-contained=true

I have also tried to setup the Serilog config directly in Program.cs (like below) but all I see are the logs from Program.cs not the ones from classes where I injected an ILogger<MyClass>

Log.Logger = new LoggerConfiguration()
     .MinimumLevel.Debug()
     .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
     .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
     .WriteTo.Console()
     .WriteTo.File(
         path: Path.Combine("D:\\deployments\\logs\\myapp", "log-.txt"),
         rollingInterval: RollingInterval.Day,
         shared: true // Important for services
     )
     .Enrich.FromLogContext()
     .Enrich.WithMachineName()
     .Enrich.WithProperty("ApplicationName", "Your ASP.NET Core App")
     .CreateLogger();

Log.Information("Environment:" + builder.Environment.EnvironmentName);

builder.Host.UseWindowsService();
builder.Host.UseSerilog(Log.Logger);

I have an ASP.NET Core 8 Web API that is installed as a service using the following method:

var processInfo = new ProcessStartInfo
        {
            FileName = "cmd.exe",
            Arguments = $"/c sc create \"{envServiceName}\" binPath= \"\\\"{environmnetPath}\\publish\\MyApi.Api.exe\\\" --environment={environment}\" DisplayName= \"MyApi {environment} API Service\" start= auto",
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = false
        };

using var process = Process.Start(processInfo);

In this .NET 8 application, I have added Serilog logging to Program.cs like this:

builder.Host.UseSerilog((ctx, cfg) => cfg.ReadFrom.Configuration(ctx.Configuration));

And in appsettings.json I have the following configuration:

{
    "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
    },
    "Serilog": {
        "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
        "MinimumLevel": "Debug",
        "WriteTo": [
          {
            "Name": "Console"
          },
          {
            "Name": "File",
            "Args": {
              "path": "D:\\deployments\\logs\\myapp\\log-.txt",
              "rollingInterval": "Day"
            }
          }
        ],
        "Enrich": [ "FromLogContext", "WithMachineName" ],
        "Properties": {
          "ApplicationName": "Your ASP.NET Core App"
        }
    },
    "AllowedHosts": "*"
}

The application is installed as a service on a windows server 2022 standard machine and the service is running under the local system account.

If I install the application directly on the server with the sc command or if I start the exe directly, I can see logs being generated but if I install it using the ProcessStartInfo method from above I don't see any logs and in the serilog self-logs I can see the following exception.

Failed to write event through SerilogLogger: System.IO.FileNotFoundException: Could not load file or assembly 'System.Diagnostics.DiagnosticSource, Version=9.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified. File name: 'System.Diagnostics.DiagnosticSource, Version=9.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' at Serilog.Extensions.Logging.SerilogLogger.PrepareWrite[TState](LogEventLevel level, EventId eventId, TState state, Exception exception, Func3 formatter) at Serilog.Extensions.Logging.SerilogLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)

The application is built using the following command

dotnet publish --configuration Release --output publish --runtime win-x64 --self-contained=true

I have also tried to setup the Serilog config directly in Program.cs (like below) but all I see are the logs from Program.cs not the ones from classes where I injected an ILogger<MyClass>

Log.Logger = new LoggerConfiguration()
     .MinimumLevel.Debug()
     .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
     .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
     .WriteTo.Console()
     .WriteTo.File(
         path: Path.Combine("D:\\deployments\\logs\\myapp", "log-.txt"),
         rollingInterval: RollingInterval.Day,
         shared: true // Important for services
     )
     .Enrich.FromLogContext()
     .Enrich.WithMachineName()
     .Enrich.WithProperty("ApplicationName", "Your ASP.NET Core App")
     .CreateLogger();

Log.Information("Environment:" + builder.Environment.EnvironmentName);

builder.Host.UseWindowsService();
builder.Host.UseSerilog(Log.Logger);
Share Improve this question edited Mar 16 at 17:48 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Mar 16 at 15:38 ZippyZippy 1,8345 gold badges28 silver badges37 bronze badges 3
  • shot in the dark but maybe WorkingDirectory on ProcessStartInfo needs to be set as well? – Ivan Petrov Commented Mar 16 at 16:41
  • @IvanPetrov I've also tried doing that without any change. – Zippy Commented Mar 18 at 15:45
  • @Zippy I would try to provide the login info using 'Usename' and 'PasswordInClearText' attributes of "ProcessStartInfo". Try to provide the credentials under which it is working when you execute as exe directly. more information here. – Chinmay T Commented Mar 25 at 17:15
Add a comment  | 

1 Answer 1

Reset to default 0

Have you tried configuring Serilog for debugging with:

Serilog.Debugging.SelfLog.Enable(Console.Error);

This enables internal logging and displays any issues related to your sinks, such as the File Sink. It helped me troubleshoot authentication issues with a Seq Sink.

The issue could be related to file access or relativ pathing

WriteTo.RollingFile(
  AppDomain.CurrentDomain.BaseDirectory + "\\logs\\log-.txt"
)

Give it a try and check the console output for any errors!

发布评论

评论列表(0)

  1. 暂无评论