Reputation: 1779
Goal: Implement Serilog into a .net Maui Blazor app using dependency injection.
I am able to get the static method in the MauiProgram.cs file to log properly, but I am unable to log anywhere else in the app.
I have tried various set ups as indicated in these docs, https://github.com/serilog/serilog-extensions-logging
I also tried the .net Blazor (not Maui) solution reported here, but to no avail: Blazor application logging with Serilog
I added
using Serilog;
to my imports.razor.
I have tried:
builder.Services.AddLogging(loggingBuilder =>
loggingBuilder.AddSerilog(Log.Logger, dispose: true));
And:
builder.Logging.AddSerilog(Log.Logger, dispose: true);
MauiProgram.cs:
using Microsoft.AspNetCore.Components.WebView.Maui;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Maui.Controls.Hosting;
using Microsoft.Maui.Hosting;
using SortedDesktop.Data;
using MudBlazor.Services;
using Serilog;
using Serilog.Events;
using System;
namespace Desktop
{
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Seq("http://adomain.com")
.CreateLogger();
var builder = MauiApp.CreateBuilder();
builder
.RegisterBlazorMauiWebView()
.UseMauiApp<App>()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
});
builder.Services.AddBlazorWebView();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddMudServices();
//builder.Services.AddLogging(loggingBuilder =>
// loggingBuilder.AddSerilog(Log.Logger, dispose: true));
builder.Logging.AddSerilog(Log.Logger, dispose: true);
try
{
Log.Information("Starting desktop app");
return builder.Build();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
return builder.Build();
}
}
}
As I mentioned, the static call above to Log.Information works fine here.
Razor page
@inject ILogger<AddJob> logger;
@code {
protected override void OnInitialized()
{
logger.LogInformation("Add Job initialized");
Log.Information("Add Job initialized (static method call)");
}
}
Neither of the calls above work.
Upvotes: 0
Views: 1933
Reputation: 145
The library Serilog-Ilogger-Blazor worked for me on Maui
https://github.com/pablopioli/serilog-ilogger-blazor
It was built for Blazor but it also works on Maui
Upvotes: 0