BeginScope Usage on EF Core DbContext

Michal Kiraly 1 Reputation point
2020-10-22T12:11:47.257+00:00

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 class HomeController : Controller
{
private readonly AppDbContext dbContext;
private readonly ILogger<HomeController> logger;

    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();
    }
}
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,644 questions
{count} votes

2 answers

Sort by: Most helpful
  1. m 4,271 Reputation points
    2020-10-23T05:25:50.257+00:00

    Hi @Janik ,

    I find that you have already change your post into the new forum: beginscope-usage-on-ef-core-dbcontext

    Though I am not one .Net engineer and not good at this scope, I do some research , and find something maybe helpful.Just sharing them here:
    entity-framework-core-log-queries-for-a-single-db-context-instance
    How-to-Write-a-Custom-Logging-Provider-in-ASP-NET

    BR,
    Mia


    If the answer is helpful, please click "Accept Answer" and upvote it.

    0 comments No comments

  2. m 4,271 Reputation points
    2020-10-24T01:21:17.37+00:00

    Hi @Janik ,

    Is the reply helpful?

    BR,
    Mia


    If the answer is helpful, please click "Accept Answer" and upvote it.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.