[英]Blazor application logging with Serilog
In a blazor application I have start-up logging configured in main as follows;在 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>();
});
and request logging in StartUp Configure;并请求登录StartUp Configure;
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");
});
}
On my blazor pages I cannot get this working;在我的 blazor 页面上,我无法正常工作;
@inject ILogger<ThisRazorPage> Logger
@code{
protected override void OnInitialized()
{
Logger.LogTrace("Log something. Please!");
}
}
But this does work;但这确实有效;
@inject ILoggerFactory LoggerFactory
@code{
protected override void OnInitialized()
{
var logger = LoggerFactory.CreateLogger<Incident>();
logger.LogTrace("Log something. Please!");
}
}
According to this the .UseSerilog()
method adds the DI for ILoggerFactory
.根据这个
.UseSerilog()
方法为ILoggerFactory
添加了 DI。 Is there a way for me to do something similar for ILogger<T>
within the DI framework so that ILogger<T>
can be used, rather than having to explicitly create a LoggerFactory
on every page.有没有办法让我在 DI 框架内为
ILogger<T>
做一些类似的事情,以便可以使用ILogger<T>
,而不必在每个页面上显式创建一个LoggerFactory
。
Static method works for me. Static 方法对我有用。
@using Serilog
@code {
Log.Information("Log something. Please!");
}
You need:你需要:
Serilog.Extensions.Logging
Serilog.Extensions.Logging
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();
}
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.