serilog / serilog-aspnetcore

Serilog integration for ASP.NET Core
Apache License 2.0
1.32k stars 209 forks source link

aspnetcore logging not working when .net 7 web api is deployed as a windows service #314

Closed bigswede74 closed 1 year ago

bigswede74 commented 1 year ago

Description

I have built a very simple .net 7 web api that is being hosted as a windows service. I have the console and file sinks configured and they work when debugging in visual studio however, when deployed as a windows service I do not get any logs from the file sink. If I just run the exe directly I get some console logging. I'm using the Two-stage initialization as specified however neither are working.

Reproduction Create a simple asp.net core 7 web api with Serilog console and File sinks configured via appsettings.json. Deploy the application as single exe self contained app as a windows service on windows server 2016.

Program.cs

public static void Main(string[] args)
{
    // Create a temp logger so any startup errors will be logged
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Override("Microsoft", LogEventLevel.Debug)
        .WriteTo.File("startup.log")
        .WriteTo.Console()
        .CreateBootstrapLogger();

    try
    {
        Log.Information("Starting web api");

        var options = new WebApplicationOptions
        {
            Args = args,
            ContentRootPath = WindowsServiceHelpers.IsWindowsService()
                                             ? AppContext.BaseDirectory : default
        };

        var builder = WebApplication.CreateBuilder(args);

        builder.Host.UseSerilog((context, services, configuration) => configuration
            .ReadFrom.Configuration(context.Configuration)
            .ReadFrom.Services(services)
            .Enrich.FromLogContext()
            .WriteTo.Console());

        builder.Services.AddHealthChecks();

        builder.Services.AddHttpLogging(logging =>
        {
            //logging.LoggingFields = HttpLoggingFields.All;
            logging.LoggingFields = HttpLoggingFields.ResponseStatusCode;
            //logging.RequestBodyLogLimit = 4096;
            //logging.ResponseBodyLogLimit = 4096;
        });

        builder.Host.UseWindowsService();

        var app = builder.Build();

        app.UseHttpLogging();

        app.MapHealthChecks("/health");

        // Configure the HTTP request pipeline.

        app.UseSerilogRequestLogging();

        // Production this should be enabled
        //app.UseHttpsRedirection();

        app.MapControllers();

        app.Run();
    }
    catch (Exception ex)
    {
        Log.Fatal(ex, "web api terminated unexpectedly");
    }
    finally
    {
        Log.CloseAndFlush();
    }
}

appsettings.json

{
    "Kestrel": {
        "Endpoints": {
            "Http": {
                "Url": "http://0.0.0.0:1234"
            }
        }
    },
    "Serilog": {
        "MinimumLevel": {
            "Default": "Information",
            "Override": {
                "Microsoft": "Information",
                "Microsoft.Hosting.Lifetime": "Information",
                "Microsoft.AspNetCore": "Information"
            }
        },
        "WriteTo": [
            {
                "Name": "File",
                "Args": {
                    "path": "C:\\logs\\log-.log",
                    "fileSizeLimitBytes": 100000000,
                    "rollOnFileSizeLimit": true,
                    "rollingInterval": "Day",
                    "retainedFileCountLimit": 30
                }
            }
        ],
        "Enrich": [ "FromLogContext" ]
    },
    "AllowedHosts": "*"
}

Expected behavior Logs should be produced for the file sink when hosted as a windows service.

Relevant package, tooling and runtime versions Packages

Platform

Additional context The .net 7 asp web api is deployed as a single self contained application.

augustoproiete commented 1 year ago

@bigswede74 Have you tried checking the output from Serilog's self log, to see if there's any error occurring internally?

e.g.

Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine(msg));

That's the first step in troubleshooting issues with any Serilog sink - https://github.com/serilog/serilog/wiki/Debugging-and-Diagnostics

BTW, chances are the user account in which your Windows Service is running does not have write access to C:\logs\

sungam3r commented 1 year ago

Deploy the application as single exe self contained app

Also check this https://github.com/serilog/serilog-settings-configuration#net-50-onwards-single-file-applications

bigswede74 commented 1 year ago

@bigswede74 Have you tried checking the output from Serilog's self log, to see if there's any error occurring internally?

e.g.

Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine(msg));

That's the first step in troubleshooting issues with any Serilog sink - https://github.com/serilog/serilog/wiki/Debugging-and-Diagnostics

BTW, chances are the user account in which your Windows Service is running does not have write access to C:\logs\

Unfortunately the selflog did not turn up any errors. I ended up removing the a couple of publish flags from the project and adding the using statement in the Serilog section of the appsettings.json file. After these changes the logs started working. see below.

Publish Settings

<PublishSingleFile>false</PublishSingleFile> <!--changed to false-->
<SelfContained>true</SelfContained>
<PublishReadyToRun>false</PublishReadyToRun> <!--changed to false-->

Using

    "Serilog": {
        "MinimumLevel": {
            "Default": "Information",
            "Override": {
                "Microsoft": "Warning",
                "Microsoft.Hosting.Lifetime": "Warning",
                "Microsoft.AspNetCore": "Warning"
            }
        },
        "Using": [ "Serilog.Sinks.Console" ],
        "WriteTo": [
            {
                "Name": "File",
                "Args": {
                    "path": "./log-.log",
                    "fileSizeLimitBytes": 100000000,
                    "rollOnFileSizeLimit": true,
                    "rollingInterval": "Day",
                    "retainedFileCountLimit": 30
                }
            }
        ],
        "Enrich": [ "FromLogContext" ]
    },