locked
BeginScope Usage on EF Core DbContext RRS feed

  • Question

  • Hi, I would like to ask if it is possible to use logging scopes (via BeginScope) while DbContext operations
    logging. Operations are logged correctly but the scope is lost (only for DbContext).
    Target framework is .NET Core 3.1. Please see code snipped below.
    Thank you, Michal

      • public HomeController(ILogger<HomeController> logger, AppDbContext dbContext)
      • {
      • this.logger = logger;
      • this.dbContext = dbContext;
      • }
      • public IActionResult Index()
      • {
      • using (logger.BeginScope(new LogMessageScope { Scope = $"Scope 1: {Guid.NewGuid()}" }))
      • {
      • // here logging scope is lost
      • var data = dbContext.GIP_LOG.Where(r => r.SEVERITY == "Information").ToList();
      • // logging scope is present
      • logger.LogInformation("Hello from Home Controller!");
      • }
      • return View();
      • }

    Thursday, October 22, 2020 1:41 PM

All replies

  • Hi Michal82,
    First, did you add "IncludeScopes=true" to the configuration of appsetting?
    Then I suggest you include a try-catch block inside the scope block, then you can log the errors and the scope will be included as you'd expect.
    Scopes work well for this situation when you want to attach additional values to every log message, but there's a problem. What if an exception occurs inside the scope using block? The scope probably contains some very useful information for debugging the problem, so naturally you'd like to include it in the error logs.

    try
    {
                using (logger.BeginScope(new LogMessageScope { Scope = $"Scope 1: {Guid.NewGuid()}" }))
               {
                 ......
               }
    }
    catch (Exception ex)
    {
               // logger.LogError(ex, "An unexpected exception occured"); 
    }

    More details you can refer to this document.
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Friday, October 23, 2020 6:24 AM