From 42b609b597128322965e178f2591f9707c406190 Mon Sep 17 00:00:00 2001 From: ChsBuffer <33744752+chsbuffer@users.noreply.github.com> Date: Wed, 31 Mar 2021 19:19:31 +0800 Subject: [PATCH] Refactor OpenLogFile --- Netch/Controllers/Guard.cs | 4 +- Netch/Controllers/MainController.cs | 12 ++--- Netch/Controllers/NFController.cs | 16 +++--- Netch/Controllers/NTTController.cs | 4 +- Netch/Controllers/TUNController.cs | 32 ++++++------ Netch/Controllers/UpdateChecker.cs | 10 ++-- Netch/Forms/MainForm.cs | 10 ++-- Netch/Forms/SettingForm.cs | 2 +- Netch/Global.cs | 21 ++++++-- Netch/Interfaces/ILogger.cs | 11 +++++ Netch/Interops/RedirectorInterop.cs | 2 +- Netch/Interops/TUNInterop.cs | 2 +- Netch/Models/Loggers/ConsoleLogger.cs | 52 ++++++++++++++++++++ Netch/Models/Loggers/FileLogger.cs | 48 ++++++++++++++++++ Netch/Models/OutboundAdapter.cs | 4 +- Netch/Models/TunAdapter.cs | 2 +- Netch/Netch.cs | 8 +-- Netch/Servers/Shadowsocks/SSUtil.cs | 2 +- Netch/Servers/ShadowsocksR/SSRUtil.cs | 6 +-- Netch/Updater/Updater.cs | 2 +- Netch/Utils/Bandwidth.cs | 2 +- Netch/Utils/Configuration.cs | 4 +- Netch/Utils/Firewall.cs | 6 +-- Netch/Utils/Logging.cs | 70 --------------------------- Netch/Utils/ModeHelper.cs | 4 +- Netch/Utils/PortHelper.cs | 2 +- Netch/Utils/ShareLink.cs | 29 ++++++----- Netch/Utils/Subscription.cs | 2 +- Netch/Utils/Utils.cs | 2 +- Netch/Utils/i18N.cs | 4 +- 30 files changed, 215 insertions(+), 160 deletions(-) create mode 100644 Netch/Interfaces/ILogger.cs create mode 100644 Netch/Models/Loggers/ConsoleLogger.cs create mode 100644 Netch/Models/Loggers/FileLogger.cs delete mode 100644 Netch/Utils/Logging.cs diff --git a/Netch/Controllers/Guard.cs b/Netch/Controllers/Guard.cs index bbabe328..10e1e39b 100644 --- a/Netch/Controllers/Guard.cs +++ b/Netch/Controllers/Guard.cs @@ -84,7 +84,7 @@ namespace Netch.Controllers } catch (Win32Exception e) { - Logging.Error($"停止 {MainFile} 错误:\n" + e); + Global.Logger.Error($"停止 {MainFile} 错误:\n" + e); } catch { @@ -268,7 +268,7 @@ namespace Netch.Controllers } catch (Exception exception) { - Logging.Warning($"写入 {Name} 日志错误:\n" + exception.Message); + Global.Logger.Warning($"写入 {Name} 日志错误:\n" + exception.Message); } } } diff --git a/Netch/Controllers/MainController.cs b/Netch/Controllers/MainController.cs index f3b06aeb..6160c1d6 100644 --- a/Netch/Controllers/MainController.cs +++ b/Netch/Controllers/MainController.cs @@ -54,7 +54,7 @@ namespace Netch.Controllers public static void Start(Server server, Mode mode) { - Logging.Info($"启动主控制器: {server.Type} [{mode.Type}]{mode.Remark}"); + Global.Logger.Info($"启动主控制器: {server.Type} [{mode.Type}]{mode.Remark}"); Server = server; Mode = mode; @@ -89,8 +89,8 @@ namespace Netch.Controllers case MessageException: throw; default: - Logging.Error(e.ToString()); - Utils.Utils.Open(Logging.LogFile); + Global.Logger.Error(e.ToString()); + Global.Logger.ShowLog(); throw new MessageException($"未处理异常\n{e.Message}"); } } @@ -158,8 +158,8 @@ namespace Netch.Controllers } catch (Exception e) { - Logging.Error(e.ToString()); - Utils.Utils.Open(Logging.LogFile); + Global.Logger.Error(e.ToString()); + Global.Logger.ShowLog(); } ModeController = null; @@ -193,7 +193,7 @@ namespace Netch.Controllers } catch (Exception e) { - Logging.Warning(e.ToString()); + Global.Logger.Warning(e.ToString()); continue; } diff --git a/Netch/Controllers/NFController.cs b/Netch/Controllers/NFController.cs index 62bbdf8c..fb1a7e08 100644 --- a/Netch/Controllers/NFController.cs +++ b/Netch/Controllers/NFController.cs @@ -176,8 +176,8 @@ namespace Netch.Controllers var binFileVersion = Utils.Utils.GetFileVersion(BinDriver); var systemFileVersion = Utils.Utils.GetFileVersion(SystemDriver); - Logging.Info("内置驱动版本: " + binFileVersion); - Logging.Info("系统驱动版本: " + systemFileVersion); + Global.Logger.Info("内置驱动版本: " + binFileVersion); + Global.Logger.Info("系统驱动版本: " + systemFileVersion); if (!File.Exists(SystemDriver)) { @@ -207,7 +207,7 @@ namespace Netch.Controllers if (!reinstall) return; - Logging.Info("更新驱动"); + Global.Logger.Info("更新驱动"); UninstallDriver(); InstallDriver(); } @@ -218,7 +218,7 @@ namespace Netch.Controllers /// 驱动是否安装成功 private static void InstallDriver() { - Logging.Info("安装 NF 驱动"); + Global.Logger.Info("安装 NF 驱动"); if (!File.Exists(BinDriver)) throw new MessageException(i18N.Translate("builtin driver files missing, can't install NF driver")); @@ -229,7 +229,7 @@ namespace Netch.Controllers } catch (Exception e) { - Logging.Error("驱动复制失败\n" + e); + Global.Logger.Error("驱动复制失败\n" + e); throw new MessageException($"Copy NF driver file failed\n{e.Message}"); } @@ -238,11 +238,11 @@ namespace Netch.Controllers var result = NFAPI.nf_registerDriver("netfilter2"); if (result == NF_STATUS.NF_STATUS_SUCCESS) { - Logging.Info("驱动安装成功"); + Global.Logger.Info("驱动安装成功"); } else { - Logging.Error($"注册驱动失败,返回值:{result}"); + Global.Logger.Error($"注册驱动失败,返回值:{result}"); throw new MessageException($"Register NF driver failed\n{result}"); } } @@ -253,7 +253,7 @@ namespace Netch.Controllers /// 是否成功卸载 public static bool UninstallDriver() { - Logging.Info("卸载 NF 驱动"); + Global.Logger.Info("卸载 NF 驱动"); try { if (NFService.Status == ServiceControllerStatus.Running) diff --git a/Netch/Controllers/NTTController.cs b/Netch/Controllers/NTTController.cs index a09689da..10021bbd 100644 --- a/Netch/Controllers/NTTController.cs +++ b/Netch/Controllers/NTTController.cs @@ -39,7 +39,7 @@ namespace Netch.Controllers } catch (Exception e) { - Logging.Warning($"写入 {Name} 日志错误:\n" + e.Message); + Global.Logger.Warning($"写入 {Name} 日志错误:\n" + e.Message); } if (output.IsNullOrWhiteSpace()) @@ -86,7 +86,7 @@ namespace Netch.Controllers } catch (Exception e) { - Logging.Error($"{Name} 控制器出错:\n" + e); + Global.Logger.Error($"{Name} 控制器出错:\n" + e); try { Stop(); diff --git a/Netch/Controllers/TUNController.cs b/Netch/Controllers/TUNController.cs index 7c19f75c..e755a726 100644 --- a/Netch/Controllers/TUNController.cs +++ b/Netch/Controllers/TUNController.cs @@ -8,7 +8,9 @@ using System.Threading.Tasks; using Netch.Models; using Netch.Servers.Socks5; using Netch.Utils; +using Vanara.PInvoke; using static Netch.Interops.TUNInterop; +using static Vanara.PInvoke.Ws2_32; namespace Netch.Controllers { @@ -84,7 +86,7 @@ namespace Netch.Controllers #endregion - Logging.Debug("tun2socks init"); + Global.Logger.Debug("tun2socks init"); Init(); _tunAdapter = new TunAdapter(); @@ -104,8 +106,8 @@ namespace Netch.Controllers { var binHash = Utils.Utils.SHA256CheckSum(BinDriver); var sysHash = Utils.Utils.SHA256CheckSum(SysDriver); - Logging.Info("自带 wintun.dll Hash: " + binHash); - Logging.Info("系统 wintun.dll Hash: " + sysHash); + Global.Logger.Info("自带 wintun.dll Hash: " + binHash); + Global.Logger.Info("系统 wintun.dll Hash: " + sysHash); if (binHash == sysHash) return; @@ -115,7 +117,7 @@ namespace Netch.Controllers } catch (Exception e) { - Logging.Error(e.ToString()); + Global.Logger.Error(e.ToString()); throw new MessageException($"Failed to copy wintun.dll to system directory: {e.Message}"); } } @@ -142,13 +144,13 @@ namespace Netch.Controllers private void SetupRouteTable(Mode mode) { Global.MainForm.StatusText(i18N.Translate("SetupBypass")); - Logging.Info("设置路由规则"); + Global.Logger.Info("设置路由规则"); - Logging.Info("绕行 → 服务器 IP"); + Global.Logger.Info("绕行 → 服务器 IP"); if (!IPAddress.IsLoopback(_serverAddresses)) RouteAction(Action.Create, $"{_serverAddresses}/32", RouteType.Outbound); - Logging.Info("绕行 → 全局绕过 IP"); + Global.Logger.Info("绕行 → 全局绕过 IP"); RouteAction(Action.Create, Global.Settings.TUNTAP.BypassIPs, RouteType.Outbound); #region Rule IPs @@ -157,12 +159,12 @@ namespace Netch.Controllers { case 1: // 代理规则 IP - Logging.Info("代理 → 规则 IP"); + Global.Logger.Info("代理 → 规则 IP"); RouteAction(Action.Create, mode.FullRule, RouteType.TUNTAP); if (Global.Settings.TUNTAP.ProxyDNS) { - Logging.Info("代理 → 自定义 DNS"); + Global.Logger.Info("代理 → 自定义 DNS"); if (Global.Settings.TUNTAP.UseCustomDNS) RouteAction(Action.Create, Global.Settings.TUNTAP.HijackDNS.Select(ip => $"{ip}/32"), RouteType.TUNTAP); else @@ -173,7 +175,7 @@ namespace Netch.Controllers case 2: // 绕过规则 IP - Logging.Info("绕行 → 规则 IP"); + Global.Logger.Info("绕行 → 规则 IP"); RouteAction(Action.Create, mode.FullRule, RouteType.Outbound); break; } @@ -182,7 +184,7 @@ namespace Netch.Controllers if (mode.Type == 2) { - Logging.Info("代理 → 全局"); + Global.Logger.Info("代理 → 全局"); SetInterface(RouteType.TUNTAP, 0); RouteAction(Action.Create, "0.0.0.0/0", RouteType.TUNTAP, record: false); } @@ -267,11 +269,9 @@ namespace Netch.Controllers throw new ArgumentOutOfRangeException(nameof(action), action, null); } - Logging.Debug($"{action}Route(\"{ip}\", {cidr}, \"{gateway}\", {index}, {metric})"); + Global.Logger.Debug($"{action}Route(\"{ip}\", {cidr}, \"{gateway}\", {index}, {metric})"); if (!result) - { - Logging.Warning($"Failed to invoke {action}Route(\"{ip}\", {cidr}, \"{gateway}\", {index}, {metric})"); - } + Global.Logger.Warning($"Failed to invoke {action}Route(\"{ip}\", {cidr}, \"{gateway}\", {index}, {metric})"); return result; } @@ -284,7 +284,7 @@ namespace Netch.Controllers var s = ipNetwork.Split('/'); if (s.Length != 2) { - Logging.Warning($"Failed to parse rule {ipNetwork}"); + Global.Logger.Warning($"Failed to parse rule {ipNetwork}"); return false; } diff --git a/Netch/Controllers/UpdateChecker.cs b/Netch/Controllers/UpdateChecker.cs index a8de12ca..ddaf12d7 100644 --- a/Netch/Controllers/UpdateChecker.cs +++ b/Netch/Controllers/UpdateChecker.cs @@ -47,24 +47,24 @@ namespace Netch.Controllers var releases = JsonSerializer.Deserialize>(json)!; LatestRelease = VersionUtil.GetLatestRelease(releases, isPreRelease); - Logging.Info($"Github 最新发布版本: {LatestRelease.tag_name}"); + Global.Logger.Info($"Github 最新发布版本: {LatestRelease.tag_name}"); if (VersionUtil.CompareVersion(LatestRelease.tag_name, Version) > 0) { - Logging.Info("发现新版本"); + Global.Logger.Info("发现新版本"); NewVersionFound?.Invoke(null, new EventArgs()); } else { - Logging.Info("目前是最新版本"); + Global.Logger.Info("目前是最新版本"); NewVersionNotFound?.Invoke(null, new EventArgs()); } } catch (Exception e) { if (e is WebException) - Logging.Warning($"获取新版本失败: {e.Message}"); + Global.Logger.Warning($"获取新版本失败: {e.Message}"); else - Logging.Warning(e.ToString()); + Global.Logger.Warning(e.ToString()); NewVersionFoundFailed?.Invoke(null, new EventArgs()); } diff --git a/Netch/Forms/MainForm.cs b/Netch/Forms/MainForm.cs index 7a851da3..77397667 100644 --- a/Netch/Forms/MainForm.cs +++ b/Netch/Forms/MainForm.cs @@ -297,7 +297,7 @@ namespace Netch.Forms catch (Exception e) { NotifyTip(i18N.Translate("update servers failed") + "\n" + e.Message, info: false); - Logging.Error("更新服务器 失败!" + e); + Global.Logger.Error("更新服务器 失败!" + e); } finally { @@ -432,8 +432,8 @@ namespace Netch.Forms { if (exception is not MessageException) { - Logging.Error($"更新失败: {exception}"); - Utils.Utils.Open(Logging.LogFile); + Global.Logger.Error($"更新失败: {exception}"); + Global.Logger.ShowLog(); } NotifyTip(exception.Message, info: false); @@ -1178,7 +1178,7 @@ namespace Netch.Forms if (!IsWaiting()) { _resumeFlag = true; - Logging.Info("操作系统即将挂起,自动停止"); + Global.Logger.Info("操作系统即将挂起,自动停止"); ControlButton_Click(null, null); } @@ -1187,7 +1187,7 @@ namespace Netch.Forms if (_resumeFlag) { _resumeFlag = false; - Logging.Info("操作系统即将从挂起状态继续,自动重启"); + Global.Logger.Info("操作系统即将从挂起状态继续,自动重启"); ControlButton_Click(null, null); } diff --git a/Netch/Forms/SettingForm.cs b/Netch/Forms/SettingForm.cs index a8504505..9e86c88e 100644 --- a/Netch/Forms/SettingForm.cs +++ b/Netch/Forms/SettingForm.cs @@ -63,7 +63,7 @@ namespace Netch.Forms } catch (Exception e) { - Logging.Warning($"Load stun.txt failed: {e.Message}"); + Global.Logger.Warning($"Load stun.txt failed: {e.Message}"); stuns = null; } diff --git a/Netch/Global.cs b/Netch/Global.cs index 44913acc..4fc22c72 100644 --- a/Netch/Global.cs +++ b/Netch/Global.cs @@ -4,7 +4,9 @@ using System.Text.Encodings.Web; using System.Text.Json; using System.Windows.Forms; using Netch.Forms; +using Netch.Interfaces; using Netch.Models; +using Netch.Models.Loggers; namespace Netch { @@ -25,6 +27,22 @@ namespace Netch /// public static readonly List Modes = new(); + public static readonly string NetchDir; + public static readonly string NetchExecutable; + + static Global() + { + NetchExecutable = Application.ExecutablePath; + NetchDir = Application.StartupPath; +#if DEBUG + Logger = new ConsoleLogger(); +#else + Logger = new FileLogger(); +#endif + } + + public static ILogger Logger { get; } + /// /// 主窗体的静态实例 /// @@ -36,8 +54,5 @@ namespace Netch IgnoreNullValues = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; - - public static readonly string NetchDir = Application.StartupPath; - public static readonly string NetchExecutable = Application.ExecutablePath; } } \ No newline at end of file diff --git a/Netch/Interfaces/ILogger.cs b/Netch/Interfaces/ILogger.cs new file mode 100644 index 00000000..922b288f --- /dev/null +++ b/Netch/Interfaces/ILogger.cs @@ -0,0 +1,11 @@ +namespace Netch.Interfaces +{ + public interface ILogger + { + void Info(string text); + void Warning(string text); + void Error(string text); + void Debug(string s); + void ShowLog(); + } +} \ No newline at end of file diff --git a/Netch/Interops/RedirectorInterop.cs b/Netch/Interops/RedirectorInterop.cs index 25b3388f..0394a5a4 100644 --- a/Netch/Interops/RedirectorInterop.cs +++ b/Netch/Interops/RedirectorInterop.cs @@ -43,7 +43,7 @@ namespace Netch.Interops public static bool Dial(NameList name, string value) { - Logging.Debug($"Dial {name} {value}"); + Global.Logger.Debug($"Dial {name} {value}"); return aio_dial(name, value); } diff --git a/Netch/Interops/TUNInterop.cs b/Netch/Interops/TUNInterop.cs index 67c1e263..2afbd49b 100644 --- a/Netch/Interops/TUNInterop.cs +++ b/Netch/Interops/TUNInterop.cs @@ -36,7 +36,7 @@ namespace Netch.Interops public static bool Dial(NameList name, string value) { - Logging.Debug($"Dial {name} {value}"); + Global.Logger.Debug($"Dial {name} {value}"); return tun_dial(name, Encoding.UTF8.GetBytes(value)); } diff --git a/Netch/Models/Loggers/ConsoleLogger.cs b/Netch/Models/Loggers/ConsoleLogger.cs new file mode 100644 index 00000000..f5b4d913 --- /dev/null +++ b/Netch/Models/Loggers/ConsoleLogger.cs @@ -0,0 +1,52 @@ +using System; +using Netch.Interfaces; + +namespace Netch.Models.Loggers +{ + public class ConsoleLogger : ILogger + { + public void Info(string text) + { + Write(text, LogLevel.INFO); + } + + public void Warning(string text) + { + Write(text, LogLevel.WARNING); + } + + public void Error(string text) + { + Write(text, LogLevel.ERROR); + } + + private void Write(string text, LogLevel logLevel) + { + var contents = $@"[{DateTime.Now}][{logLevel.ToString()}] {text}{Constants.EOF}"; + switch (logLevel) + { + case LogLevel.DEBUG: + case LogLevel.INFO: + case LogLevel.WARNING: + Console.Write(contents); + break; + case LogLevel.ERROR: + Console.Error.Write(contents); + break; + default: + throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); + } + } + + public void Debug(string s) + { +#if DEBUG + Write(s, LogLevel.DEBUG); +#endif + } + + public void ShowLog() + { + } + } +} \ No newline at end of file diff --git a/Netch/Models/Loggers/FileLogger.cs b/Netch/Models/Loggers/FileLogger.cs new file mode 100644 index 00000000..f2bda3e3 --- /dev/null +++ b/Netch/Models/Loggers/FileLogger.cs @@ -0,0 +1,48 @@ +using System; +using System.IO; +using Netch.Interfaces; + +namespace Netch.Models.Loggers +{ + public class FileLogger : ILogger + { + public string LogFile { get; set; }= Path.Combine(Global.NetchDir, "logging\\application.log"); + + private readonly object _fileLock = new(); + + public void Info(string text) + { + Write(text, LogLevel.INFO); + } + + public void Warning(string text) + { + Write(text, LogLevel.WARNING); + } + + public void Error(string text) + { + Write(text, LogLevel.ERROR); + } + + public void Write(string text, LogLevel logLevel) + { + var contents = $@"[{DateTime.Now}][{logLevel.ToString()}] {text}{Constants.EOF}"; + + lock (_fileLock) + File.AppendAllText(LogFile, contents); + } + + public void Debug(string s) + { +#if DEBUG + Write(s, LogLevel.DEBUG); +#endif + } + + public void ShowLog() + { + Utils.Utils.Open(LogFile); + } + } +} \ No newline at end of file diff --git a/Netch/Models/OutboundAdapter.cs b/Netch/Models/OutboundAdapter.cs index 6178e90d..bba99543 100644 --- a/Netch/Models/OutboundAdapter.cs +++ b/Netch/Models/OutboundAdapter.cs @@ -25,8 +25,8 @@ namespace Netch.Models InterfaceIndex = (int) pRoute.dwForwardIfIndex; Gateway = new IPAddress(pRoute.dwForwardNextHop.S_un_b); - Logging.Info($"出口 网关 地址:{Gateway}"); - Logging.Info($"出口适配器:{NetworkInterface.Name} {NetworkInterface.Id} {NetworkInterface.Description}, index: {InterfaceIndex}"); + Global.Logger.Info($"出口 网关 地址:{Gateway}"); + Global.Logger.Info($"出口适配器:{NetworkInterface.Name} {NetworkInterface.Id} {NetworkInterface.Description}, index: {InterfaceIndex}"); } public IPAddress Address { get; } diff --git a/Netch/Models/TunAdapter.cs b/Netch/Models/TunAdapter.cs index 8432d11b..991f0cad 100644 --- a/Netch/Models/TunAdapter.cs +++ b/Netch/Models/TunAdapter.cs @@ -14,7 +14,7 @@ namespace Netch.Models NetworkInterface = NetworkInterface.GetAllNetworkInterfaces().First(i => i.GetIPProperties().GetIPv4Properties().Index == InterfaceIndex); Gateway = IPAddress.Parse(Global.Settings.TUNTAP.Gateway); - Logging.Info($"WinTUN 适配器:{NetworkInterface.Name} {NetworkInterface.Id} {NetworkInterface.Description}, index: {InterfaceIndex}"); + Global.Logger.Info($"WinTUN 适配器:{NetworkInterface.Name} {NetworkInterface.Id} {NetworkInterface.Description}, index: {InterfaceIndex}"); } diff --git a/Netch/Netch.cs b/Netch/Netch.cs index 883d838c..593f7bd0 100644 --- a/Netch/Netch.cs +++ b/Netch/Netch.cs @@ -80,8 +80,8 @@ namespace Netch Environment.Exit(2); } - Logging.Info($"版本: {UpdateChecker.Owner}/{UpdateChecker.Repo}@{UpdateChecker.Version}"); - Task.Run(() => { Logging.Info($"主程序 SHA256: {Utils.Utils.SHA256CheckSum(Global.NetchExecutable)}"); }); + Global.Logger.Info($"版本: {UpdateChecker.Owner}/{UpdateChecker.Repo}@{UpdateChecker.Version}"); + Task.Run(() => { Global.Logger.Info($"主程序 SHA256: {Utils.Utils.SHA256CheckSum(Global.NetchExecutable)}"); }); // 绑定错误捕获 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); @@ -101,8 +101,8 @@ namespace Netch public static void Application_OnException(object sender, ThreadExceptionEventArgs e) { - Logging.Error(e.Exception.ToString()); - Utils.Utils.Open(Logging.LogFile); + Global.Logger.Error(e.Exception.ToString()); + Global.Logger.ShowLog(); } private static void SingleInstance_ArgumentsReceived(IEnumerable args) diff --git a/Netch/Servers/Shadowsocks/SSUtil.cs b/Netch/Servers/Shadowsocks/SSUtil.cs index aa3a93be..a8820afc 100644 --- a/Netch/Servers/Shadowsocks/SSUtil.cs +++ b/Netch/Servers/Shadowsocks/SSUtil.cs @@ -65,7 +65,7 @@ namespace Netch.Servers.Shadowsocks var server = (Shadowsocks) s; if (!SSGlobal.EncryptMethods.Contains(server.EncryptMethod)) { - Logging.Error($"不支持的 SS 加密方式:{server.EncryptMethod}"); + Global.Logger.Error($"不支持的 SS 加密方式:{server.EncryptMethod}"); { return false; } diff --git a/Netch/Servers/ShadowsocksR/SSRUtil.cs b/Netch/Servers/ShadowsocksR/SSRUtil.cs index e31ae5bf..66ed82d9 100644 --- a/Netch/Servers/ShadowsocksR/SSRUtil.cs +++ b/Netch/Servers/ShadowsocksR/SSRUtil.cs @@ -146,19 +146,19 @@ namespace Netch.Servers.ShadowsocksR var server = (ShadowsocksR) s; if (!SSRGlobal.EncryptMethods.Contains(server.EncryptMethod)) { - Logging.Error($"不支持的 SSR 加密方式:{server.EncryptMethod}"); + Global.Logger.Error($"不支持的 SSR 加密方式:{server.EncryptMethod}"); return false; } if (!SSRGlobal.Protocols.Contains(server.Protocol)) { - Logging.Error($"不支持的 SSR 协议:{server.Protocol}"); + Global.Logger.Error($"不支持的 SSR 协议:{server.Protocol}"); return false; } if (!SSRGlobal.OBFSs.Contains(server.OBFS)) { - Logging.Error($"不支持的 SSR 混淆:{server.OBFS}"); + Global.Logger.Error($"不支持的 SSR 混淆:{server.OBFS}"); return false; } diff --git a/Netch/Updater/Updater.cs b/Netch/Updater/Updater.cs index 2c4a0e52..eafea704 100644 --- a/Netch/Updater/Updater.cs +++ b/Netch/Updater/Updater.cs @@ -161,7 +161,7 @@ namespace Netch.Updater } catch { - Logging.Error($"failed to rename file \"{file}\""); + Global.Logger.Error($"failed to rename file \"{file}\""); throw; } } diff --git a/Netch/Utils/Bandwidth.cs b/Netch/Utils/Bandwidth.cs index 1f563258..309cfa3e 100644 --- a/Netch/Utils/Bandwidth.cs +++ b/Netch/Utils/Bandwidth.cs @@ -78,7 +78,7 @@ namespace Netch.Utils var processList = instances.Select(instance => instance.Id).ToList(); - Logging.Info("流量统计进程:" + string.Join(",", instances.Select(instance => $"({instance.Id})" + instance.ProcessName).ToArray())); + Global.Logger.Info("流量统计进程:" + string.Join(",", instances.Select(instance => $"({instance.Id})" + instance.ProcessName).ToArray())); received = 0; diff --git a/Netch/Utils/Configuration.cs b/Netch/Utils/Configuration.cs index 9be0d856..9579fb54 100644 --- a/Netch/Utils/Configuration.cs +++ b/Netch/Utils/Configuration.cs @@ -42,8 +42,8 @@ namespace Netch.Utils } catch (Exception e) { - Logging.Error(e.ToString()); - Utils.Open(Logging.LogFile); + Global.Logger.Error(e.ToString()); + Global.Logger.ShowLog(); Environment.Exit(-1); Global.Settings = null!; } diff --git a/Netch/Utils/Firewall.cs b/Netch/Utils/Firewall.cs index e0870c69..8297e53b 100644 --- a/Netch/Utils/Firewall.cs +++ b/Netch/Utils/Firewall.cs @@ -17,7 +17,7 @@ namespace Netch.Utils { if (!FirewallWAS.IsSupported) { - Logging.Warning("不支持防火墙"); + Global.Logger.Warning("不支持防火墙"); return; } @@ -37,7 +37,7 @@ namespace Netch.Utils } catch (Exception e) { - Logging.Warning("添加防火墙规则错误(如已关闭防火墙则可无视此错误)\n" + e); + Global.Logger.Warning("添加防火墙规则错误(如已关闭防火墙则可无视此错误)\n" + e); } } @@ -57,7 +57,7 @@ namespace Netch.Utils } catch (Exception e) { - Logging.Warning("清除防火墙规则错误\n" + e); + Global.Logger.Warning("清除防火墙规则错误\n" + e); } } diff --git a/Netch/Utils/Logging.cs b/Netch/Utils/Logging.cs deleted file mode 100644 index 883197e3..00000000 --- a/Netch/Utils/Logging.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.IO; -using Netch.Models; - -namespace Netch.Utils -{ - public static class Logging - { - public const string LogFile = "logging\\application.log"; - - private static readonly object FileLock = new(); - - /// - /// 信息 - /// - /// 内容 - public static void Info(string text) - { - Write(text, LogLevel.INFO); - } - - /// - /// 信息 - /// - /// 内容 - public static void Warning(string text) - { - Write(text, LogLevel.WARNING); - } - - /// - /// 错误 - /// - /// 内容 - public static void Error(string text) - { - Write(text, LogLevel.ERROR); - } - - private static void Write(string text, LogLevel logLevel) - { - var contents = $@"[{DateTime.Now}][{logLevel.ToString()}] {text}{Constants.EOF}"; -#if DEBUG - switch (logLevel) - { - case LogLevel.DEBUG: - case LogLevel.INFO: - case LogLevel.WARNING: - Console.Write(contents); - break; - case LogLevel.ERROR: - Console.Error.Write(contents); - break; - default: - throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); - } -#else - lock (FileLock) - File.AppendAllText(LogFile, contents); -#endif - } - - public static void Debug(string s) - { -#if DEBUG - Write(s, LogLevel.DEBUG); -#endif - } - } -} \ No newline at end of file diff --git a/Netch/Utils/ModeHelper.cs b/Netch/Utils/ModeHelper.cs index 8523fe07..22b9072a 100644 --- a/Netch/Utils/ModeHelper.cs +++ b/Netch/Utils/ModeHelper.cs @@ -85,7 +85,7 @@ namespace Netch.Utils } catch (Exception e) { - Logging.Warning($"Load mode \"{file}\" failed: {e.Message}"); + Global.Logger.Warning($"Load mode \"{file}\" failed: {e.Message}"); } } catch @@ -142,7 +142,7 @@ namespace Netch.Utils case 6: return new PcapController(); default: - Logging.Error("未知模式类型"); + Global.Logger.Error("未知模式类型"); throw new MessageException("未知模式类型"); } } diff --git a/Netch/Utils/PortHelper.cs b/Netch/Utils/PortHelper.cs index 89e97f54..0a740a98 100644 --- a/Netch/Utils/PortHelper.cs +++ b/Netch/Utils/PortHelper.cs @@ -24,7 +24,7 @@ namespace Netch.Utils } catch (Exception e) { - Logging.Error("获取保留端口失败: " + e); + Global.Logger.Error("获取保留端口失败: " + e); } } diff --git a/Netch/Utils/ShareLink.cs b/Netch/Utils/ShareLink.cs index 50baca07..8070fa5f 100644 --- a/Netch/Utils/ShareLink.cs +++ b/Netch/Utils/ShareLink.cs @@ -32,17 +32,16 @@ namespace Netch.Utils try { - list.AddRange(JsonSerializer.Deserialize>(text)! - .Select(server => new Shadowsocks - { - Hostname = server.server, - Port = server.server_port, - EncryptMethod = server.method, - Password = server.password, - Remark = server.remarks, - Plugin = server.plugin, - PluginOption = server.plugin_opts - })); + list.AddRange(JsonSerializer.Deserialize>(text)!.Select(server => new Shadowsocks + { + Hostname = server.server, + Port = server.server_port, + EncryptMethod = server.method, + Password = server.password, + Remark = server.remarks, + Plugin = server.plugin, + PluginOption = server.plugin_opts + })); } catch (JsonException) { @@ -56,16 +55,16 @@ namespace Netch.Utils catch (Exception e) { errorFlag = true; - Logging.Error(e.ToString()); + Global.Logger.Error(e.ToString()); } } if (errorFlag) - Utils.Open(Logging.LogFile); + Global.Logger.ShowLog(); } catch (Exception e) { - Logging.Error(e.ToString()); + Global.Logger.Error(e.ToString()); } return list; @@ -90,7 +89,7 @@ namespace Netch.Utils if (util != null) list.AddRange(util.ParseUri(text)); else - Logging.Warning($"无法处理 {scheme} 协议订阅链接"); + Global.Logger.Warning($"无法处理 {scheme} 协议订阅链接"); } foreach (var node in list.Where(node => !node.Remark.IsNullOrWhiteSpace())) diff --git a/Netch/Utils/Subscription.cs b/Netch/Utils/Subscription.cs index 85e2c403..12e4dfbe 100644 --- a/Netch/Utils/Subscription.cs +++ b/Netch/Utils/Subscription.cs @@ -53,7 +53,7 @@ namespace Netch.Utils catch (Exception e) { Global.MainForm.NotifyTip($"{i18N.TranslateFormat("Update servers error from {0}", item.Remark)}\n{e.Message}", info: false); - Logging.Error(e.ToString()); + Global.Logger.Error(e.ToString()); } } } diff --git a/Netch/Utils/Utils.cs b/Netch/Utils/Utils.cs index 2c1fad08..2d4e0f97 100644 --- a/Netch/Utils/Utils.cs +++ b/Netch/Utils/Utils.cs @@ -243,7 +243,7 @@ namespace Netch.Utils } }; - Logging.Debug($"{fileName} {arguments}"); + Global.Logger.Debug($"{fileName} {arguments}"); p.Start(); var output = await p.StandardOutput.ReadToEndAsync(); diff --git a/Netch/Utils/i18N.cs b/Netch/Utils/i18N.cs index 0248a6c8..a9a0d01c 100644 --- a/Netch/Utils/i18N.cs +++ b/Netch/Utils/i18N.cs @@ -41,7 +41,7 @@ namespace Netch.Utils { var oldLangCode = LangCode; LangCode = languages.FirstOrDefault(s => GetLanguage(s).Equals(GetLanguage(LangCode))) ?? "en-US"; - Logging.Info($"找不到语言 {oldLangCode}, 使用 {LangCode}"); + Global.Logger.Info($"找不到语言 {oldLangCode}, 使用 {LangCode}"); } switch (LangCode) @@ -61,7 +61,7 @@ namespace Netch.Utils if (!dictionary.Any()) { - Logging.Error($"{LangCode} 语言文件错误"); + Global.Logger.Error($"{LangCode} 语言文件错误"); return; }