使用 Serilog 记录 Blazor 应用程序

2024-06-25

在 blazor 应用程序中,我配置了启动日志记录main如下;


        public static void Main(string[] args)
        {
            var assembly = Assembly.GetExecutingAssembly().GetName();

            var appInsightsTelemetryConfiguration = TelemetryConfiguration.CreateDefault();
            appInsightsTelemetryConfiguration.InstrumentationKey = "aa11aa11aa-a1a1-a1-aa-a111-aa11";

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Override("Microsoft.AspNetCore", Serilog.Events.LogEventLevel.Warning)
                .Enrich.FromLogContext()
                .Enrich.WithProperty("Application", $"{assembly.Name}")
                .WriteTo.Console()          
                .WriteTo.Seq(serverUrl: "http://myseqserver.inthecloud.azurecontainer.io:5341/") 
                .WriteTo.ApplicationInsights(appInsightsTelemetryConfiguration, TelemetryConverter.Traces)
                .CreateLogger();

            try
            {
                Log.Information(Constants.Logging.Messages.SERVICE_STARTED, assembly.Name);
                var host = CreateHostBuilder(args).Build();

                using (var serviceScope = host.Services.CreateScope())
                {
                    var context = serviceScope.ServiceProvider.GetRequiredService<MyDbContext>();
                    context.Database.Migrate(); // apply outstanding migrations automatically
                }

                host.Run();
                return;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, Constants.Logging.Messages.SERVICE_STARTED, assembly.Name);
                return;
            }
            finally
            {
                // make sure all batched messages are written.
                Log.CloseAndFlush();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseSerilog()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

并请求登录StartUp配置;

public void ConfigureServices(IServiceCollection services)
{
  //...
  services.AddApplicationInsightsTelemetry("aa11aa11aa-a1a1-a1-aa-a111-aa11");
  //...
}
        

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
      /// ...

            // Add this line; you'll need `using Serilog;` up the top, too
            app.UseSerilogRequestLogging();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }

在我的 Blazor 页面上,我无法使其正常工作;

@inject ILogger<ThisRazorPage> Logger

@code{
  protected override void OnInitialized()
  {
      Logger.LogTrace("Log something. Please!");
  }
}

但这确实有效;

@inject ILoggerFactory LoggerFactory

@code{
  protected override void OnInitialized()
  {
      var logger = LoggerFactory.CreateLogger<Incident>();
      logger.LogTrace("Log something. Please!");
  }
}

根据this https://andrewlock.net/adding-serilog-to-the-asp-net-core-generic-host/ the .UseSerilog()方法添加 DIILoggerFactory。有没有办法让我做类似的事情ILogger<T>在 DI 框架内,以便ILogger<T>可以使用,而不必显式创建LoggerFactory在每一页上。


你需要:

  • add Serilog.Extensions.Logging
  • 添加到你的 Main()
public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("#app");
  
    // ...
            
    builder.Services.AddTransient<AccountsViewModel>();


    var levelSwitch = new LoggingLevelSwitch();
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.ControlledBy(levelSwitch)
        .Enrich.WithProperty("InstanceId", Guid.NewGuid().ToString("n"))
        .CreateLogger();

    // ------------- this is what you'r looking for
    builder.Logging.AddSerilog();

    // ...

    await builder.Build().RunAsync();
}
  • 并在你的 ViewModel 中
public class AccountsViewModel
{
    private readonly ILogger<AccountsViewModel> Logger;
    private readonly HttpClient Http;

    public AccountsViewModel(
        ILogger<AccountsViewModel> logger,
        HttpClient http
        )
    {
        Http = http;
        Logger = logger;

        Logger.LogInformation("AccountsViewModel()");
    }
}
  • 或在您的剃刀页面中:
@inject ILogger<ThisRazorPage> logger;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Serilog 记录 Blazor 应用程序 的相关文章

随机推荐