Home > Enterprise >  How to access scope message from a Logger
How to access scope message from a Logger

Time:01-26

I'm a beginner to Logger, just wondering how does BeginScope() work

// startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) {
   if (env.IsDevelopment()) {
      app.UseDeveloperExceptionPage();
   }
   app.UseEndpoints(endpoints => {
      endpoints.MapGet("/", async context => {
         using (logger.BeginScope("Example")) {
            logger.LogInformation("Processing credit card payment");
         }
      });
   });
}

enter image description here

I think a scope in logger is the you can add a "prefix" to the logged message, so in my case the output should be "Example Processing credit card payment", so how can I access the scope message "Example" and get in printed in the output?

CodePudding user response:

Set IncludeScopes:true in Program.cs like below:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        })
        .ConfigureLogging(logger => {
            logger.AddConsole(options =>
            {
                options.IncludeScopes = true;
            });
        });

Or you can add IncludeScopes in appsettings.json like this document:Configure logging

  •  Tags:  
  • Related