Search code examples
asp.net-coreloggingilogger

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


So this is my logging configuration:

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();
    }
}

And I'm just trying to do this from a controller method

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

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

But this is what I'm getting in the logs

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

Is there anything I'm missing?


Solution

  • If you want to see the content in your BeginScope, you must to structured logging first.You can see more details in this article.

    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.

    You are using serilog, here is an example using Seq structured.

    1:Download Seq.

    2:At the Visual Studio Package Manager Console type:

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

    3: In your logging configuration:

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

    4:Run your project and to your GetRegionDescendantsById action.The visit URL http://localhost:5341.

    You can see the details here.

    Test Result: enter image description here