diff --git a/src/MaaWpfGui/App.xaml.cs b/src/MaaWpfGui/App.xaml.cs index 92c27f5486..7051957dec 100644 --- a/src/MaaWpfGui/App.xaml.cs +++ b/src/MaaWpfGui/App.xaml.cs @@ -42,7 +42,7 @@ namespace MaaWpfGui protected override void OnStartup(StartupEventArgs e) { - if (WineRuntimeInformation.IsRunningUnderWine && MaaDesktopIntegration.Availabile) + if (WineRuntimeInformation.IsRunningUnderWine && MaaDesktopIntegration.Available) { // override buintin font map as early as possible FontConfigIntegration.Install(); diff --git a/src/MaaWpfGui/Configuration/Factory/ConfigFactory.cs b/src/MaaWpfGui/Configuration/Factory/ConfigFactory.cs index 2ded675fbe..c27c0364a7 100644 --- a/src/MaaWpfGui/Configuration/Factory/ConfigFactory.cs +++ b/src/MaaWpfGui/Configuration/Factory/ConfigFactory.cs @@ -247,16 +247,16 @@ public static class ConfigFactory if (result) { ConfigurationUpdateEvent?.Invoke(key, oldValue, newValue); - _logger.Debug($"Configuration {key} has been set to {newValue}"); + _logger.Debug("Configuration {Key} has been set to {NewValue}", key, newValue); } else { - _logger.Warning($"Failed to save configuration {key} to {newValue}"); + _logger.Warning("Failed to save configuration {Key} to {NewValue}", key, newValue); } } catch (Exception e) { - _logger.Error(e, $"Failed to save configuration {key} to {newValue}, Exception: {e.Message}"); + _logger.Error(e, "Failed to save configuration {Key} to {NewValue}, Exception: {Message}", key, newValue, e.Message); } } @@ -305,20 +305,20 @@ public static class ConfigFactory { if (Save()) { - _logger.Information($"{_configurationFile} saved"); + _logger.Information("{File} saved", _configurationFile); } else { - _logger.Warning($"{_configurationFile} save failed"); + _logger.Warning("{File} save failed", _configurationFile); } if (Save(_configurationBakFile)) { - _logger.Information($"{_configurationBakFile} saved"); + _logger.Information("{File} saved", _configurationBakFile); } else { - _logger.Warning($"{_configurationBakFile} save failed"); + _logger.Warning("{File} save failed", _configurationBakFile); } } } diff --git a/src/MaaWpfGui/Helper/ConfigurationHelper.cs b/src/MaaWpfGui/Helper/ConfigurationHelper.cs index e58f1a6088..c9efec74c6 100644 --- a/src/MaaWpfGui/Helper/ConfigurationHelper.cs +++ b/src/MaaWpfGui/Helper/ConfigurationHelper.cs @@ -450,20 +450,20 @@ namespace MaaWpfGui.Helper if (Save()) { - _logger.Information($"{_configurationFile} saved"); + _logger.Information("{File} saved", _configurationFile); } else { - _logger.Warning($"{_configurationFile} save failed"); + _logger.Warning("{File} save failed", _configurationFile); } if (Save(_configurationBakFile)) { - _logger.Information($"{_configurationBakFile} saved"); + _logger.Information("{File} saved", _configurationBakFile); } else { - _logger.Warning($"{_configurationBakFile} save failed"); + _logger.Warning("{File} save failed", _configurationBakFile); } } diff --git a/src/MaaWpfGui/Helper/EmulatorHelper.cs b/src/MaaWpfGui/Helper/EmulatorHelper.cs index b087a99029..2138cf95b9 100644 --- a/src/MaaWpfGui/Helper/EmulatorHelper.cs +++ b/src/MaaWpfGui/Helper/EmulatorHelper.cs @@ -102,8 +102,8 @@ public class EmulatorHelper } catch (Exception e) { - _logger.Error("Error: Failed to get the main module of the emulator process."); - _logger.Error(e.Message); + _logger.Error("Failed to get the main module of the emulator process."); + _logger.Error("{EMessage}", e.Message); return false; } @@ -145,15 +145,15 @@ public class EmulatorHelper var process = Process.Start(startInfo); if (process != null && process.WaitForExit(5000)) { - _logger.Information($"Emulator at index {emuIndex} closed through console. Console path: {consolePath}"); + _logger.Information("Emulator at index {EmuIndex} closed through console. Console path: {ConsolePath}", emuIndex, consolePath); return true; } - _logger.Warning($"Console process at index {emuIndex} did not exit within the specified timeout. Killing emulator by window. Console path: {consolePath}"); + _logger.Warning("Console process at index {EmuIndex} did not exit within the specified timeout. Killing emulator by window. Console path: {ConsolePath}", emuIndex, consolePath); return KillEmulatorByWindow(); } - _logger.Error("Error: MuMuManager.exe not found in expected locations (new or old). Trying to kill emulator by window."); + _logger.Error("MuMuManager.exe not found in expected locations (new or old). Trying to kill emulator by window."); return KillEmulatorByWindow(); } @@ -191,8 +191,8 @@ public class EmulatorHelper } catch (Exception e) { - _logger.Error("Error: Failed to get the main module of the emulator process."); - _logger.Error(e.Message); + _logger.Error("Failed to get the main module of the emulator process."); + _logger.Error("{EMessage}", e.Message); return false; } @@ -221,15 +221,15 @@ public class EmulatorHelper var process = Process.Start(startInfo); if (process != null && process.WaitForExit(5000)) { - _logger.Information($"Emulator at index {emuIndex} closed through console. Console path: {consolePath}"); + _logger.Information("Emulator at index {EmuIndex} closed through console. Console path: {ConsolePath}", emuIndex, consolePath); return true; } - _logger.Warning($"Console process at index {emuIndex} did not exit within the specified timeout. Killing emulator by window. Console path: {consolePath}"); + _logger.Warning("Console process at index {EmuIndex} did not exit within the specified timeout. Killing emulator by window. Console path: {ConsolePath}", emuIndex, consolePath); return KillEmulatorByWindow(); } - _logger.Information($"Error: `{consolePath}` not found, try to kill emulator by window."); + _logger.Error("`{ConsolePath}` not found, try to kill emulator by window.", consolePath); return KillEmulatorByWindow(); } @@ -265,8 +265,8 @@ public class EmulatorHelper } catch (Exception e) { - _logger.Error("Error: Failed to get the main module of the emulator process."); - _logger.Error(e.Message); + _logger.Error("Failed to get the main module of the emulator process."); + _logger.Error("{EMessage}", e.Message); return false; } @@ -295,15 +295,15 @@ public class EmulatorHelper var process = Process.Start(startInfo); if (process != null && process.WaitForExit(5000)) { - _logger.Information($"Emulator at index {emuIndex} closed through console. Console path: {consolePath}"); + _logger.Information("Emulator at index {EmuIndex} closed through console. Console path: {ConsolePath}", emuIndex, consolePath); return true; } - _logger.Warning($"Console process at index {emuIndex} did not exit within the specified timeout. Killing emulator by window. Console path: {consolePath}"); + _logger.Warning("Console process at index {EmuIndex} did not exit within the specified timeout. Killing emulator by window. Console path: {ConsolePath}", emuIndex, consolePath); return KillEmulatorByWindow(); } - _logger.Information($"Error: `{consolePath}` not found, try to kill emulator by window."); + _logger.Error("Error: `{ConsolePath}` not found, try to kill emulator by window.", consolePath); return KillEmulatorByWindow(); } @@ -331,8 +331,8 @@ public class EmulatorHelper } catch (Exception e) { - _logger.Error("Error: Failed to get the main module of the emulator process."); - _logger.Error(e.Message); + _logger.Error("Failed to get the main module of the emulator process."); + _logger.Error("{EMessage}", e.Message); return false; } @@ -361,15 +361,15 @@ public class EmulatorHelper var process = Process.Start(startInfo); if (process != null && process.WaitForExit(5000)) { - _logger.Information($"Emulator at index {emuIndex} closed through console. Console path: {consolePath}"); + _logger.Information("Emulator at index {EmuIndex} closed through console. Console path: {ConsolePath}", emuIndex, consolePath); return true; } - _logger.Warning($"Console process at index {emuIndex} did not exit within the specified timeout. Killing emulator by window. Console path: {consolePath}"); + _logger.Warning("Console process at index {EmuIndex} did not exit within the specified timeout. Killing emulator by window. Console path: {ConsolePath}", emuIndex, consolePath); return KillEmulatorByWindow(); } - _logger.Information($"Error: `{consolePath}` not found, try to kill emulator by window."); + _logger.Error("`{ConsolePath}` not found, try to kill emulator by window.", consolePath); return KillEmulatorByWindow(); } @@ -392,8 +392,8 @@ public class EmulatorHelper } catch (Exception e) { - _logger.Error("Error: Failed to get the main module of the emulator process."); - _logger.Error(e.Message); + _logger.Error("Failed to get the main module of the emulator process."); + _logger.Error("{EMessage}", e.Message); return false; } @@ -413,21 +413,21 @@ public class EmulatorHelper if (File.Exists(consolePath)) { - _logger.Information($"Info: `{consolePath}` has been found. This may be the BlueStacks China emulator, try to kill the emulator by window."); + _logger.Information("`{ConsolePath}` has been found. This may be the BlueStacks China emulator, try to kill the emulator by window.", consolePath); return KillEmulatorByWindow(); } - _logger.Information($"Info: `{consolePath}` not found. This may be the BlueStacks International emulator, try to kill the emulator by the port."); + _logger.Information("`{ConsolePath}` not found. This may be the BlueStacks International emulator, try to kill the emulator by the port.", consolePath); if (KillEmulator()) { return true; } - _logger.Information("Info: Failed to kill emulator by the port, try to kill emulator process with PID."); + _logger.Information("Failed to kill emulator by the port, try to kill emulator process with PID."); if (processes.Length > 1) { - _logger.Warning("Warning: The number of elements in processes exceeds one, abort closing the emulator"); + _logger.Warning("The number of elements in processes exceeds one, abort closing the emulator"); return false; } @@ -438,7 +438,7 @@ public class EmulatorHelper } catch (Exception ex) { - _logger.Error($"Error: Failed to kill emulator process with PID {processes[0].Id}. Exception: {ex.Message}"); + _logger.Error(ex, "Failed to kill emulator process with PID {ProcessId}. Exception: {ExceptionMessage}", processes[0].Id, ex.Message); } return false; @@ -453,10 +453,10 @@ public class EmulatorHelper int pid = 0; var windowName = new[] { - "明日方舟", - "明日方舟 - MuMu模拟器", - "BlueStacks App Player", - "BlueStacks", + "明日方舟", + "明日方舟 - MuMu模拟器", + "BlueStacks App Player", + "BlueStacks", }; foreach (string i in windowName) { @@ -484,12 +484,12 @@ public class EmulatorHelper emulator.Kill(); if (emulator.WaitForExit(5000)) { - _logger.Information($"Emulator with process ID {pid} killed successfully."); + _logger.Information("Emulator with process ID {Pid} killed successfully.", pid); KillEmulator(); return true; } - _logger.Error($"Failed to kill emulator with process ID {pid}."); + _logger.Error("Failed to kill emulator with process ID {Pid}.", pid); return false; } @@ -516,8 +516,8 @@ public class EmulatorHelper { int pid = 0; string address = ConfigurationHelper.GetValue(ConfigurationKeys.ConnectAddress, string.Empty); - var port = address.StartsWith("127") ? address.Substring(10) : "5555"; - _logger.Information($"address: {address}, port: {port}"); + var port = address.StartsWith("127") ? address[10..] : "5555"; + _logger.Information("address: {Address}, port: {Port}", address, port); string portCmd = "netstat -ano|findstr \"" + port + "\""; Process checkCmd = new Process diff --git a/src/MaaWpfGui/Main/AsstProxy.cs b/src/MaaWpfGui/Main/AsstProxy.cs index 93fb53242f..e746937de9 100644 --- a/src/MaaWpfGui/Main/AsstProxy.cs +++ b/src/MaaWpfGui/Main/AsstProxy.cs @@ -85,9 +85,9 @@ namespace MaaWpfGui.Main { fixed (byte* ptr = EncodeNullTerminatedUtf8(dirname)) { - _logger.Information($"AsstLoadResource dirname: {dirname}"); + _logger.Information("AsstLoadResource dirname: {Dirname}", dirname); var ret = MaaService.AsstLoadResource(ptr); - _logger.Information($"AsstLoadResource ret: {ret}"); + _logger.Information("AsstLoadResource ret: {Ret}", ret); return ret; } } @@ -102,21 +102,21 @@ namespace MaaWpfGui.Main private static unsafe bool AsstConnect(AsstHandle handle, string adbPath, string address, string config) { - _logger.Information($"handle: {(long)handle}, adbPath: {adbPath}, address: {address}, config: {config}"); + _logger.Information("handle: {Handle}, adbPath: {AdbPath}, address: {Address}, config: {Config}", (long)handle, adbPath, address, config); fixed (byte* ptr1 = EncodeNullTerminatedUtf8(adbPath), ptr2 = EncodeNullTerminatedUtf8(address), ptr3 = EncodeNullTerminatedUtf8(config)) { bool ret = MaaService.AsstConnect(handle, ptr1, ptr2, ptr3); - _logger.Information($"handle: {(long)handle}, adbPath: {adbPath}, address: {address}, config: {config}, return: {ret}"); + _logger.Information("handle: {Handle}, adbPath: {AdbPath}, address: {Address}, config: {Config}, return: {Ret}", (long)handle, adbPath, address, config, ret); return ret; } } private static unsafe void AsstSetConnectionExtras(string name, string extras) { - _logger.Information($"name: {name}, extras: {extras}"); + _logger.Information("name: {Name}, extras: {Extras}", name, extras); fixed (byte* ptr1 = EncodeNullTerminatedUtf8(name), ptr2 = EncodeNullTerminatedUtf8(extras)) @@ -372,11 +372,11 @@ namespace MaaWpfGui.Main const string Resource = @"\resource"; if (!Directory.Exists(path + Resource)) { - _logger.Warning($"Resource not found: {path + Resource}"); + _logger.Warning("Resource not found: {Path}", path + Resource); return true; } - _logger.Information($"Load resource: {path + Resource}"); + _logger.Information("Load resource: {Path}", path + Resource); return AsstLoadResource(path); } @@ -397,15 +397,15 @@ namespace MaaWpfGui.Main if (!Directory.Exists(tasksFolderPath)) { Directory.CreateDirectory(tasksFolderPath); - _logger.Information($"Created directory: {tasksFolderPath}"); + _logger.Information("Created directory: {TasksFolderPath}", tasksFolderPath); } File.Move(tasksJsonPath, newTasksJsonPath, true); - _logger.Information($"Moved {tasksJsonPath} to {newTasksJsonPath}"); + _logger.Information("Moved {TasksJsonPath} to {NewTasksJsonPath}", tasksJsonPath, newTasksJsonPath); } catch (Exception ex) { - _logger.Error($"Failed to move tasks.json: {ex.Message}"); + _logger.Error("Failed to move tasks.json: {ExMessage}", ex.Message); } } } @@ -2036,12 +2036,12 @@ namespace MaaWpfGui.Main if (!actualConnectionStatus) { Connected = false; - _logger.Information($"Connection lost to {_connectedAdb} {_connectedAddress}"); + _logger.Information("Connection lost to {ConnectedAdb} {ConnectedAddress}", _connectedAdb, _connectedAddress); error = "Connection lost"; } else { - _logger.Information($"Already connected to {_connectedAdb} {_connectedAddress}"); + _logger.Information("Already connected to {ConnectedAdb} {ConnectedAddress}", _connectedAdb, _connectedAddress); if (!_forcedReloadResource) { return true; diff --git a/src/MaaWpfGui/Main/Bootstrapper.cs b/src/MaaWpfGui/Main/Bootstrapper.cs index 954ab0e393..2c06bf9718 100644 --- a/src/MaaWpfGui/Main/Bootstrapper.cs +++ b/src/MaaWpfGui/Main/Bootstrapper.cs @@ -150,11 +150,11 @@ namespace MaaWpfGui.Main _logger = Log.Logger.ForContext(); _logger.Information("==================================="); _logger.Information("MaaAssistantArknights GUI started"); - _logger.Information($"Version {uiVersion}"); - _logger.Information($"Built at {builtDate:O}"); - _logger.Information($"Maa ENV: {maaEnv}"); - _logger.Information($"Command Line: {string.Join(' ', args)}"); - _logger.Information($"User Dir {Directory.GetCurrentDirectory()}"); + _logger.Information("Version {UiVersion}", uiVersion); + _logger.Information("Built at {BuiltDate:O}", builtDate); + _logger.Information("Maa ENV: {MaaEnv}", maaEnv); + _logger.Information("Command Line: {Join}", string.Join(' ', args)); + _logger.Information("User Dir {GetCurrentDirectory}", Directory.GetCurrentDirectory()); if (withDebugFile) { _logger.Information("Start with DEBUG file"); @@ -167,10 +167,10 @@ namespace MaaWpfGui.Main if (WineRuntimeInformation.IsRunningUnderWine) { - _logger.Information($"Running under Wine {WineRuntimeInformation.WineVersion} on {WineRuntimeInformation.HostSystemName}"); + _logger.Information("Running under Wine {WineVersion} on {HostSystemName}", WineRuntimeInformation.WineVersion, WineRuntimeInformation.HostSystemName); RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly; - _logger.Information($"MaaWineBridge status: {MaaWineBridge.Availability}"); - _logger.Information($"MaaDesktopIntegration available: {MaaDesktopIntegration.Availabile}"); + _logger.Information("MaaWineBridge status: {WineBridgeAvailability}", MaaWineBridge.Availability); + _logger.Information("MaaDesktopIntegration available: {Available}", MaaDesktopIntegration.Available); } _logger.Information("==================================="); @@ -333,7 +333,7 @@ namespace MaaWpfGui.Main Release(); _logger.Information("MaaAssistantArknights GUI exited"); - _logger.Information(string.Empty); + _logger.Information("{Message}", string.Empty); Log.CloseAndFlush(); base.OnExit(e); @@ -406,7 +406,7 @@ namespace MaaWpfGui.Main public static void ShutdownAndRestartWithoutArgs([CallerMemberName] string caller = "") { _isRestartingWithoutArgs = true; - _logger.Information($"Shutdown and restart without Args, call by `{caller}`"); + _logger.Information("Shutdown and restart without Args, call by `{Caller}`", caller); Execute.OnUIThread(Application.Current.Shutdown); } @@ -420,7 +420,7 @@ namespace MaaWpfGui.Main public static void Shutdown([CallerMemberName] string caller = "") { - _logger.Information($"Shutdown called by `{caller}`"); + _logger.Information("Shutdown called by `{Caller}`", caller); Execute.OnUIThread(Application.Current.Shutdown); } @@ -510,7 +510,7 @@ namespace MaaWpfGui.Main } catch (Exception ex) { - _logger.Error($"Error updating configuration: {desiredConfig}, ex: {ex.Message}"); + _logger.Error("Error updating configuration: {DesiredConfig}, ex: {ExMessage}", desiredConfig, ex.Message); } return false; diff --git a/src/MaaWpfGui/Models/ResourceUpdater.cs b/src/MaaWpfGui/Models/ResourceUpdater.cs index 145c8e5794..a8e48d5360 100644 --- a/src/MaaWpfGui/Models/ResourceUpdater.cs +++ b/src/MaaWpfGui/Models/ResourceUpdater.cs @@ -142,7 +142,7 @@ namespace MaaWpfGui.Models catch (Exception e) { _logger.Error(e, "Failed to send GET request to {Uri}", new Uri(url).GetLeftPart(UriPartial.Path)); - _logger.Information($"current_version: {currentVersion}, cdk: {cdk.Mask()}"); + _logger.Information("current_version: {CurrentVersion}, cdk: {Mask}", currentVersion, cdk.Mask()); } if (response is null) @@ -153,7 +153,7 @@ namespace MaaWpfGui.Models } var jsonStr = await response.Content.ReadAsStringAsync(); - _logger.Information(jsonStr); + _logger.Information("{jsonStr}", jsonStr); JObject? data = null; try { @@ -161,7 +161,7 @@ namespace MaaWpfGui.Models } catch (Exception ex) { - _logger.Error("Failed to deserialize json: " + ex.Message); + _logger.Error(ex, "Failed to deserialize json."); } if (data is null) @@ -214,7 +214,7 @@ namespace MaaWpfGui.Models // 到这里已经确定有新版本了 var releaseNote = data["data"]?["release_note"]?.ToString(); - _logger.Information($"New version found: {version:yyyy-MM-dd+HH:mm:ss.fff}, {releaseNote}"); + _logger.Information("New version found: {DateTime:yyyy-MM-dd+HH:mm:ss.fff}, {ReleaseNote}", version, releaseNote); releaseNote = LocalizationHelper.FormatResourceVersion(releaseNote, version); diff --git a/src/MaaWpfGui/Services/Notification/DiscordNotificationProvider.cs b/src/MaaWpfGui/Services/Notification/DiscordNotificationProvider.cs index e6403b5df8..151d535856 100644 --- a/src/MaaWpfGui/Services/Notification/DiscordNotificationProvider.cs +++ b/src/MaaWpfGui/Services/Notification/DiscordNotificationProvider.cs @@ -70,7 +70,7 @@ public class DiscordNotificationProvider(IHttpService httpService) : IExternalNo return null; } - _logger.Debug($"DM Channel created successfully. Channel ID: {channelId}"); + _logger.Debug("DM Channel created successfully. Channel ID: {JsonElement}", channelId); return channelId.GetString(); } diff --git a/src/MaaWpfGui/Services/Notification/DiscordWebhookNotificationProvider.cs b/src/MaaWpfGui/Services/Notification/DiscordWebhookNotificationProvider.cs index b5407cd6a3..f8d4dfcc29 100644 --- a/src/MaaWpfGui/Services/Notification/DiscordWebhookNotificationProvider.cs +++ b/src/MaaWpfGui/Services/Notification/DiscordWebhookNotificationProvider.cs @@ -61,7 +61,7 @@ public class DiscordWebhookNotificationProvider(IHttpService httpService) : IExt } var responseData = JsonSerializer.Deserialize(response); - _logger.Warning($"Failed to send Discord Webhook, {responseData?.Message}"); + _logger.Warning("Failed to send Discord Webhook, {ResponseDataMessage}", responseData?.Message); return false; } diff --git a/src/MaaWpfGui/Services/Notification/ServerChanNotificationProvider.cs b/src/MaaWpfGui/Services/Notification/ServerChanNotificationProvider.cs index df968e325a..0956c11577 100644 --- a/src/MaaWpfGui/Services/Notification/ServerChanNotificationProvider.cs +++ b/src/MaaWpfGui/Services/Notification/ServerChanNotificationProvider.cs @@ -69,11 +69,11 @@ namespace MaaWpfGui.Services.Notification return true; } - _logger.Warning($"Failed to send ServerChan notification, code: {code}"); + _logger.Warning("Failed to send ServerChan notification, code: {Value}", code); } else { - _logger.Warning($"Failed to send ServerChan notification, unknown response: {responseContent}"); + _logger.Warning("Failed to send ServerChan notification, unknown response: {ResponseContent}", responseContent); } } catch (Exception ex) diff --git a/src/MaaWpfGui/Services/Notification/SmtpNotificationProvider.cs b/src/MaaWpfGui/Services/Notification/SmtpNotificationProvider.cs index 3662fc7054..280329db5e 100644 --- a/src/MaaWpfGui/Services/Notification/SmtpNotificationProvider.cs +++ b/src/MaaWpfGui/Services/Notification/SmtpNotificationProvider.cs @@ -124,11 +124,11 @@ namespace MaaWpfGui.Services.Notification if (sendResult.Successful) { - _logger.Information($"Successfully sent Email notification to {emailTo}"); + _logger.Information("Successfully sent Email notification to {EmailTo}", emailTo); return true; } - _logger.Warning($"Failed to send Email notification to {emailTo}, {sendResult.ErrorMessages}"); + _logger.Warning("Failed to send Email notification to {EmailTo}, {SendResultErrorMessages}", emailTo, sendResult.ErrorMessages); return false; } diff --git a/src/MaaWpfGui/States/RunningState.cs b/src/MaaWpfGui/States/RunningState.cs index d8709e8ee0..9fa30700c5 100644 --- a/src/MaaWpfGui/States/RunningState.cs +++ b/src/MaaWpfGui/States/RunningState.cs @@ -202,7 +202,7 @@ namespace MaaWpfGui.States if (confirmed >= confirmTimes) { - _logger.Information($"Idle state confirmed after {confirmTimes} checks."); + _logger.Information("Idle state confirmed after {ConfirmTimes} checks.", confirmTimes); return; } } diff --git a/src/MaaWpfGui/Utilities/AutoStart.cs b/src/MaaWpfGui/Utilities/AutoStart.cs index a5d823638a..5c2d2cdc07 100644 --- a/src/MaaWpfGui/Utilities/AutoStart.cs +++ b/src/MaaWpfGui/Utilities/AutoStart.cs @@ -102,14 +102,14 @@ namespace MaaWpfGui.Utilities if (key == null) { error = "Failed to open registry key."; - _logger.Error(error); + _logger.Error("{ErrorMessage}", error); return false; } if (set) { key.SetValue(_registryKeyName, "\"" + _fileValue + "\""); - _logger.Information($"Set [{_registryKeyName}, \"{_fileValue}\"] into \"{CurrentUserRunKey}\""); + _logger.Information("Set [{RegistryKeyName}, \"{FileValue}\"] into \"{CurrentUserRunKey}\"", _registryKeyName, _fileValue, CurrentUserRunKey); } else { @@ -121,19 +121,19 @@ namespace MaaWpfGui.Utilities catch (UnauthorizedAccessException uae) { error = "Unauthorized access: " + uae.Message; - _logger.Error(error); + _logger.Error("{ErrorMessage}", error); return false; } catch (SecurityException se) { error = "Security error: " + se.Message; - _logger.Error(error); + _logger.Error("{ErrorMessage}", error); return false; } catch (Exception e) { error = "Failed to set startup: " + e.Message; - _logger.Error(error); + _logger.Error("{ErrorMessage}", error); return false; } } diff --git a/src/MaaWpfGui/Utilities/PowerManagement.cs b/src/MaaWpfGui/Utilities/PowerManagement.cs index b3633e8f26..a01ac1669d 100644 --- a/src/MaaWpfGui/Utilities/PowerManagement.cs +++ b/src/MaaWpfGui/Utilities/PowerManagement.cs @@ -106,7 +106,7 @@ namespace MaaWpfGui.Utilities } catch (Exception ex) { - _logger.Error($"Shutdown error: {ex.Message}"); + _logger.Error("Shutdown error: {ExMessage}", ex.Message); return false; } finally @@ -126,7 +126,7 @@ namespace MaaWpfGui.Utilities } catch (Exception ex) { - _logger.Error($"Hibernate error: {ex.Message}"); + _logger.Error("Hibernate error: {ExMessage}", ex.Message); return false; } } @@ -139,7 +139,7 @@ namespace MaaWpfGui.Utilities } catch (Exception ex) { - _logger.Error($"Sleep error: {ex.Message}"); + _logger.Error("Sleep error: {ExMessage}", ex.Message); return false; } } diff --git a/src/MaaWpfGui/ViewModels/UI/AnnouncementViewModel.cs b/src/MaaWpfGui/ViewModels/UI/AnnouncementViewModel.cs index eb51a87edf..255ee93181 100644 --- a/src/MaaWpfGui/ViewModels/UI/AnnouncementViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/AnnouncementViewModel.cs @@ -253,15 +253,18 @@ namespace MaaWpfGui.ViewModels.UI var body = await HttpResponseHelper.GetStringAsync(response); if (!string.IsNullOrEmpty(body) && AnnouncementInfo != body) { - _logger.Information($"old Announcement:\n" + - $"===================================\n" + - $"{AnnouncementInfo}\n" + - $"===================================\n" + - $"\n" + - $"new AnnouncementInfo:\n" + - $"===================================\n" + - $"{body}\n" + - $"==================================="); + const string Template = + "old Announcement:\n" + + "===================================\n" + + "{AnnouncementInfo}\n" + + "===================================\n\n" + + "new AnnouncementInfo:\n" + + "===================================\n" + + "{Body}\n" + + "==================================="; + _logger.Information(Template, + AnnouncementInfo, + body); AnnouncementInfo = body; DoNotRemindThisAnnouncementAgain = false; } diff --git a/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs b/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs index cceaf54ef9..b2fbe93f13 100644 --- a/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs @@ -975,7 +975,7 @@ namespace MaaWpfGui.ViewModels.UI catch (Exception ex) { AddLog(LocalizationHelper.GetString("CopilotJsonError"), UiLogColor.Error, showTime: false); - _logger.Error(ex.ToString()); + _logger.Error(ex, "Exception caught"); } } diff --git a/src/MaaWpfGui/ViewModels/UI/RecognizerViewModel.cs b/src/MaaWpfGui/ViewModels/UI/RecognizerViewModel.cs index b189cc6eea..db600974f0 100644 --- a/src/MaaWpfGui/ViewModels/UI/RecognizerViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/RecognizerViewModel.cs @@ -976,11 +976,11 @@ namespace MaaWpfGui.ViewModels.UI { _peepImageSemaphoreCurrentCount++; _peepImageSemaphore.Release(); - _logger.Information($"Screenshot Semaphore Full, increase semaphore count to {_peepImageSemaphoreCurrentCount}"); + _logger.Information("Screenshot Semaphore Full, increase semaphore count to {PeepImageSemaphoreCurrentCount}", _peepImageSemaphoreCurrentCount); return; } - _logger.Warning($"Screenshot Semaphore Full, Reduce Target FPS count to {--PeepTargetFps}"); + _logger.Warning("Screenshot Semaphore Full, Reduce Target FPS count to {PeepTargetFps}", --PeepTargetFps); _ = Execute.OnUIThreadAsync(() => { Growl.Clear(); @@ -1003,7 +1003,7 @@ namespace MaaWpfGui.ViewModels.UI // 若不满足条件,提前释放 frameData 避免内存泄露 if (!Peeping || count <= _peepImageNewestCount) { - _logger.Debug($"Peep image count {count} is not the newest, skip updating image."); + _logger.Debug("Peep image count {Count} is not the newest, skip updating image.", count); ArrayPool.Shared.Return(frameData); return; } diff --git a/src/MaaWpfGui/ViewModels/UI/TaskQueueViewModel.cs b/src/MaaWpfGui/ViewModels/UI/TaskQueueViewModel.cs index 9316583800..501ca98949 100644 --- a/src/MaaWpfGui/ViewModels/UI/TaskQueueViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/TaskQueueViewModel.cs @@ -256,7 +256,7 @@ namespace MaaWpfGui.ViewModels.UI bool HasOtherMaa() { var processesCount = Process.GetProcessesByName("MAA").Length; - _logger.Information($"MAA processes count: {processesCount}"); + _logger.Information("MAA processes count: {ProcessesCount}", processesCount); return processesCount > 1; } @@ -505,7 +505,7 @@ namespace MaaWpfGui.ViewModels.UI var delayTime = CalculateRandomDelay(); _ = Task.Run(async () => { - _logger.Information($"waiting for update check: {delayTime}"); + _logger.Information("waiting for update check: {DelayTime}", delayTime); await Task.Delay(delayTime); await Instances.VersionUpdateViewModel.VersionUpdateAndAskToRestartAsync(); await ResourceUpdater.ResourceUpdateAndReloadAsync(); @@ -572,14 +572,14 @@ namespace MaaWpfGui.ViewModels.UI if (timeToChangeConfig) { - _logger.Information($"Scheduled configuration change: Timer Index: {configIndex}"); + _logger.Information("Scheduled configuration change: Timer Index: {ConfigIndex}", configIndex); HandleConfigChange(configIndex); return; } if (timeToStart) { - _logger.Information($"Scheduled start: Timer Index: {configIndex}"); + _logger.Information("Scheduled start: Timer Index: {ConfigIndex}", configIndex); await HandleScheduledStart(configIndex); SettingsViewModel.TimerSettings.TimerModels.Timers[configIndex].IsOn ??= false; @@ -602,7 +602,11 @@ namespace MaaWpfGui.ViewModels.UI if (SettingsViewModel.TimerSettings.CustomConfig && Instances.SettingsViewModel.CurrentConfiguration != SettingsViewModel.TimerSettings.TimerModels.Timers[configIndex].TimerConfig) { - _logger.Warning($"Scheduled start skipped: Custom configuration is enabled, but the current configuration does not match the scheduled timer configuration (Timer Index: {configIndex}). Current Configuration: {Instances.SettingsViewModel.CurrentConfiguration}, Scheduled Configuration: {SettingsViewModel.TimerSettings.TimerModels.Timers[configIndex].TimerConfig}"); + _logger.Warning( + "Scheduled start skipped: Custom configuration is enabled, but the current configuration does not match the scheduled timer configuration (Timer Index: {ConfigIndex}). Current Configuration: {CurrentConfiguration}, Scheduled Configuration: {TimerConfig}", + configIndex, + Instances.SettingsViewModel.CurrentConfiguration, + SettingsViewModel.TimerSettings.TimerModels.Timers[configIndex].TimerConfig); return; } @@ -668,10 +672,10 @@ namespace MaaWpfGui.ViewModels.UI dialog.Close(); tcs.TrySetResult(true); }; - _logger.Information($"Timer wait time: {seconds}"); + _logger.Information("Timer wait time: {Seconds}", seconds); await Task.WhenAny(Task.Delay(delay), tcs.Task); dialog.Close(); - _logger.Information($"Timer canceled: {canceled}"); + _logger.Information("Timer canceled: {Canceled}", canceled); return canceled; } } @@ -989,7 +993,7 @@ namespace MaaWpfGui.ViewModels.UI { var log = new LogItemViewModel(content, color, weight, toolTip: toolTip); LogItemViewModels.Add(log); - _logger.Information(content); + _logger.Information("{Content}", content); }); } @@ -1002,7 +1006,7 @@ namespace MaaWpfGui.ViewModels.UI { LogItemViewModels.Clear(); _logger.Information("Main windows log clear."); - _logger.Information(string.Empty); + _logger.Information("{Empty}", string.Empty); }); } diff --git a/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs b/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs index 3bec8f9532..06c96fe2da 100644 --- a/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs @@ -248,7 +248,7 @@ public class VersionUpdateViewModel : Screen } catch (Exception e) { - _logger.Error($"parse mirrorChyan changes.json error: {e.Message}"); + _logger.Error("parse mirrorChyan changes.json error: {EMessage}", e.Message); } } @@ -282,7 +282,7 @@ public class VersionUpdateViewModel : Screen } catch (Exception e) { - _logger.Error($"move file error, path: {path}, moveTo: {moveTo}, error: {e.Message}"); + _logger.Error("move file error, path: {Path}, moveTo: {MoveTo}, error: {EMessage}", path, moveTo, e.Message); throw; } } @@ -299,8 +299,8 @@ public class VersionUpdateViewModel : Screen FileSystem.DeleteDirectory(dir.Replace(extractDir, curDir), UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); } catch - { // ignore - _logger.Error($"delete directory error, dir: {dir}"); + { + _logger.Error("delete directory error, dir: {Dir}", dir); } })); } @@ -344,7 +344,7 @@ public class VersionUpdateViewModel : Screen } catch (Exception e) { - _logger.Error($"move file error, file name: {file}, error: {e.Message}"); + _logger.Error("move file error, file name: {File}, error: {EMessage}", file, e.Message); throw; } } @@ -366,7 +366,7 @@ public class VersionUpdateViewModel : Screen } catch (Exception e) { - _logger.Error($"delete file error, filePath: {filePath}, error: {e.Message}, try to backup."); + _logger.Error("delete file error, filePath: {FilePath}, error: {EMessage}, try to backup.", filePath, e.Message); int index = 0; string currentDate = DateTime.Now.ToString("yyyyMMddHHmm"); string backupFilePath = $"{filePath}.{currentDate}.{index}"; @@ -383,7 +383,7 @@ public class VersionUpdateViewModel : Screen } catch (Exception e1) { - _logger.Error($"move file error, path: {filePath}, moveTo: {backupFilePath}, error: {e1.Message}"); + _logger.Error("move file error, path: {FilePath}, moveTo: {BackupFilePath}, error: {E1Message}", filePath, backupFilePath, e1.Message); throw; } } @@ -1006,7 +1006,7 @@ public class VersionUpdateViewModel : Screen catch (Exception e) { _logger.Error(e, "Failed to send GET request to {Uri}", new Uri(url).GetLeftPart(UriPartial.Path)); - _logger.Information($"current_version: {_curVersion}, cdk: {cdk.Mask()}, arch: {arch}, channel: {channel}"); + _logger.Information("current_version: {CurVersion}, cdk: {Mask}, arch: {Arch}, channel: {Channel}", _curVersion, cdk.Mask(), arch, channel); } if (response is null) @@ -1016,7 +1016,7 @@ public class VersionUpdateViewModel : Screen } var jsonStr = await response.Content.ReadAsStringAsync(); - _logger.Information(jsonStr); + _logger.Information("{JsonStr}", jsonStr); JObject? data = null; try { @@ -1024,7 +1024,7 @@ public class VersionUpdateViewModel : Screen } catch (Exception ex) { - _logger.Error("Failed to deserialize json: " + ex.Message); + _logger.Error(ex, "Failed to deserialize json"); } if (data is null) @@ -1083,7 +1083,7 @@ public class VersionUpdateViewModel : Screen } // 到这里已经确定有新版本了 - _logger.Information($"New version found: {version}"); + _logger.Information("New version found: {Version}", version); _mirrorcVersionName = version; _mirrorcReleaseNote = data["data"]?["release_note"]?.ToString(); diff --git a/src/MaaWpfGui/ViewModels/UserControl/Settings/ConnectSettingsUserControlModel.cs b/src/MaaWpfGui/ViewModels/UserControl/Settings/ConnectSettingsUserControlModel.cs index 4f141b457d..75655695d5 100644 --- a/src/MaaWpfGui/ViewModels/UserControl/Settings/ConnectSettingsUserControlModel.cs +++ b/src/MaaWpfGui/ViewModels/UserControl/Settings/ConnectSettingsUserControlModel.cs @@ -319,7 +319,7 @@ public class ConnectSettingsUserControlModel : PropertyChangedBase } catch (Exception e) { - _logger.Warning($"An error occurred: {e.Message}"); + _logger.Warning("An error occurred: {EMessage}", e.Message); EmulatorPath = string.Empty; } } @@ -472,7 +472,7 @@ public class ConnectSettingsUserControlModel : PropertyChangedBase } catch (Exception e) { - _logger.Warning($"An error occurred: {e.Message}"); + _logger.Warning("An error occurred: {EMessage}", e.Message); EmulatorPath = string.Empty; } } @@ -771,7 +771,7 @@ public class ConnectSettingsUserControlModel : PropertyChangedBase } catch (Exception e) { - _logger.Information(e.Message); + _logger.Warning(e, "Exception caught"); error = LocalizationHelper.GetString("EmulatorException"); return false; } @@ -1085,7 +1085,7 @@ public class ConnectSettingsUserControlModel : PropertyChangedBase } catch (Exception ex) { - _logger.Error($"An error occurred while deleting directory: {ex.GetType()}: {ex.Message}"); + _logger.Error("An error occurred while deleting directory: {Type}: {ExMessage}", ex.GetType(), ex.Message); ToastNotification.ShowDirect(LocalizationHelper.GetString("AdbDeletionFailedMessage")); return; } diff --git a/src/MaaWpfGui/ViewModels/UserControl/Settings/StartSettingsUserControlModel.cs b/src/MaaWpfGui/ViewModels/UserControl/Settings/StartSettingsUserControlModel.cs index f635e8e8d1..2a2c4b0f93 100644 --- a/src/MaaWpfGui/ViewModels/UserControl/Settings/StartSettingsUserControlModel.cs +++ b/src/MaaWpfGui/ViewModels/UserControl/Settings/StartSettingsUserControlModel.cs @@ -66,7 +66,7 @@ public class StartSettingsUserControlModel : PropertyChangedBase { if (!AutoStart.SetStart(value, out var error)) { - _logger.Error($"Failed to set startup: {error}"); + _logger.Error("Failed to set startup: {Error}", error); MessageBoxHelper.Show(error, LocalizationHelper.GetString("Warning"), icon: MessageBoxImage.Warning); return; } @@ -366,14 +366,11 @@ public class StartSettingsUserControlModel : PropertyChangedBase if (e is Win32Exception { NativeErrorCode: 740 }) { Instances.TaskQueueViewModel.AddLog(LocalizationHelper.GetString("EmulatorStartFailed"), UiLogColor.Warning); - - _logger.Warning( - "Insufficient permissions to start the emulator:\n" + - "EmulatorPath: " + EmulatorPath + "\n"); + _logger.Warning("Insufficient permissions to start the emulator:\nEmulatorPath: {EmulatorPath}\n", EmulatorPath); } else { - _logger.Warning("Emulator start failed with error: " + e.Message); + _logger.Warning("Emulator start failed with error: {ErrorMessage}", e.Message); } return; @@ -496,13 +493,13 @@ public class StartSettingsUserControlModel : PropertyChangedBase } catch (Exception ex) { - _logger.Error($"Error in HardRestartAdb: {ex.Message}"); + _logger.Error("Error in HardRestartAdb: {ExMessage}", ex.Message); } } } catch (Exception ex) { - _logger.Error($"Error in HardRestartAdb: {ex.Message}"); + _logger.Error("Error in HardRestartAdb: {ExMessage}", ex.Message); } } diff --git a/src/MaaWpfGui/ViewModels/UserControl/TaskQueue/InfrastSettingsUserControlModel.cs b/src/MaaWpfGui/ViewModels/UserControl/TaskQueue/InfrastSettingsUserControlModel.cs index 601220c772..c944d9bf4c 100644 --- a/src/MaaWpfGui/ViewModels/UserControl/TaskQueue/InfrastSettingsUserControlModel.cs +++ b/src/MaaWpfGui/ViewModels/UserControl/TaskQueue/InfrastSettingsUserControlModel.cs @@ -428,7 +428,7 @@ public class InfrastSettingsUserControlModel : TaskViewModel { var count = CustomInfrastPlanInfoList.Count; value = ((value % count) + count) % count; - _logger.Warning($"CustomInfrastPlanIndex out of range, reset to Index % Count: {value}"); + _logger.Warning("CustomInfrastPlanIndex out of range, reset to Index % Count: {Value}", value); } if (value != _customInfrastPlanIndex && NeedAddCustomInfrastPlanInfo) diff --git a/src/MaaWpfGui/WineCompat/MaaDesktopIntegration.cs b/src/MaaWpfGui/WineCompat/MaaDesktopIntegration.cs index ce10e89fd3..cf7ff48ed3 100644 --- a/src/MaaWpfGui/WineCompat/MaaDesktopIntegration.cs +++ b/src/MaaWpfGui/WineCompat/MaaDesktopIntegration.cs @@ -18,7 +18,7 @@ namespace MaaWpfGui.WineCompat; internal unsafe class MaaDesktopIntegration { - public static bool Availabile { get; } + public static bool Available { get; } static MaaDesktopIntegration() { @@ -28,7 +28,7 @@ internal unsafe class MaaDesktopIntegration { glib_default_main_loop_start(); AppDomain.CurrentDomain.ProcessExit += (sender, args) => glib_default_main_loop_stop(); - Availabile = true; + Available = true; } catch {