Logger Begin Scope 对我不起作用! .net核心

Logger Begin Scope is not working for me! .net Core

这是我的日志记录配置:

public static void Main(string[] args)
{
    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();

    Log.Logger = new LoggerConfiguration()
        .Enrich.FromLogContext()
        .WriteTo.Console()
        .WriteTo.File("C:HotelServiceLog.txt")
        .CreateLogger();

    //Log.Logger = Loggers.NewSerilogLogger(configuration);

    try {
        Log.Information("Starting up");
        CreateHostBuilder(args).Build().Run();
    }
    catch (Exception ex) {
        Log.Fatal(ex, "Application start-up failed");
    }
    finally {
        Log.CloseAndFlush();
    }
}

我只是想通过控制器方法来做到这一点

public async Task<ActionResult<ExpediaRegionsResponse>> GetRegionDescendantsById([FromBody] ExpediaRegionsRequest request) {
    try {

        using (_logger.BeginScope("Controller Scope")) {
            _logger.LogInformation("Controller processing");
        }
        ...
    }
}

但这就是我在日志中得到的内容

2020-12-07 12:09:26.511 -05:00 [INF] Controller processing
2020-12-07 12:09:26.529 -05:00 [INF] Controller processing

有什么我遗漏的吗?

如果你想看到你BeginScope中的内容,你必须structured loggingfirst.You才能看到这篇文章的更多细节。

Some of the most popular options are to store the logs in Elastic Search with a Kibana front end, or to use Seq. The Serilog logging provider also supports structured logging, and is typically used to write to both of these destinations.

您正在使用 serilog,这里是一个使用 Seq 结构化的示例。

1:下载Seq.

2:在 Visual Studio 包管理器控制台类型:

Install-Package Serilog.Sinks.Seq -DependencyVersion Highest
Install-Package Serilog.Sinks.Console

3:在您的日志记录配置中:

Log.Logger = new LoggerConfiguration()
            //......
            .WriteTo.Seq("http://localhost:5341")
            //......

4:运行 你的项目和你的 GetRegionDescendantsById action.The 访问 URL http://localhost:5341.

可以看到详情here

测试结果: