From 7493f07da98918a8a20984767c01c6b38c4c0bf1 Mon Sep 17 00:00:00 2001 From: ChsBuffer <33744752+chsbuffer@users.noreply.github.com> Date: Sat, 29 May 2021 19:54:44 +0800 Subject: [PATCH] Migrate to Serilog --- Netch/Constants.cs | 2 + Netch/Controllers/Guard.cs | 11 +++--- Netch/Controllers/MainController.cs | 9 ++--- Netch/Controllers/NFController.cs | 17 +++++---- Netch/Controllers/NTTController.cs | 5 ++- Netch/Controllers/TUNController.cs | 11 +++--- Netch/Controllers/UpdateChecker.cs | 14 +++---- Netch/Forms/MainForm.Designer.cs | 22 +++++------ Netch/Forms/MainForm.cs | 10 ++--- Netch/Forms/MainForm.resx | 12 ++++++ Netch/Forms/SettingForm.cs | 3 +- Netch/Global.cs | 9 ----- Netch/Interfaces/ILogger.cs | 11 ------ Netch/Interops/AioDNS.cs | 3 +- Netch/Interops/Redirector.cs | 3 +- Netch/Interops/tun2socks.cs | 5 ++- Netch/Models/LogLevel.cs | 3 +- Netch/Models/Loggers/ConsoleLogger.cs | 54 --------------------------- Netch/Models/Loggers/FileLogger.cs | 48 ------------------------ Netch/Netch.cs | 37 +++++++++++++++--- Netch/Netch.csproj | 6 +++ Netch/Servers/Shadowsocks/SSUtil.cs | 25 ++++++------- Netch/Servers/ShadowsocksR/SSRUtil.cs | 7 ++-- Netch/Services/Updater.cs | 5 ++- Netch/Utils/Bandwidth.cs | 3 +- Netch/Utils/Configuration.cs | 4 +- Netch/Utils/Firewall.cs | 7 ++-- Netch/Utils/ModeHelper.cs | 5 ++- Netch/Utils/PortHelper.cs | 3 +- Netch/Utils/RouteUtils.cs | 5 ++- Netch/Utils/ShareLink.cs | 12 ++---- Netch/Utils/Subscription.cs | 3 +- Netch/Utils/Utils.cs | 11 +++--- Netch/Utils/i18N.cs | 5 ++- 34 files changed, 162 insertions(+), 228 deletions(-) delete mode 100644 Netch/Interfaces/ILogger.cs delete mode 100644 Netch/Models/Loggers/ConsoleLogger.cs delete mode 100644 Netch/Models/Loggers/FileLogger.cs diff --git a/Netch/Constants.cs b/Netch/Constants.cs index 1eae118e..fbff7201 100644 --- a/Netch/Constants.cs +++ b/Netch/Constants.cs @@ -3,6 +3,8 @@ public static class Constants { public const string EOF = "\r\n"; + public const string OutputTemplate = @"[{Timestamp:yyyy-MM-dd HH:mm:ss}][{Level}] {Message:lj}{NewLine}{Exception}"; + public const string LogFile = "logging\\application.log"; public static class Parameter { diff --git a/Netch/Controllers/Guard.cs b/Netch/Controllers/Guard.cs index 349bc649..472dd27a 100644 --- a/Netch/Controllers/Guard.cs +++ b/Netch/Controllers/Guard.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; +using Serilog; using Timer = System.Timers.Timer; namespace Netch.Controllers @@ -84,7 +85,7 @@ namespace Netch.Controllers } catch (Win32Exception e) { - Global.Logger.Error($"停止 {MainFile} 错误:\n" + e); + Log.Error(e, "停止 {MainFile} 异常", MainFile); } catch { @@ -199,13 +200,13 @@ namespace Netch.Controllers _logStreamWriter!.WriteLine(line); } - private readonly object LogStreamLock = new(); + private readonly object _logStreamLock = new(); private void CloseLogFile() { if (!RedirectToFile) return; - lock (LogStreamLock) + lock (_logStreamLock) { if (_logFileStream == null) return; @@ -273,9 +274,9 @@ namespace Netch.Controllers { _logStreamWriter!.Flush(); } - catch (Exception exception) + catch (Exception ex) { - Global.Logger.Warning($"写入 {Name} 日志错误:\n" + exception.Message); + Log.Warning(ex, "写入 {Name} 日志异常", Name); } } } diff --git a/Netch/Controllers/MainController.cs b/Netch/Controllers/MainController.cs index 6a28f0d1..26f6de35 100644 --- a/Netch/Controllers/MainController.cs +++ b/Netch/Controllers/MainController.cs @@ -5,6 +5,7 @@ using Netch.Interfaces; using Netch.Models; using Netch.Servers.Socks5; using Netch.Utils; +using Serilog; namespace Netch.Controllers { @@ -55,7 +56,7 @@ namespace Netch.Controllers public static void Start(Server server, Mode mode) { - Global.Logger.Info($"启动主控制器: {server.Type} [{(int)mode.Type}]{mode.Remark}"); + Log.Information("启动主控制器: {Server} {Mode}", $"{server.Type}", $"[{(int)mode.Type}]{mode.Remark}"); Server = server; Mode = mode; @@ -90,8 +91,7 @@ namespace Netch.Controllers case MessageException: throw; default: - Global.Logger.Error(e.ToString()); - Global.Logger.ShowLog(); + Log.Error(e, "主控制器启动未处理异常"); throw new MessageException($"未处理异常\n{e.Message}"); } } @@ -159,8 +159,7 @@ namespace Netch.Controllers } catch (Exception e) { - Global.Logger.Error(e.ToString()); - Global.Logger.ShowLog(); + Log.Error(e, "主控制器停止未处理异常"); } ModeController = null; diff --git a/Netch/Controllers/NFController.cs b/Netch/Controllers/NFController.cs index 1cc3bca9..8c1eeea1 100644 --- a/Netch/Controllers/NFController.cs +++ b/Netch/Controllers/NFController.cs @@ -9,6 +9,7 @@ using Netch.Models; using Netch.Servers.Shadowsocks; using Netch.Servers.Socks5; using Netch.Utils; +using Serilog; using static Netch.Interops.Redirector; namespace Netch.Controllers @@ -177,8 +178,8 @@ namespace Netch.Controllers var binFileVersion = Utils.Utils.GetFileVersion(BinDriver); var systemFileVersion = Utils.Utils.GetFileVersion(SystemDriver); - Global.Logger.Info("内置驱动版本: " + binFileVersion); - Global.Logger.Info("系统驱动版本: " + systemFileVersion); + Log.Information("内置驱动版本: " + binFileVersion); + Log.Information("系统驱动版本: " + systemFileVersion); if (!File.Exists(SystemDriver)) { @@ -208,7 +209,7 @@ namespace Netch.Controllers if (!reinstall) return; - Global.Logger.Info("更新驱动"); + Log.Information("更新驱动"); UninstallDriver(); InstallDriver(); } @@ -219,7 +220,7 @@ namespace Netch.Controllers /// 驱动是否安装成功 private static void InstallDriver() { - Global.Logger.Info("安装 NF 驱动"); + Log.Information("安装 NF 驱动"); if (!File.Exists(BinDriver)) throw new MessageException(i18N.Translate("builtin driver files missing, can't install NF driver")); @@ -230,7 +231,7 @@ namespace Netch.Controllers } catch (Exception e) { - Global.Logger.Error("驱动复制失败\n" + e); + Log.Error(e,"驱动复制失败\n"); throw new MessageException($"Copy NF driver file failed\n{e.Message}"); } @@ -239,11 +240,11 @@ namespace Netch.Controllers var result = NFAPI.nf_registerDriver("netfilter2"); if (result == NF_STATUS.NF_STATUS_SUCCESS) { - Global.Logger.Info("驱动安装成功"); + Log.Information("驱动安装成功"); } else { - Global.Logger.Error($"注册驱动失败,返回值:{result}"); + Log.Error("注册驱动失败: {Result}",result); throw new MessageException($"Register NF driver failed\n{result}"); } } @@ -254,7 +255,7 @@ namespace Netch.Controllers /// 是否成功卸载 public static bool UninstallDriver() { - Global.Logger.Info("卸载 NF 驱动"); + Log.Information("卸载 NF 驱动"); try { if (NFService.Status == ServiceControllerStatus.Running) diff --git a/Netch/Controllers/NTTController.cs b/Netch/Controllers/NTTController.cs index 91e6be18..4f818d13 100644 --- a/Netch/Controllers/NTTController.cs +++ b/Netch/Controllers/NTTController.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Threading.Tasks; using Netch.Interfaces; using Netch.Utils; +using Serilog; namespace Netch.Controllers { @@ -40,7 +41,7 @@ namespace Netch.Controllers } catch (Exception e) { - Global.Logger.Warning($"写入 {Name} 日志错误:\n" + e.Message); + Log.Warning(e, "写入 {Name} 日志错误", Name); } if (output.IsNullOrWhiteSpace()) @@ -87,7 +88,7 @@ namespace Netch.Controllers } catch (Exception e) { - Global.Logger.Error($"{Name} 控制器出错:\n" + e); + Log.Error(e, "{Name} 控制器启动异常", Name); try { Stop(); diff --git a/Netch/Controllers/TUNController.cs b/Netch/Controllers/TUNController.cs index 72db20bb..8f55efb3 100644 --- a/Netch/Controllers/TUNController.cs +++ b/Netch/Controllers/TUNController.cs @@ -9,6 +9,7 @@ using Netch.Models; using Netch.Servers.Socks5; using Netch.Utils; using Netch.Interops; +using Serilog; using static Netch.Interops.tun2socks; namespace Netch.Controllers @@ -109,7 +110,7 @@ namespace Netch.Controllers private void SetupRouteTable(Mode mode) { Global.MainForm.StatusText(i18N.Translate("Setup Route Table Rule")); - Global.Logger.Info("设置路由规则"); + Log.Information("设置路由规则"); // Server Address if (!IPAddress.IsLoopback(_serverAddresses)) @@ -189,19 +190,19 @@ namespace Netch.Controllers var binHash = Utils.Utils.SHA256CheckSum(binDriver); var sysHash = Utils.Utils.SHA256CheckSum(sysDriver); - Global.Logger.Info("自带 wintun.dll Hash: " + binHash); - Global.Logger.Info("系统 wintun.dll Hash: " + sysHash); + Log.Information("自带 wintun.dll Hash: {Hash}", binHash); + Log.Information("系统 wintun.dll Hash: {Hash}", sysHash); if (binHash == sysHash) return; try { - Global.Logger.Info("Copy wintun.dll to System Directory"); + Log.Information("Copy wintun.dll to System Directory"); File.Copy(binDriver, sysDriver, true); } catch (Exception e) { - Global.Logger.Error(e.ToString()); + Log.Error(e,"复制 wintun.dll 异常"); throw new MessageException($"Failed to copy wintun.dll to system directory: {e.Message}"); } } diff --git a/Netch/Controllers/UpdateChecker.cs b/Netch/Controllers/UpdateChecker.cs index 99b1c926..a10fb1a4 100644 --- a/Netch/Controllers/UpdateChecker.cs +++ b/Netch/Controllers/UpdateChecker.cs @@ -8,6 +8,7 @@ using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; +using Serilog; namespace Netch.Controllers { @@ -47,24 +48,24 @@ namespace Netch.Controllers var releases = JsonSerializer.Deserialize>(json)!; LatestRelease = GetLatestRelease(releases, isPreRelease); - Global.Logger.Info($"Github 最新发布版本: {LatestRelease.tag_name}"); + Log.Information("Github 最新发布版本: {Version}", LatestRelease.tag_name); if (VersionUtil.CompareVersion(LatestRelease.tag_name, Version) > 0) { - Global.Logger.Info("发现新版本"); + Log.Information("发现新版本"); NewVersionFound?.Invoke(null, new EventArgs()); } else { - Global.Logger.Info("目前是最新版本"); + Log.Information("目前是最新版本"); NewVersionNotFound?.Invoke(null, new EventArgs()); } } catch (Exception e) { if (e is WebException) - Global.Logger.Warning($"获取新版本失败: {e.Message}"); + Log.Warning(e, "获取新版本失败"); else - Global.Logger.Warning(e.ToString()); + Log.Error(e, "获取新版本异常"); NewVersionFoundFailed?.Invoke(null, new EventArgs()); } @@ -76,7 +77,6 @@ namespace Netch.Controllers sha256 = string.Empty; var matches = Regex.Matches(LatestRelease.body, @"^\| (?.*) \| (?.*) \|\r?$", RegexOptions.Multiline) - .Cast() .Skip(2); /* Skip(2) @@ -105,7 +105,7 @@ namespace Netch.Controllers return sb.ToString(); } - public static Release GetLatestRelease(IEnumerable releases, bool isPreRelease) + private static Release GetLatestRelease(IEnumerable releases, bool isPreRelease) { if (!isPreRelease) releases = releases.Where(release => !release.prerelease); diff --git a/Netch/Forms/MainForm.Designer.cs b/Netch/Forms/MainForm.Designer.cs index 4395c50e..42a26865 100644 --- a/Netch/Forms/MainForm.Designer.cs +++ b/Netch/Forms/MainForm.Designer.cs @@ -40,10 +40,10 @@ this.UpdateServersFromSubscribeLinksToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.OptionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.OpenDirectoryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.ShowHideConsoleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.CleanDNSCacheToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.UninstallServiceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.removeNetchFirewallRulesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.ShowHideConsoleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.HelpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.CheckForUpdatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.fAQToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); @@ -207,6 +207,13 @@ this.OpenDirectoryToolStripMenuItem.Text = "Open Directory"; this.OpenDirectoryToolStripMenuItem.Click += new System.EventHandler(this.OpenDirectoryToolStripMenuItem_Click); // + // ShowHideConsoleToolStripMenuItem + // + this.ShowHideConsoleToolStripMenuItem.Name = "ShowHideConsoleToolStripMenuItem"; + this.ShowHideConsoleToolStripMenuItem.Size = new System.Drawing.Size(243, 22); + this.ShowHideConsoleToolStripMenuItem.Text = "Show/Hide Console"; + this.ShowHideConsoleToolStripMenuItem.Click += new System.EventHandler(this.ShowHideConsoleToolStripMenuItem_Click); + // // CleanDNSCacheToolStripMenuItem // this.CleanDNSCacheToolStripMenuItem.Name = "CleanDNSCacheToolStripMenuItem"; @@ -228,13 +235,6 @@ this.removeNetchFirewallRulesToolStripMenuItem.Text = "Remove Netch Firewall Rules"; this.removeNetchFirewallRulesToolStripMenuItem.Click += new System.EventHandler(this.RemoveNetchFirewallRulesToolStripMenuItem_Click); // - // ShowHideConsoleToolStripMenuItem - // - this.ShowHideConsoleToolStripMenuItem.Name = "ShowHideConsoleToolStripMenuItem"; - this.ShowHideConsoleToolStripMenuItem.Size = new System.Drawing.Size(243, 22); - this.ShowHideConsoleToolStripMenuItem.Text = "Show/Hide Console"; - this.ShowHideConsoleToolStripMenuItem.Click += new System.EventHandler(this.ShowHideConsoleToolStripMenuItem_Click); - // // HelpToolStripMenuItem // this.HelpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { @@ -609,19 +609,19 @@ this.ExitToolStripButton}); this.NotifyMenu.Name = "NotifyMenu"; this.NotifyMenu.ShowItemToolTips = false; - this.NotifyMenu.Size = new System.Drawing.Size(108, 48); + this.NotifyMenu.Size = new System.Drawing.Size(181, 70); // // ShowMainFormToolStripButton // this.ShowMainFormToolStripButton.Name = "ShowMainFormToolStripButton"; - this.ShowMainFormToolStripButton.Size = new System.Drawing.Size(107, 22); + this.ShowMainFormToolStripButton.Size = new System.Drawing.Size(180, 22); this.ShowMainFormToolStripButton.Text = "Show"; this.ShowMainFormToolStripButton.Click += new System.EventHandler(this.ShowMainFormToolStripButton_Click); // // ExitToolStripButton // this.ExitToolStripButton.Name = "ExitToolStripButton"; - this.ExitToolStripButton.Size = new System.Drawing.Size(107, 22); + this.ExitToolStripButton.Size = new System.Drawing.Size(180, 22); this.ExitToolStripButton.Text = "Exit"; this.ExitToolStripButton.Click += new System.EventHandler(this.ExitToolStripButton_Click); // diff --git a/Netch/Forms/MainForm.cs b/Netch/Forms/MainForm.cs index 23846a5a..48d3c0a5 100644 --- a/Netch/Forms/MainForm.cs +++ b/Netch/Forms/MainForm.cs @@ -17,6 +17,7 @@ using System.Windows.Forms; using Netch.Enums; using Netch.Interfaces; using Netch.Services; +using Serilog; using Vanara.PInvoke; namespace Netch.Forms @@ -295,7 +296,7 @@ namespace Netch.Forms catch (Exception e) { NotifyTip(i18N.Translate("update servers failed") + "\n" + e.Message, info: false); - Global.Logger.Error("更新服务器 失败!" + e); + Log.Error("更新服务器 失败!" + e); } finally { @@ -430,8 +431,7 @@ namespace Netch.Forms { if (exception is not MessageException) { - Global.Logger.Error($"更新失败: {exception}"); - Global.Logger.ShowLog(); + Log.Error(exception, "更新失败"); } NotifyTip(exception.Message, info: false); @@ -1174,7 +1174,7 @@ namespace Netch.Forms if (!IsWaiting()) { _resumeFlag = true; - Global.Logger.Info("操作系统即将挂起,自动停止"); + Log.Information("操作系统即将挂起,自动停止"); ControlButton_Click(null, null); } @@ -1183,7 +1183,7 @@ namespace Netch.Forms if (_resumeFlag) { _resumeFlag = false; - Global.Logger.Info("操作系统即将从挂起状态继续,自动重启"); + Log.Information("操作系统即将从挂起状态继续,自动重启"); ControlButton_Click(null, null); } diff --git a/Netch/Forms/MainForm.resx b/Netch/Forms/MainForm.resx index f298a7be..d7413891 100644 --- a/Netch/Forms/MainForm.resx +++ b/Netch/Forms/MainForm.resx @@ -57,4 +57,16 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 130, 17 + + + 246, 17 + + + 359, 17 + \ No newline at end of file diff --git a/Netch/Forms/SettingForm.cs b/Netch/Forms/SettingForm.cs index 53fdc855..1d65cfab 100644 --- a/Netch/Forms/SettingForm.cs +++ b/Netch/Forms/SettingForm.cs @@ -8,6 +8,7 @@ using System.IO; using System.Linq; using System.Net; using System.Windows.Forms; +using Serilog; namespace Netch.Forms { @@ -63,7 +64,7 @@ namespace Netch.Forms } catch (Exception e) { - Global.Logger.Warning($"Load stun.txt failed: {e.Message}"); + Log.Warning(e,"Load stun.txt failed"); stuns = null; } diff --git a/Netch/Global.cs b/Netch/Global.cs index 32b17ee5..9285b770 100644 --- a/Netch/Global.cs +++ b/Netch/Global.cs @@ -1,7 +1,5 @@ using Netch.Forms; -using Netch.Interfaces; using Netch.Models; -using Netch.Models.Loggers; using System; using System.Collections.Generic; using System.Text.Encodings.Web; @@ -34,15 +32,8 @@ namespace Netch { NetchExecutable = Application.ExecutablePath; NetchDir = Application.StartupPath; -#if DEBUG - Logger = new ConsoleLogger(); -#else - Logger = new FileLogger(); -#endif } - public static ILogger Logger { get; } - /// /// 主窗体的静态实例 /// diff --git a/Netch/Interfaces/ILogger.cs b/Netch/Interfaces/ILogger.cs deleted file mode 100644 index 922b288f..00000000 --- a/Netch/Interfaces/ILogger.cs +++ /dev/null @@ -1,11 +0,0 @@ -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/AioDNS.cs b/Netch/Interops/AioDNS.cs index f4ef5a90..108d35da 100644 --- a/Netch/Interops/AioDNS.cs +++ b/Netch/Interops/AioDNS.cs @@ -1,5 +1,6 @@ using System.Runtime.InteropServices; using System.Text; +using Serilog; namespace Netch.Interops { @@ -9,7 +10,7 @@ namespace Netch.Interops public static bool Dial(NameList name, string value) { - Global.Logger.Debug($"[aiodns] Dial {name}: {value}"); + Log.Debug($"[aiodns] Dial {name}: {value}"); return aiodns_dial(name, Encoding.UTF8.GetBytes(value)); } diff --git a/Netch/Interops/Redirector.cs b/Netch/Interops/Redirector.cs index 985857db..ddbc7f8e 100644 --- a/Netch/Interops/Redirector.cs +++ b/Netch/Interops/Redirector.cs @@ -1,4 +1,5 @@ using System.Runtime.InteropServices; +using Serilog; namespace Netch.Interops { @@ -42,7 +43,7 @@ namespace Netch.Interops public static bool Dial(NameList name, string value) { - Global.Logger.Debug($"[Redirector] Dial {name}: {value}"); + Log.Debug($"[Redirector] Dial {name}: {value}"); return aio_dial(name, value); } diff --git a/Netch/Interops/tun2socks.cs b/Netch/Interops/tun2socks.cs index 5c7e4b1c..d4b61dcd 100644 --- a/Netch/Interops/tun2socks.cs +++ b/Netch/Interops/tun2socks.cs @@ -1,5 +1,6 @@ using System.Runtime.InteropServices; using System.Text; +using Serilog; namespace Netch.Interops { @@ -35,13 +36,13 @@ namespace Netch.Interops public static bool Dial(NameList name, string value) { - Global.Logger.Debug($"[tun2socks] Dial {name}: {value}"); + Log.Debug( $"[tun2socks] Dial {name}: {value}"); return tun_dial(name, Encoding.UTF8.GetBytes(value)); } public static bool Init() { - Global.Logger.Debug($"[tun2socks] init"); + Log.Debug("[tun2socks] init"); return tun_init(); } diff --git a/Netch/Models/LogLevel.cs b/Netch/Models/LogLevel.cs index 8d8e4f8f..760ce5df 100644 --- a/Netch/Models/LogLevel.cs +++ b/Netch/Models/LogLevel.cs @@ -4,7 +4,6 @@ namespace Netch.Models { INFO, WARNING, - ERROR, - DEBUG + ERROR } } \ No newline at end of file diff --git a/Netch/Models/Loggers/ConsoleLogger.cs b/Netch/Models/Loggers/ConsoleLogger.cs deleted file mode 100644 index 6f23a1d7..00000000 --- a/Netch/Models/Loggers/ConsoleLogger.cs +++ /dev/null @@ -1,54 +0,0 @@ -using Netch.Interfaces; -using System; -using Vanara.PInvoke; - -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() - { - User32.ShowWindow(Netch.ConsoleHwnd, ShowWindowCommand.SW_SHOW); - } - } -} \ No newline at end of file diff --git a/Netch/Models/Loggers/FileLogger.cs b/Netch/Models/Loggers/FileLogger.cs deleted file mode 100644 index 7d06c4d8..00000000 --- a/Netch/Models/Loggers/FileLogger.cs +++ /dev/null @@ -1,48 +0,0 @@ -using Netch.Interfaces; -using System; -using System.IO; - -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/Netch.cs b/Netch/Netch.cs index fd23a69f..669c3cd2 100644 --- a/Netch/Netch.cs +++ b/Netch/Netch.cs @@ -9,6 +9,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; +using Serilog; +using Serilog.Events; using Vanara.PInvoke; using static Vanara.PInvoke.Kernel32; @@ -73,6 +75,8 @@ namespace Netch dir.Delete(true); } + CreateLogger(); + // 加载语言 i18N.Load(Global.Settings.Language); @@ -82,12 +86,13 @@ namespace Netch Environment.Exit(2); } - Global.Logger.Info($"版本: {UpdateChecker.Owner}/{UpdateChecker.Repo}@{UpdateChecker.Version}"); - Task.Run(() => { Global.Logger.Info($"主程序 SHA256: {Utils.Utils.SHA256CheckSum(Global.NetchExecutable)}"); }); + Log.Information("版本: {Version}", $"{UpdateChecker.Owner}/{UpdateChecker.Repo}@{UpdateChecker.Version}"); + Task.Run(() => { Log.Information("主程序 SHA256: {Hash}", $"{Utils.Utils.SHA256CheckSum(Global.NetchExecutable)}"); }); // 绑定错误捕获 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.ThreadException += Application_OnException; + Application.ApplicationExit += Application_OnExit; Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); @@ -95,10 +100,32 @@ namespace Netch Application.Run(Global.MainForm); } - public static void Application_OnException(object sender, ThreadExceptionEventArgs e) + public static void CreateLogger() { - Global.Logger.Error(e.Exception.ToString()); - Global.Logger.ShowLog(); + Log.Logger = new LoggerConfiguration() +#if DEBUG + .MinimumLevel.Debug() + .WriteTo.Async(c => c.Debug(outputTemplate: Constants.OutputTemplate)) + .WriteTo.Async(c => c.Console(outputTemplate: Constants.OutputTemplate)) +#else + .MinimumLevel.Information() + .WriteTo.Async(c => c.File(Path.Combine(Global.NetchDir, Constants.LogFile), + outputTemplate: Constants.OutputTemplate, + rollOnFileSizeLimit: false)) +#endif + .MinimumLevel.Override(@"Microsoft", LogEventLevel.Information) + .Enrich.FromLogContext() + .CreateLogger(); + } + + private static void Application_OnException(object sender, ThreadExceptionEventArgs e) + { + Log.Error(e.Exception, "未处理异常"); + } + + private static void Application_OnExit(object? sender, EventArgs eventArgs) + { + Log.CloseAndFlush(); } private static void SingleInstance_ArgumentsReceived(IEnumerable args) diff --git a/Netch/Netch.csproj b/Netch/Netch.csproj index 758c2853..7d71e410 100644 --- a/Netch/Netch.csproj +++ b/Netch/Netch.csproj @@ -44,6 +44,12 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + diff --git a/Netch/Servers/Shadowsocks/SSUtil.cs b/Netch/Servers/Shadowsocks/SSUtil.cs index 3e401428..1fab9d0d 100644 --- a/Netch/Servers/Shadowsocks/SSUtil.cs +++ b/Netch/Servers/Shadowsocks/SSUtil.cs @@ -9,6 +9,7 @@ using Netch.Models; using Netch.Servers.Shadowsocks.Form; using Netch.Servers.Shadowsocks.Models.SSD; using Netch.Utils; +using Serilog; namespace Netch.Servers.Shadowsocks { @@ -65,10 +66,8 @@ namespace Netch.Servers.Shadowsocks var server = (Shadowsocks)s; if (!SSGlobal.EncryptMethods.Contains(server.EncryptMethod)) { - Global.Logger.Error($"不支持的 SS 加密方式:{server.EncryptMethod}"); - { - return false; - } + Log.Warning("不支持的 SS 加密方式:{Method}", server.EncryptMethod); + return false; } return true; @@ -79,17 +78,17 @@ namespace Netch.Servers.Shadowsocks var json = JsonSerializer.Deserialize
(ShareLink.URLSafeBase64Decode(s.Substring(6)))!; return json.servers.Select(server => new Shadowsocks - { - Remark = server.remarks, - Hostname = server.server, - Port = server.port != 0 ? server.port : json.port, - Password = server.password ?? json.password, - EncryptMethod = server.encryption ?? json.encryption, - Plugin = string.IsNullOrEmpty(json.plugin) ? string.IsNullOrEmpty(server.plugin) ? null : server.plugin : json.plugin, - PluginOption = string.IsNullOrEmpty(json.plugin_options) + { + Remark = server.remarks, + Hostname = server.server, + Port = server.port != 0 ? server.port : json.port, + Password = server.password ?? json.password, + EncryptMethod = server.encryption ?? json.encryption, + Plugin = string.IsNullOrEmpty(json.plugin) ? string.IsNullOrEmpty(server.plugin) ? null : server.plugin : json.plugin, + PluginOption = string.IsNullOrEmpty(json.plugin_options) ? string.IsNullOrEmpty(server.plugin_options) ? null : server.plugin_options : json.plugin_options - }) + }) .Where(CheckServer); } diff --git a/Netch/Servers/ShadowsocksR/SSRUtil.cs b/Netch/Servers/ShadowsocksR/SSRUtil.cs index 24ed3d64..677887a9 100644 --- a/Netch/Servers/ShadowsocksR/SSRUtil.cs +++ b/Netch/Servers/ShadowsocksR/SSRUtil.cs @@ -6,6 +6,7 @@ using Netch.Models; using Netch.Servers.Shadowsocks; using Netch.Servers.ShadowsocksR.Form; using Netch.Utils; +using Serilog; namespace Netch.Servers.ShadowsocksR { @@ -146,19 +147,19 @@ namespace Netch.Servers.ShadowsocksR var server = (ShadowsocksR)s; if (!SSRGlobal.EncryptMethods.Contains(server.EncryptMethod)) { - Global.Logger.Error($"不支持的 SSR 加密方式:{server.EncryptMethod}"); + Log.Error("不支持的 SSR 加密方式:{Method}", server.EncryptMethod); return false; } if (!SSRGlobal.Protocols.Contains(server.Protocol)) { - Global.Logger.Error($"不支持的 SSR 协议:{server.Protocol}"); + Log.Error("不支持的 SSR 协议:{Protocol}", server.Protocol); return false; } if (!SSRGlobal.OBFSs.Contains(server.OBFS)) { - Global.Logger.Error($"不支持的 SSR 混淆:{server.OBFS}"); + Log.Error("不支持的 SSR 混淆:{Obfs}", server.OBFS); return false; } diff --git a/Netch/Services/Updater.cs b/Netch/Services/Updater.cs index 4e540751..690ff41a 100644 --- a/Netch/Services/Updater.cs +++ b/Netch/Services/Updater.cs @@ -11,6 +11,7 @@ using Netch.Controllers; using Netch.Models; using Netch.Properties; using Netch.Utils; +using Serilog; namespace Netch.Services { @@ -160,9 +161,9 @@ namespace Netch.Services { File.Move(file, file + ".old"); } - catch + catch(Exception e) { - Global.Logger.Error($"failed to rename file \"{file}\""); + Log.Error(e,"failed to rename file \"{File}\"",file); throw; } } diff --git a/Netch/Utils/Bandwidth.cs b/Netch/Utils/Bandwidth.cs index 5cb2a270..39b79a70 100644 --- a/Netch/Utils/Bandwidth.cs +++ b/Netch/Utils/Bandwidth.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; +using Serilog; namespace Netch.Utils { @@ -78,7 +79,7 @@ namespace Netch.Utils var processList = instances.Select(instance => instance.Id).ToList(); - Global.Logger.Info("流量统计进程:" + string.Join(",", instances.Select(instance => $"({instance.Id})" + instance.ProcessName).ToArray())); + Log.Information("流量统计进程: {Processes}", $"{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 81e312d9..e77c78d7 100644 --- a/Netch/Utils/Configuration.cs +++ b/Netch/Utils/Configuration.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; +using Serilog; namespace Netch.Utils { @@ -42,8 +43,7 @@ namespace Netch.Utils } catch (Exception e) { - Global.Logger.Error(e.ToString()); - Global.Logger.ShowLog(); + Log.Error(e,"加载配置异常"); Environment.Exit(-1); Global.Settings = null!; } diff --git a/Netch/Utils/Firewall.cs b/Netch/Utils/Firewall.cs index 8297e53b..eb5b001d 100644 --- a/Netch/Utils/Firewall.cs +++ b/Netch/Utils/Firewall.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using WindowsFirewallHelper; using WindowsFirewallHelper.FirewallRules; +using Serilog; namespace Netch.Utils { @@ -17,7 +18,7 @@ namespace Netch.Utils { if (!FirewallWAS.IsSupported) { - Global.Logger.Warning("不支持防火墙"); + Log.Warning("不支持防火墙"); return; } @@ -37,7 +38,7 @@ namespace Netch.Utils } catch (Exception e) { - Global.Logger.Warning("添加防火墙规则错误(如已关闭防火墙则可无视此错误)\n" + e); + Log.Warning(e, "添加防火墙规则错误"); } } @@ -57,7 +58,7 @@ namespace Netch.Utils } catch (Exception e) { - Global.Logger.Warning("清除防火墙规则错误\n" + e); + Log.Warning(e, "清除防火墙规则错误"); } } diff --git a/Netch/Utils/ModeHelper.cs b/Netch/Utils/ModeHelper.cs index 04503e08..53481898 100644 --- a/Netch/Utils/ModeHelper.cs +++ b/Netch/Utils/ModeHelper.cs @@ -7,6 +7,7 @@ using Netch.Interfaces; using Netch.Models; using Netch.Servers.Shadowsocks; using Netch.Servers.Socks5; +using Serilog; namespace Netch.Utils { @@ -87,7 +88,7 @@ namespace Netch.Utils } catch (Exception e) { - Global.Logger.Warning($"Load mode \"{file}\" failed: {e.Message}"); + Log.Warning(e, "Load mode \"{FileName}\" failed", file); } } catch @@ -142,7 +143,7 @@ namespace Netch.Utils case ModeType.Pcap2Socks: return new PcapController(); default: - Global.Logger.Error("未知模式类型"); + Log.Error("未知模式类型"); throw new MessageException("未知模式类型"); } } diff --git a/Netch/Utils/PortHelper.cs b/Netch/Utils/PortHelper.cs index 5edd09bf..e62f4401 100644 --- a/Netch/Utils/PortHelper.cs +++ b/Netch/Utils/PortHelper.cs @@ -4,6 +4,7 @@ using System.Diagnostics; using System.Linq; using System.Net.NetworkInformation; using Netch.Models; +using Serilog; using static Vanara.PInvoke.IpHlpApi; using static Vanara.PInvoke.Ws2_32; @@ -24,7 +25,7 @@ namespace Netch.Utils } catch (Exception e) { - Global.Logger.Error("获取保留端口失败: " + e); + Log.Error(e,"获取保留端口错误"); } } diff --git a/Netch/Utils/RouteUtils.cs b/Netch/Utils/RouteUtils.cs index 8917abbb..8bfb9485 100644 --- a/Netch/Utils/RouteUtils.cs +++ b/Netch/Utils/RouteUtils.cs @@ -3,6 +3,7 @@ using System.Diagnostics.CodeAnalysis; using System.Net.Sockets; using Netch.Interops; using Netch.Models; +using Serilog; namespace Netch.Utils { @@ -18,7 +19,7 @@ namespace Netch.Utils { if (!TryParseIPNetwork(rule, out var network, out var cidr)) { - Global.Logger.Warning($"invalid rule {rule}"); + Log.Warning("invalid rule {Rule}", rule); return false; } @@ -40,7 +41,7 @@ namespace Netch.Utils { if (!TryParseIPNetwork(rule, out var network, out var cidr)) { - Global.Logger.Warning($"invalid rule {rule}"); + Log.Warning("invalid rule {Rule}",rule); return false; } diff --git a/Netch/Utils/ShareLink.cs b/Netch/Utils/ShareLink.cs index d76a6e98..9ebac219 100644 --- a/Netch/Utils/ShareLink.cs +++ b/Netch/Utils/ShareLink.cs @@ -7,6 +7,7 @@ using System.IO; using System.Linq; using System.Text; using System.Text.Json; +using Serilog; namespace Netch.Utils { @@ -45,7 +46,6 @@ namespace Netch.Utils } catch (JsonException) { - var errorFlag = false; foreach (var line in text.GetLines()) { try @@ -54,17 +54,13 @@ namespace Netch.Utils } catch (Exception e) { - errorFlag = true; - Global.Logger.Error(e.ToString()); + Log.Error(e, "从分享链接导入服务器异常"); } } - - if (errorFlag) - Global.Logger.ShowLog(); } catch (Exception e) { - Global.Logger.Error(e.ToString()); + Log.Error(e, "从分享链接导入服务器异常"); } return list; @@ -89,7 +85,7 @@ namespace Netch.Utils if (util != null) list.AddRange(util.ParseUri(text)); else - Global.Logger.Warning($"无法处理 {scheme} 协议订阅链接"); + Log.Warning("无法处理 {Scheme} 协议订阅链接", scheme); } foreach (var node in list.Where(node => !node.Remark.IsNullOrWhiteSpace())) diff --git a/Netch/Utils/Subscription.cs b/Netch/Utils/Subscription.cs index 4ebaf52c..d8b137ab 100644 --- a/Netch/Utils/Subscription.cs +++ b/Netch/Utils/Subscription.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; +using Serilog; namespace Netch.Utils { @@ -53,7 +54,7 @@ namespace Netch.Utils catch (Exception e) { Global.MainForm.NotifyTip($"{i18N.TranslateFormat("Update servers error from {0}", item.Remark)}\n{e.Message}", info: false); - Global.Logger.Error(e.ToString()); + Log.Warning(e, "更新服务器失败"); } } } diff --git a/Netch/Utils/Utils.cs b/Netch/Utils/Utils.cs index fb107d6b..f9dd0da5 100644 --- a/Netch/Utils/Utils.cs +++ b/Netch/Utils/Utils.cs @@ -13,13 +13,14 @@ using System.Threading.Tasks; using System.Windows.Forms; using MaxMind.GeoIP2; using Microsoft.Win32.TaskScheduler; +using Serilog; using Task = System.Threading.Tasks.Task; namespace Netch.Utils { public static class Utils { - public static bool Open(string path) + public static void Open(string path) { try { @@ -29,12 +30,10 @@ namespace Netch.Utils Arguments = path, UseShellExecute = true }); - - return true; } - catch + catch (Exception e) { - return false; + Log.Warning(e, "打开 {Uri} 失败", path); } } @@ -246,7 +245,7 @@ namespace Netch.Utils } }; - Global.Logger.Debug($"{fileName} {arguments}"); + Log.Debug($"{fileName} {arguments}"); p.Start(); var output = await p.StandardOutput.ReadToEndAsync(); diff --git a/Netch/Utils/i18N.cs b/Netch/Utils/i18N.cs index 14dea142..6435f72f 100644 --- a/Netch/Utils/i18N.cs +++ b/Netch/Utils/i18N.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Text; using System.Text.Json; using System.Windows.Forms; +using Serilog; namespace Netch.Utils { @@ -41,7 +42,7 @@ namespace Netch.Utils { var oldLangCode = LangCode; LangCode = languages.FirstOrDefault(s => GetLanguage(s).Equals(GetLanguage(LangCode))) ?? "en-US"; - Global.Logger.Info($"找不到语言 {oldLangCode}, 使用 {LangCode}"); + Log.Information("找不到语言 {OldLangCode}, 使用 {LangCode}",oldLangCode,LangCode); } switch (LangCode) @@ -61,7 +62,7 @@ namespace Netch.Utils if (!dictionary.Any()) { - Global.Logger.Error($"{LangCode} 语言文件错误"); + Log.Error("{LangCode} 语言文件错误", LangCode); return; }