You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MAUI应用的第二页配置MetroLog.Maui日志功能

MAUI中第二页配置MetroLog.Maui日志的问题解决

问题描述

我正尝试在MAUI应用的第二页中使用MetroLog.Maui添加日志功能。主页面已成功将日志输出到控制台和文件,但在为第二页NewPage1配置日志时遇到了困难。

现有配置代码

MauiProgram中的MetroLog配置

builder.Logging
#if DEBUG
    .AddTraceLogger(
        options =>
        {
            options.MinLevel = LogLevel.Trace;
            options.MaxLevel = LogLevel.Critical;
        }) // 输出到调试窗口

    .AddStreamingFileLogger(
                options =>
                {
                    options.RetainDays = 2;
                    options.FolderPath = Path.Combine(
                        FileSystem.CacheDirectory,
                        "MetroLogs");
                })

#endif
    .AddInMemoryLogger(
        options =>
        {
            options.MaxLines = 1024;
            options.MinLevel = LogLevel.Debug;
            options.MaxLevel = LogLevel.Critical;
        })
#if RELEASE
            .AddStreamingFileLogger(
                options =>
                {
                    options.RetainDays = 2;
                    options.FolderPath = Path.Combine(
                        FileSystem.CacheDirectory,
                        "MetroLogs");
                })
#endif
    .AddConsoleLogger(
        options =>
        {
            options.MinLevel = LogLevel.Information;
            options.MaxLevel = LogLevel.Critical;
        }); // 输出到控制台(Android对应logcat)

            {
                builder.Services.AddTransient<MainPage>();

#if DEBUG
                builder.Logging.AddDebug();
#endif

                return builder.Build();
            }
        }
    }

MainPage的实现代码

public partial class MainPage : ContentPage
 {
     private int count = 0;
     private ILogger<MainPage> _logger;

     public MainPage(ILogger<MainPage> logger)
     {
         InitializeComponent();
         _logger = logger;
     }

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

         if (count == 1)
             CounterBtn.Text = $"Clicked {count} time";
         else
             CounterBtn.Text = $"Clicked {count} times";

         SemanticScreenReader.Announce(CounterBtn.Text);

         _logger.LogInformation("Counter clicked {Count} times", count);
     }

     private void OnLogClicked(object sender, EventArgs e)
     {
         //跳转到日志页面
         Navigation.PushAsync(new NewPage1());
         _logger.LogInformation("Navigated to the log page");
     }
 }

疑问

请问我的第二页的构造函数签名应该是什么样的?或是我还遗漏了其他配置?

修改后可运行的NewPage1代码

using MetroLog;
using Microsoft.Extensions.Logging;
using Microsoft.Maui.Controls.PlatformConfiguration;
using Microsoft.VisualBasic;
using System.Reflection;
using System;

namespace SerilogMaui1;

public partial class NewPage1 : ContentPage
{
   
    public ILogger<MainPage> Logger { get; }


    public NewPage1(ILogger<MainPage> logger)
    {
        InitializeComponent();
           Logger = logger;
    }

    private async void Button_Clicked(object sender, EventArgs e)
    {
        Logger.LogInformation("clicked button in NewPage1");
        await DisplayAlert("Alert", "You have been alerted", "OK");
    }
}

问题解决说明

  1. 规范的构造函数写法
    你当前的NewPage1构造函数注入的是ILogger<MainPage>,虽然能运行,但更合理的做法是注入与当前页面绑定的日志实例ILogger<NewPage1>,这样日志会明确标记来源是NewPage1,更利于日志排查。修改后的构造函数如下:
private readonly ILogger<NewPage1> _logger;

public NewPage1(ILogger<NewPage1> logger)
{
    InitializeComponent();
    _logger = logger;
}
  1. 注册页面到依赖注入容器
    你的MauiProgram中仅注册了MainPage(builder.Services.AddTransient<MainPage>();),但未注册NewPage1。依赖注入容器需要知道如何创建NewPage1实例,才能解析其构造函数中的参数,因此需要添加注册:
builder.Services.AddTransient<NewPage1>();
  1. 正确的页面跳转方式
    当前你直接通过new NewPage1()创建页面实例,这种方式会绕过依赖注入容器,导致构造函数中的参数无法被正确注入。推荐通过依赖注入的方式获取页面实例,比如在MainPage中注入Func<NewPage1>工厂:
private readonly ILogger<MainPage> _logger;
private readonly Func<NewPage1> _newPage1Factory;

public MainPage(ILogger<MainPage> logger, Func<NewPage1> newPage1Factory)
{
    InitializeComponent();
    _logger = logger;
    _newPage1Factory = newPage1Factory;
}

private void OnLogClicked(object sender, EventArgs e)
{
    // 使用工厂创建NewPage1实例
    var newPage = _newPage1Factory();
    Navigation.PushAsync(newPage);
    _logger.LogInformation("Navigated to the log page");
}

按照上述步骤修改后,NewPage1的日志功能就能正常工作,同时符合MAUI依赖注入的最佳实践。

内容的提问来源于stack exchange,提问作者Fritz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 10:24:52