【问题标题】:AspNetCore.TestHost: How to get log output from the in-process server?AspNetCore.TestHost:如何从进程内服务器获取日志输出?
【发布时间】:2021-03-08 15:20:25
【问题描述】:

我正在使用 Microsoft.AspNetCore.TestHost 来集成测试我的 ASP.NET Core Web 服务应用程序。

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

这可行,但我有一个问题:如果服务器端出现意外错误,它通常只会抛出“内部服务器错误”,我必须调试才能看到它的作用。

当然我可以改进来自服务器的错误消息,但除此之外我希望能够看到来自服务器的日志输出

这可能吗?

我在想,当我在上面创建 TestServer 对象时,也许我可以注入一个日志接收器,例如来自 Serilog.Sinks.InMemory 的那个,然后检查其中的内容。 WebHostBuilder 有一个方法 ConfigureLogging,但我不知道该怎么做。

【问题讨论】:

    标签: asp.net-core logging integration-testing asp.net-core-testhost


    【解决方案1】:

    当然可以:)

    您需要 Serilog.AspNetCore nuget 包,以及(显然)用于接收器的 Serilog.Sinks.InMemory

    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(...)
    

    如果不起作用,请告诉我,我将编辑答案。我测试了它,它对我有用。

    【讨论】:

    • 我需要哪些 NuGet 包才能获得扩展方法 UseSerilog
    • 我尝试引用 SerilogSerilog.Extensions.HostingSerilog.Extensions.Logging 和 Serilog.Sinks.InMemory,但他们都没有给我这个扩展方法。
    • 你需要使用的是Serilog.AspNetCore,加上Serilog.Sinks.InMemory作为sink。
    猜你喜欢
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多