1

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);
3
  • shot in the dark but maybe WorkingDirectory on ProcessStartInfo needs to be set as well? Commented Mar 16 at 16:41
  • @IvanPetrov I've also tried doing that without any change. 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. Commented Mar 25 at 17:15

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

4 Comments

I have already specified in the question what is the self log output. Failed to write event through SerilogLogger: System.IO.FileNotFoundException: Could not load file or assembly 'System.Diagnostics.DiagnosticSource,
ok i stumbled over that pice, have you tried programaticly to access the path where you wannt to save your seri logs, i dont think this is a serilog issue more a issue with file access in service
I had file access issues as well and they were logged in the serilog self log. The latest errors are very generic unfortunately.
have you tryd out to check for .net relativ file paths (SpecialFolders) instead of specifying an absolute one? stackoverflow.com/questions/76972731/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.