Get Standard Output of Kestrel

Viewed 20

I have a service that I have setup. When it starts, the standard output posts this:

info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.

I want to capture this (and any other output) in a string.

The way I am starting the service is not standard. I have class that looks like this:

public static class HostTestService
{
    private static WebApplication? currentApp;

    public static async Task<List<string>?> StartService()
    {
        if (currentApp != null) { await StopService(); }

        var builder = WebApplication.CreateBuilder();
        var app = builder.Build();
        app.Start();
        
        var server = app.Services.GetService<IServer>();
        var addressFeature = server?.Features.Get<IServerAddressesFeature>();
        var addresses = addressFeature?.Addresses.ToList();
        
        // Set the Current app so that calls to shut it down will now succeed.
        currentApp = app;

        return addresses;
    }

    public static async Task StopService()
    {
        if (currentApp != null)
        {
            await currentApp.StopAsync(TimeSpan.FromSeconds(10));
            await currentApp.DisposeAsync();
            currentApp = null;
        }
    }
}

I then call HostTestService.StartService() in my code (an NUnit test). But I need to capture the output of the service somehow. I would rather not redirect all of the standard output. (This causes issues with other things that need standard output.)

How can I get this output from my WebAPI Core service?

0 Answers
Related