Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

How to use ILogger.BeginScope in Blazor Server for the entire activity?

$
0
0

In a standard request/response app with AspNet.Core, it was easy to add informations to the request context so that every single log entry could have access to them automatically. For exemple, if I need that all my log entries have the logged UserName and the FormId that he is presently editing, I just had to create a new Middleware that use ILogger.BeginScope to achieve that and register the middleware at the beginning of the pipeline.

public class FormLogEnricherMiddleware : IMiddleware{    private readonly IMyForm _myForm;    private readonly ILogger<FormLogEnricherMiddleware > _logger;    public FormLogEnricherMiddleware(IMyForm myForm, ILogger<FormLogEnricherMiddleware> logger)    {        _myForm = myForm;        _logger = logger;    }    public Task InvokeAsync(HttpContext context, RequestDelegate next)    {        var scopeTags = new Dictionary<string, object>()        {            ["UserName"] = context.User?.Identity?.Name,            ["FormId"] = _myForm.FormId        };        using (_logger.BeginScope(scopeTags))        {            return next(context);        }    }}

Program.cs

...builder.Services.AddControllersWithViews();builder.Services.AddScoped<FormLogEnricherMiddleware>();var app = builder.Build();app.UseMiddleware<FormLogEnricherMiddleware>();// Configure the HTTP request pipeline.if (!app.Environment.IsDevelopment()){    app.UseExceptionHandler("/Home/Error");    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.    app.UseHsts();}app.UseHttpsRedirection();app.UseStaticFiles();...

HomeController.cs

_logger.LogInformation("This is a test");

Result
enter image description here

Now that we use Blazor Server with web sockets, the middleware way is not working anymore. So how can we add informations in a ILogger scope so that every log have access to them automatically?


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>