0

目标:使用依赖注入将 Serilog 实施到 .net Maui Blazor 应用程序中。

我能够让 MauiProgram.cs 文件中的静态方法正确记录,但我无法在应用程序的其他任何地方记录。

我已经尝试了这些文档中指示的各种设置,https://github.com/serilog/serilog-extensions-logging

我还尝试了此处报告的 .net Blazor (not Maui) 解决方案,但无济于事:Blazor application logging with Serilog

我添加了

using Serilog;

到我的imports.razor。

我努力了:

builder.Services.AddLogging(loggingBuilder => 
    loggingBuilder.AddSerilog(Log.Logger, dispose: true));

和:

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();

    }
}
}

正如我所提到的,上面对 Log.Information 的静态调用在这里可以正常工作。

剃刀页面

@inject ILogger<AddJob> logger;

@code {
protected override void OnInitialized()
{
    logger.LogInformation("Add Job initialized");
    Log.Information("Add Job initialized (static method call)");
}
}

上述调用均无效。

4

1 回答 1

0

Serilog-Ilogger-Blazor 图书馆在毛伊岛为我工作

https://github.com/pablopioli/serilog-ilogger-blazor

它是为 Blazor 构建的,但也适用于 Maui

于 2021-11-26T19:41:22.187 回答