AspNetCore.Docs icon indicating copy to clipboard operation
AspNetCore.Docs copied to clipboard

Sample on how to use logger scope is either not explained very well or incomplete

Open PonchoPowers opened this issue 1 year ago • 1 comments

Description

The example I'm referring to is:

[HttpGet("{id}")]
public async Task<ActionResult<TodoItemDTO>> GetTodoItem(long id)
{
    TodoItem todoItem;
    var transactionId = Guid.NewGuid().ToString();
    using (_logger.BeginScope(new List<KeyValuePair<string, object>>
        {
            new KeyValuePair<string, object>("TransactionId", transactionId),
        }))
    {
        _logger.LogInformation(MyLogEvents.GetItem, "Getting item {Id}", id);

        todoItem = await _context.TodoItems.FindAsync(id);

        if (todoItem == null)
        {
            _logger.LogWarning(MyLogEvents.GetItemNotFound, 
                "Get({Id}) NOT FOUND", id);
            return NotFound();
        }
    }

    return ItemToDTO(todoItem);
}

How is TransactionId used in the example? There is no explanation as to what would would be logged as a result of adding it either, giving the impression that the following is logged:

"Getting item X"

Could either the example be updated to show how TransactionId would be used, or provide clarity how TransactionId is used if it is used at all in the example?

Page URL

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-8.0

Content source URL

https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/fundamentals/logging/index.md

Document ID

726e3bf1-f367-d733-8933-bccc04da0e16

Article author

@tdykstra

PonchoPowers avatar May 05 '24 21:05 PonchoPowers

The following from SO is quite handy, so something similar to this would be good: https://stackoverflow.com/questions/76507960/is-it-possible-to-pass-some-logging-scope-variables-to-a-net-log-message-wher#answer-76508154

PonchoPowers avatar May 05 '24 22:05 PonchoPowers