BeginScope forgets stuff when returning from the method
See original GitHub issueNLog 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:
- Created 4 years ago
- Comments:6 (4 by maintainers)
Top 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 >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
The correct way to implement the logic would be like this:
Now the BeginScope-context will flow down to the GetItem()-task.
I assume your question has been answered, if not, please let us know!