Using serilog with .NET MAUI

Viewed 908

I have a very simple .NET MAUI app (not a Blazor one). I've installed Seriolog and Serilog.Extensions.Logging (so I can use AppCenter). I have the following in my startup code to initialise Serilog

public static MauiApp CreateMauiApp()
{
    // set up logging
    var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    path = Path.Combine(path, "debugcode.txt");

    Log.Logger = new LoggerConfiguration()
        //.MinimumLevel.Debug()
        .WriteTo.File(path)
        .WriteTo.AppCenterCrashes(restrictedToMinimumLevel: LogEventLevel.Information)
        .WriteTo.Console()
        .CreateLogger();

    var builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp<App>()
        .ConfigureFonts(fonts =>
        {
            fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
            fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
        })
        .Logging.AddSerilog(Log.Logger);


    return builder.Build();
}

This compiles without an issue. I've added into the main.xaml.cs the code for logging (the code is just the default .NET MAUI test app shipped with VisualStudio). The minimum debug line is commented out, but it makes no difference if it's not commented out.

protected override void OnDisappearing()
{
    base.OnDisappearing();
    Log.CloseAndFlush();
}

void OnCounterClicked(object sender, EventArgs e)
{
    count++;

    var nums = $"Current count: {count}";

    CounterLabel.Text = nums;

    Log.Debug($"***** Current count: {nums}");

    SemanticScreenReader.Announce(CounterLabel.Text);
}

I have tried changing the debug level, but no matter what, nothing is showing in the console for the debug information.

3 Answers

Here is a working example:

Install These nuget packages:

  • Serilog
  • Serilog.Extensions.Logging
  • Serilog.Sinks.File

Code:

    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();

        SetupSerilog();

        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
            });

        builder.Services.AddMauiBlazorWebView();
#if DEBUG
        builder.Services.AddBlazorWebViewDeveloperTools();
#endif

        builder.Logging.AddSerilog(dispose: true);

        return builder.Build();
    }

    private static void SetupSerilog()
    {
        var flushInterval = new TimeSpan(0, 0, 1);
        var file = Path.Combine(FileSystem.AppDataDirectory, "MyApp.log");

        Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Verbose()
        .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
        .Enrich.FromLogContext()
        .WriteTo.File(file, flushToDiskInterval: flushInterval, encoding: System.Text.Encoding.UTF8, rollingInterval: RollingInterval.Day, retainedFileCountLimit: 22)
        .CreateLogger();
    }

Adding Serilog.Sinks.Xamarin and calling .WriteTo.AndroidLog() in LoggerConfiguration works. For iOS, I think that .WriteTo.NSLog() should work too.

A couple points.

  • Make sure you include using Serilog; in the classes that write to the log e.g. Log.Debug($"***** Current count: {nums}");

  • If writing to the AndroidLog, use Tools -> Android -> Device Log. Make sure your LoggerConfiguration includes something you can filter on, such as specifying the Source.

.WriteTo.AndroidLog()
.Enrich.WithProperty(Serilog.Core.Constants.SourceContextPropertyName, ".yourappname")
  • It's a good idea to also add Serilog.Sinks.Debug to your project and add .WriteTo.Debug() to your LoggerConfiguration.
Related