我正在尝试使用 MetroLog.Maui 将日志记录添加到 Maui 应用程序的第二页。 我的 MainPage 正在毫无问题地记录到控制台和文件,但我正在努力解决如何将日志记录添加到 NewPage1(第二页)。
这是我的 MauiProgram 中的 MetroLog 代码。
builder.Logging
#if DEBUG
.AddTraceLogger(
options =>
{
options.MinLevel = LogLevel.Trace;
options.MaxLevel = LogLevel.Critical;
}) // Will write to the Debug Output
.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;
}); // Will write to the Console Output (logcat for android)
{
builder.Services.AddTransient<MainPage>();
#if DEBUG
builder.Logging.AddDebug();
#endif
return builder.Build();
}
}
}
这是我设置主页的方法。
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)
{
//Navigate to the log page
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");
}
}
这是有效的 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");
}
}