使用Serilog进行Blazor应用程序日志记录 [英] Blazor application logging with Serilog

查看:25
本文介绍了使用Serilog进行Blazor应用程序日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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>();
                });

并请求登录启动配置;

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.UseSerilog()方法为ILoggerFactory添加DI。有没有办法让我在DI框架内对ILogger<T>执行类似的操作,以便可以使用ILogger<T>,而不必在每个页面上显式创建LoggerFactory

推荐答案

静电方法适合我。

@using Serilog


@code {
    Log.Information("Log something. Please!");
}

这篇关于使用Serilog进行Blazor应用程序日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