【问题标题】:Blazor application logging with Serilog使用 Serilog 进行 Blazor 应用程序日志记录
【发布时间】:2020-12-15 05:25:39
【问题描述】:

在一个 blazor 应用程序中,我在 ma​​in 中配置了启动日志记录,如下所示;


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

【问题讨论】:

    标签: asp.net-core blazor blazor-server-side serilog asp.net-core-logging


    【解决方案1】:

    静态方法适合我。

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

    【讨论】:

    • 把“@using Serilog”放到你的 _Imports.razor 中,你不需要每次都把它写在你的 .razor 文件中。当您使用文件隐藏代码 (xyz.razor.cs) 时,您需要提供 using 指令。解决这个问题,亚当的解决方案也对我有用。但是,条件是 Serilog 的使用已按照 Serilogs 主页上的文档实施。
    【解决方案2】:

    你需要:

    • 添加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;
    

    【讨论】:

    • 我无法让它工作。一切都像这里一样。
    猜你喜欢
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 2021-03-22
    • 2021-03-09
    • 1970-01-01
    相关资源
    最近更新 更多