Skip to content

WebHost inside Generic host not logging startup messages #126

Closed
@gthvidsten

Description

@gthvidsten

If you have a generic host, then inside this host you add a web host, and you are using .UseSerilog() for both, then the web host startup messages are not logged to Serilog.

This is what I mean by "startup messages":

Hosting environment: Production
Content root path: C:\Users\Me\Project\src\App\bin\Debug\netcoreapp3.0
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

Program.cs

public static async Task Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Debug()
        .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
        .Enrich.FromLogContext()
        .WriteTo.Console()
        .CreateLogger();

    IHostBuilder builder = new HostBuilder()
        .UseSerilog()
        .ConfigureServices(services => { collection.AddHostedService<MyService>(); });

    await builder.RunConsoleAsync();
}

MyService.cs

public class MyService : IHostedService
{
    private IWebHost _webHost;

    public async Task StartAsync(CancellationToken ct)
    {
        _webHost = WebHost.CreateDefaultBuilder()
            .UseStartup<MyService>()
            .UseSerilog()
            .Build();

        _webHost.RunAsync();
    }

    public async Task StopAsync(CancellationToken ct)
    {
        await _webHost.StopAsync();
    }

    public void ConfigureServices(IServiceCollection services) {
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
    }
}

When this starts the logging from the generic host uses Serilog, but the logging in the web host startup does not. Logging of requests to the web host, on the other hand, does use Serilog. This is apparent in the output:

Hosting environment: Production
Content root path: C:\Users\Me\Project\src\App\bin\Debug\netcoreapp3.0
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
[15:32:01 INF] Application started. Press Ctrl+C to shut down.
[15:32:01 INF] Hosting environment: Production
[15:32:01 INF] Content root path: C:\Users\Me\Project\src\App\bin\Debug\netcoreapp3.0
[15:32:33 INF] Request starting HTTP/1.1 GET http://localhost:5000/
[15:32:33 INF] Request finished in 13.2002ms 404

Expected behaviour

The startup messages from a web host inside a generic host should still be logged to Serilog.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions