AspNetCore.TestHost: How to get log output from the in-process server?
Asked Answered
B

1

2

I am using the Microsoft.AspNetCore.TestHost to integration-test my ASP.NET Core web service application.

var testServer = new TestServer(
    new WebHostBuilder()
        .UseStartup<Startup>()
        .UseConfiguration(configuration));
var client = testServer.CreateClient();

This works, but I have a problem: If there's an unexpected error on the server side, it typically just throws "Internal Server Error" and I have to debug to see what it does.

Of course I can improve the error messages from my server, but in addition to that I want to be able to see log output from the server.

Is this possible?

I am thinking that when I create my TestServer object above, perhaps I can inject a log sink such as the one from Serilog.Sinks.InMemory and then inspect the contents of that. The WebHostBuilder has a method ConfigureLogging, but I couldn't figure out how to do what I want.

Bromine answered 8/3, 2021 at 15:20 Comment(1)
B
1

Sure it's possible :)

You need the Serilog.AspNetCore nuget package, plus (obviously) Serilog.Sinks.InMemory for the sink.

var testServer = new TestServer(
    new WebHostBuilder()
        .UseSerilog((ctx, conf) => conf.WriteTo.InMemory()) // That's pretty much it.
        .UseStartup<Startup>()
        .UseConfiguration(cBuilder.Build()));

// Then, in the tests, you can access it like this. But you probably know.
InMemorySink.Instance
    .Should()
    .HaveMessage(...)

If doesn't work, let me know and I will edit the answer. I tested it, and it works for me.

Burkes answered 8/3, 2021 at 18:13 Comment(3)
What NuGet packages do I need in order to get the extension method UseSerilog?Bromine
I've tried to reference Serilog, Serilog.Extensions.Hosting, Serilog.Extensions.Logging and Serilog.Sinks.InMemory, but none of them give me this extension method.Bromine
The one you need to use is Serilog.AspNetCore, plus Serilog.Sinks.InMemory for the sink.Burkes

© 2022 - 2024 — McMap. All rights reserved.