Skip to content

Commit f2528b7

Browse files
committed
迁移到 Microsoft.Extensions.Logging
1 parent d680a2d commit f2528b7

9 files changed

Lines changed: 41 additions & 39 deletions

File tree

CoreAppUAP/App.xaml.cs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using CoreAppUAP.Common;
22
using CoreAppUAP.Helpers;
33
using CoreAppUAP.Pages;
4+
using Microsoft.Extensions.Logging;
45
using System;
56
using System.Threading;
67
using Windows.ApplicationModel;
@@ -141,7 +142,7 @@ private static void EnsureWindow(IActivatedEventArgs e)
141142
}
142143
catch (Exception ex)
143144
{
144-
SettingsHelper.LogManager.GetLogger(nameof(App)).Error(ex.ExceptionToMessage(), ex);
145+
SettingsHelper.LoggerFactory.CreateLogger<App>().LogError("Failed to set CoreApplication.EnablePrelaunch(true). {message} (0x{hResult:X})", ex.GetMessage(), ex.HResult);
145146
goto end;
146147
}
147148
}
@@ -185,15 +186,18 @@ private static void OnSuspending(object sender, SuspendingEventArgs e)
185186

186187
private static void Application_UnhandledException(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e)
187188
{
188-
SettingsHelper.LogManager?.GetLogger("Unhandled Exception - Application").Error(e.Exception.ExceptionToMessage(), e.Exception);
189+
if (e.Exception is Exception ex)
190+
{
191+
SettingsHelper.LoggerFactory.CreateLogger("Unhandled Exception - Application").LogError(ex, "Unhandled exception. {message} (0x{hResult:X})", ex.GetMessage(), ex.HResult);
192+
}
189193
e.Handled = true;
190194
}
191195

192196
private static void CurrentDomain_UnhandledException(object sender, System.UnhandledExceptionEventArgs e)
193197
{
194198
if (e.ExceptionObject is Exception ex)
195199
{
196-
SettingsHelper.LogManager?.GetLogger("Unhandled Exception - CurrentDomain").Error(ex.ExceptionToMessage(), ex);
200+
SettingsHelper.LoggerFactory.CreateLogger("Unhandled Exception - CurrentDomain").LogError(ex, "Unhandled exception. {message} (0x{hResult:X})", ex.GetMessage(), ex.HResult);
197201
}
198202
}
199203

@@ -210,7 +214,10 @@ private static void RegisterExceptionHandlingSynchronizationContext()
210214

211215
private static void SynchronizationContext_UnhandledException(object sender, Common.UnhandledExceptionEventArgs e)
212216
{
213-
SettingsHelper.LogManager?.GetLogger("Unhandled Exception - SynchronizationContext").Error(e.Exception.ExceptionToMessage(), e.Exception);
217+
if (e.Exception is Exception ex)
218+
{
219+
SettingsHelper.LoggerFactory.CreateLogger("Unhandled Exception - SynchronizationContext").LogError(ex, "Unhandled exception. {message} (0x{hResult:X})", ex.GetMessage(), ex.HResult);
220+
}
214221
e.Handled = true;
215222
}
216223
}

CoreAppUAP/Common/SettingsPaneRegister.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using CoreAppUAP.Helpers;
2+
using Microsoft.Extensions.Logging;
23
using System;
34
using Windows.ApplicationModel.Search;
45
using Windows.Storage;
@@ -23,7 +24,7 @@ public static void Register(Window window)
2324
}
2425
catch (Exception ex)
2526
{
26-
SettingsHelper.LogManager.GetLogger(nameof(SettingsPaneRegister)).Error(ex.ExceptionToMessage(), ex);
27+
SettingsHelper.LoggerFactory.CreateLogger(typeof(SettingsPaneRegister)).LogError(ex, "Failed to register settings pane. {message} (0x{hResult:X})", ex.GetMessage(), ex.HResult);
2728
}
2829
}
2930

@@ -36,7 +37,7 @@ public static void Unregister(Window window)
3637
}
3738
catch (Exception ex)
3839
{
39-
SettingsHelper.LogManager.GetLogger(nameof(SettingsPaneRegister)).Error(ex.ExceptionToMessage(), ex);
40+
SettingsHelper.LoggerFactory.CreateLogger(typeof(SettingsPaneRegister)).LogError(ex, "Failed to unregister settings pane. {message} (0x{hResult:X})", ex.GetMessage(), ex.HResult);
4041
}
4142
}
4243

