question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

BeginScope forgets stuff when returning from the method

See original GitHub issue

NLog version: 4.5.0

Platform: .NET Core 2.1

        [HttpGet]
        public async Task<IActionResult> Test(int id)
        {
            var item = await GetItem(id);

            _injectedLogger.LogInformation("Doing something with the item");

            return Ok();
        }

        private async Task<object> GetItem(int id)
        {
            _injectedLogger.BeginScope(new Dictionary<string, object>{["id"] = id});

            // pretend we are getting it from the database, and it takes a long time
            await Task.Delay(100);

            _injectedLogger.LogInformation($"Fetched an object from the database with id={id}");

            // pretend this is the thing we got from the database
            return new { id };
        }

In the above sample I call BeginScope inside the GetItem method, setting up the logger to include the id for the rest of the request processing. But, the id is only included in the logged message inside GetItem, in the log of the message “Doing something wit hthe item” it is missing. It seems like the value is forgotten when the async method GetItem returns.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
snakefootcommented, Aug 15, 2019

The correct way to implement the logic would be like this:

        [HttpGet]
        public async Task<IActionResult> Test(int id)
        {
           using (_injectedLogger.BeginScope(new [] { new KeyValuePair<string, object>("id", id) }))
           {
                var item = await GetItem(id);
               _injectedLogger.LogInformation("Doing something with the item");
               return Ok();
            }
        }

Now the BeginScope-context will flow down to the GetItem()-task.

0reactions
304NotModifiedcommented, Aug 24, 2019

I assume your question has been answered, if not, please let us know!

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to preserve log scopes for unhandled exceptions?
You might wish to make the SetProperty method return IDisposable and remove the property from the context on Dispose.
Read more >
C# 8.0: Understanding Using Declarations - Code with Steve
In this post, I introduce a C# 8 language feature called using declarations and compare the compiled code with the more common using ......
Read more >
Logging with ILogger in .NET: Recommendations and best ...
This article describes recommendations and best practices for using the ILogger based logging system which has been introduced with .
Read more >
Logging with Serilog (part 2) - iStruction
Introduction. In the previous post about Serilog I showed how to initialize logging in a .Net Core Windows Service application.
Read more >
What is "scoped logging" defined as?
Yep. Scope is simply a spatial-temporal region. Logging tools will provide different mechanisms for tracking it, but it boils down to: Where ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found