Serilog LogContext in Blazor with IIS Site Bindings

Viewed 92

I use Serilog in my Blazor Server Side Application, which deploy on IIS using site bindings IIS Site Bindings

And I want to ensure that the logs(unhandled exceptions and my custom log info) on these sites are written to different folders by hostname.

My Serilog Configuration:

public static class HostBuilderExtension
{
  public static IHostBuilder AddSerilog(this IHostBuilder hostBuilder)
  {
    return hostBuilder.UseSerilog((hostingContext, loggerConfiguration) =>
    {
      var appSettings = hostingContext.Configuration.Get<AppSettings>();
      loggerConfiguration
      .ReadFrom.Configuration(hostingContext.Configuration)
      .Enrich.FromLogContext()
      .WriteTo.Map("Hostname", "ms-hosting", (hostname, wr) =>
        wr.Async(to =>
        to.File(appSettings.GeneralLogsPath(hostname), rollingInterval: RollingInterval.Day, shared: true)));
    });
  }
}

GeneralLogsPath

public string GeneralLogsPath(string hostname) => Path.Combine(AppLogsRoot, hostname, "General", "log.log");

Registration in Program.cs:

builder.Host.AddSerilog();

And my custom Middleware to push current hostname to LogContext:

using Serilog.Context;
using System.Collections.Generic;

namespace Herbst.Acc2.CustomerWebUI.Classes;

public class ScopedLoggingMiddleware
{
  private readonly RequestDelegate _next;
  private readonly ILogger<ScopedLoggingMiddleware> _logger;
  public ScopedLoggingMiddleware(RequestDelegate next, ILogger<ScopedLoggingMiddleware> logger)
  {
    _next = next ?? throw new ArgumentNullException(nameof(next));
    _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  }

  public async Task Invoke(HttpContext context)
  {
    if (context == null) throw new ArgumentNullException(nameof(context));

    var hostname = context.Request.Host.Host;

    try
    {
      using (LogContext.PushProperty("Hostname", hostname))
      {
        await _next(context);
      }
    }
    //To make sure that we don't loose the scope in case of an unexpected error
    catch (Exception ex) when (LogOnUnexpectedError(ex))
    {
      return;
    }
  }

  private bool LogOnUnexpectedError(Exception ex)
  {
    _logger.LogError(ex, "An unexpected exception occured!");
    return true;
  }
}

public static class ScopedLoggingMiddlewareExtensions
{
  public static IApplicationBuilder UseScopedLogging(this IApplicationBuilder builder)
  {
    return builder.UseMiddleware<ScopedLoggingMiddleware>();
  }
}

In Program.cs

app.UseScopedLogging();

Can I be sure that the message from test-t1.com will never written to \logs\test-t2.com?

0 Answers
Related