@@ -51,7 +52,7 @@ private static void OnCommandsRequested(SettingsPane sender, SettingsPaneCommand
5152
new SettingsCommand(
5253
"LogFolder",
5354
"LogFolder",
54-
async handler => _ = Launcher.LaunchFolderAsync(await ApplicationData.Current.LocalFolder.CreateFolderAsync("MetroLogs", CreationCollisionOption.OpenIfExists))));
55+
async handler => _ = Launcher.LaunchFolderAsync(await ApplicationData.Current.LocalFolder.CreateFolderAsync("Logs", CreationCollisionOption.OpenIfExists))));
5556
args.Request.ApplicationCommands.Add(
5657
new SettingsCommand(
5758
"Repository",

CoreAppUAP/CoreAppUAP.csproj

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,13 @@
2020
<PropertyGroup>
2121
<AddMicrosoftVCLibsSDKReference>False</AddMicrosoftVCLibsSDKReference>
2222
<EnableAppxWindowsUniversalTargetDeviceFamilyItem>False</EnableAppxWindowsUniversalTargetDeviceFamilyItem>
23+
<MicrosoftWindowsSDKBuildToolsMSIXPackageVersion>1.7.20250508.1</MicrosoftWindowsSDKBuildToolsMSIXPackageVersion>
2324
</PropertyGroup>
2425

2526
<ItemGroup>
2627
<PackageReference Include="CommunityToolkit.Common" Version="8.4.0" />
27-
<PackageReference Include="MetroLog.Net6" Version="2.1.0" />
28+
<PackageReference Include="Karambolo.Extensions.Logging.File" Version="3.6.3" />
29+
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="9.0.6" />
2830
</ItemGroup>
2931

3032
<ItemGroup>

CoreAppUAP/Helpers/SettingsHelper.cs

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
using CommunityToolkit.Common.Helpers;
2-
using MetroLog;
3-
using MetroLog.Targets;
2+
using Karambolo.Extensions.Logging.File;
3+
using Microsoft.Extensions.Logging;
44
using System;
55
using System.Diagnostics.CodeAnalysis;
6-
using System.IO;
76
using System.Text.Json;
87
using System.Text.Json.Serialization;
98
using System.Text.Json.Serialization.Metadata;
@@ -38,19 +37,24 @@ public static void SetDefaultSettings()
3837

3938
public static partial class SettingsHelper
4039
{
41-
public static ILogManager LogManager { get; } = CreateLogManager();
40+
public static ILoggerFactory LoggerFactory { get; } = CreateLoggerFactory();
4241
public static ApplicationDataStorageHelper LocalObject { get; } = ApplicationDataStorageHelper.GetCurrent(new SystemTextJsonObjectSerializer());
4342

4443
static SettingsHelper() => SetDefaultSettings();
4544

46-
public static ILogManager CreateLogManager()
47-
{
48-
string path = Path.Combine(ApplicationData.Current.LocalFolder.Path, "MetroLogs");
49-
if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }
50-
LoggingConfiguration loggingConfiguration = new();
51-
loggingConfiguration.AddTarget(LogLevel.Info, LogLevel.Fatal, new StreamingFileTarget(path, 7));
52-
return LogManagerFactory.CreateLogManager(loggingConfiguration);
53-
}
45+
public static ILoggerFactory CreateLoggerFactory() =>
46+
Microsoft.Extensions.Logging.LoggerFactory.Create(x => _ = x.AddFile(x =>
47+
{
48+
x.RootPath = ApplicationData.Current.LocalFolder.Path;
49+
x.IncludeScopes = true;
50+
x.BasePath = "Logs";
51+
x.Files = [
52+
new LogFileOptions()
53+
{
54+
Path = "Log - <date>.log"
55+
}
56+
];
57+
}).AddDebug());
5458
}
5559

5660
public class SystemTextJsonObjectSerializer : IObjectSerializer

CoreAppUAP/Helpers/UIHelper.cs

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using System;
2-
using System.Text;
32
using System.Threading;
43
using System.Threading.Tasks;
54
using Windows.ApplicationModel;
@@ -9,15 +8,7 @@ namespace CoreAppUAP.Helpers
98
{
109
public static class UIHelper
1110
{
12-
public static string ExceptionToMessage(this Exception ex)
13-
{
14-
StringBuilder builder = new StringBuilder().AppendLine();
15-
if (!string.IsNullOrWhiteSpace(ex.Message)) { _ = builder.AppendLine($"Message: {ex.Message}"); }
16-
_ = builder.AppendLine($"HResult: {ex.HResult} (0x{ex.HResult:X})");
17-
if (!string.IsNullOrWhiteSpace(ex.StackTrace)) { _ = builder.AppendLine(ex.StackTrace); }
18-
if (!string.IsNullOrWhiteSpace(ex.HelpLink)) { _ = builder.Append($"HelperLink: {ex.HelpLink}"); }
19-
return builder.ToString();
20-
}
11+
public static object GetMessage(this Exception ex) => ex.Message is { Length: > 0 } message ? message : ex.GetType();
2112

2213
public static TResult AwaitByTaskCompleteSource<TResult>(this Task<TResult> function, CancellationToken cancellationToken = default)
2314
{

CoreAppUAP/Helpers/WindowHelper.cs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
11
using CoreAppUAP.Common;
22
using System;
33
using System.Collections.Generic;
4-
using System.Runtime.Versioning;
54
using System.Threading.Tasks;
65
using Windows.ApplicationModel.Core;
76
using Windows.UI.Core;
87
using Windows.UI.ViewManagement;
9-
using Windows.UI.WindowManagement;
108
using Windows.UI.Xaml;
11-
using Windows.UI.Xaml.Controls;
12-
using Windows.UI.Xaml.Hosting;
139

1410
namespace CoreAppUAP.Helpers
1511
{

CoreAppUAP/Pages/SettingsPages/SettingsPage.xaml.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ private async void Button_Click(object sender, RoutedEventArgs e)
8282
_ = Launcher.LaunchUriAsync(new Uri("https://github.com/wherewhere/CoreAppUAP/issues"));
8383
break;
8484
case "LogFolder":
85-
_ = Launcher.LaunchFolderAsync(await ApplicationData.Current.LocalFolder.CreateFolderAsync("MetroLogs", CreationCollisionOption.OpenIfExists));
85+
_ = Launcher.LaunchFolderAsync(await ApplicationData.Current.LocalFolder.CreateFolderAsync("Logs", CreationCollisionOption.OpenIfExists));
8686
break;
8787
case "NewWindow":
8888
_ = await WindowHelper.CreateWindowAsync(window =>

CoreAppUAP/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
namespace CoreAppUAP
44
{
5-
public static class Program
5+
public static partial class Program
66
{
77
public static void Main(string[] args) => Application.Start(static p => _ = new App());
88
}

CoreAppUAP/ViewModels/SettingsPages/SettingsViewModel.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using CoreAppUAP.Common;
22
using CoreAppUAP.Helpers;
3+
using Microsoft.Extensions.Logging;
34
using System;
45
using System.Collections.Generic;
56
using System.ComponentModel;
@@ -97,7 +98,7 @@ public SettingsViewModel(CoreDispatcher dispatcher)
9798
public async Task<bool> OpenLogFileAsync()
9899
{
99100
await ThreadSwitcher.ResumeBackgroundAsync();
100-
StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("MetroLogs", CreationCollisionOption.OpenIfExists);
101+
StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Logs", CreationCollisionOption.OpenIfExists);
101102
IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();
102103
if (files is [StorageFile file, ..])
103104
{
@@ -113,12 +114,12 @@ public async Task CleanLogsAsync()
113114
try
114115
{
115116
await ThreadSwitcher.ResumeBackgroundAsync();
116-
StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("MetroLogs", CreationCollisionOption.OpenIfExists);
117+
StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Logs", CreationCollisionOption.OpenIfExists);
117118
await folder.DeleteAsync();
118119
}
119120
catch (Exception ex)
120121
{
121-
SettingsHelper.LogManager.GetLogger(nameof(SettingsViewModel)).Error(ex.ExceptionToMessage(), ex);
122+
SettingsHelper.LoggerFactory.CreateLogger<SettingsViewModel>().LogError(ex, "Failed to clean the logs. {message} (0x{hResult:X})", ex.GetMessage(), ex.HResult);
122123
}
123124
finally
124125
{

0 commit comments

Comments
 (0)