I am running a Blazor WASM Hosted application using Serilog.Sinks.BrowserHttp on the Client and Serilog.AspNetCore.Ingestion and Serilog.Sinks.MSSqlServer on the Server.
My Server Program.cs is setup as follows
public class Program
{
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Enrich.WithProperty("InstanceId", Guid.NewGuid())
.Enrich.WithProperty("Origin", "Server")
.CreateLogger();
try
{
Log.Information("Starting up");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application start-up failed");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
My Server Startup.cs Configure is setup as follows
app.UseSerilogIngestion();
app.UseSerilogRequestLogging();
My Client Program.cs is setup as follows
//Serilog
var levelSwitch = new LoggingLevelSwitch();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(levelSwitch)
.Enrich.WithProperty("InstanceId", Guid.NewGuid())
.WriteTo.BrowserHttp(controlLevelSwitch: levelSwitch)
.CreateLogger();
Log.Information("Client has started");
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddLogging(logging =>
{
logging.ClearProviders();
logging.AddSerilog(dispose: true);
});
This allows me to use dependency injection on my components and log as expected. However, id like to add additional properties like Username, UserId etc outside of the MessageTemplate. Example :
using Microsoft.Extensions.Logging;
[Inject]
public ILogger<CountryList> Logger { get; set; }
Logger.LogError(ex, "An Exception was thrown", Username, UserId);
The ILogger is from the Microsoft.Extensions.Logging library which does not have .ForContext(). Is there a way to add properties besides the .BeginScope approach? I really would like to keep it clean and single line as opposed to wrapping every logging with a using statement.