App.xaml.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. using ivf_tl_Services;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Configuration;
  6. using System.Data;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Windows;
  12. using System.Windows.Threading;
  13. namespace ivf_tl_Operate
  14. {
  15. /// <summary>
  16. /// Interaction logic for App.xaml
  17. /// </summary>
  18. public partial class App : Application
  19. {
  20. private static Mutex instance;
  21. // 当前生效的语言资源字典(运行时由 ChangeLanguage 维护)。用于按引用精确移除旧语言字典,
  22. // 避免历史 bug:盲删最后一个 MergedDictionary 误删 AdaptiveStyles(TouchMinSize)。
  23. private ResourceDictionary _currentLangRd;
  24. public App()
  25. {
  26. Log4netHelper.WriteLog("App构造函数运行");
  27. //首先注册开始和退出事件
  28. this.Startup += new StartupEventHandler(App_Startup);
  29. this.Exit += new ExitEventHandler(App_Exit);
  30. }
  31. protected override void OnStartup(StartupEventArgs e)
  32. {
  33. bool isNotRunning; //互斥体判断
  34. instance = new Mutex(true, "ivf_tl_Operate", out isNotRunning); //同步基元变量
  35. if (!isNotRunning) // 如果不是未运行状态
  36. {
  37. MessageBox.Show("程序已启动 ");
  38. App.Current.Shutdown();
  39. return;
  40. }
  41. base.OnStartup(e);
  42. AppContext.SetSwitch("Switch.System.Windows.Input.Stylus.EnablePointerSupport", true);
  43. }
  44. private void App_Exit(object sender, ExitEventArgs e)
  45. {
  46. }
  47. private void App_Startup(object sender, StartupEventArgs e)
  48. {
  49. //UI线程未捕获异常处理事件
  50. this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
  51. //Task线程内未捕获异常处理事件
  52. TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
  53. //非UI线程未捕获异常处理事件
  54. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
  55. // M5-02-5:启动时一次性凭据迁移(明文 passWord/engineerPwd → 密文,幂等)。须先于读取凭据。
  56. ivf_tl_Operate.Helpers.AppConfigHelper.MigratePlaintextCredentials();
  57. // M8-P3b:操作日志组件启动初始化(一次)。project=operate,Kafka 从 App.config kfkaIP+kfkaPort。
  58. InitOperationLog();
  59. // M8 点击层:注册全局按钮点击拦截,把每次点击记成 module="界面点击" 的操作日志(导航/点击轨迹)。
  60. // 开发阶段全量记录便于排障;上线用 §10 配置关模块「界面点击」即可。
  61. Helpers.ClickTrailLogger.Install();
  62. ChangeLanguage(ConfigurationManager.AppSettings["Language"].ToString());
  63. }
  64. /// <summary>
  65. /// M8-P3b:初始化操作日志组件。Kafka 地址取 App.config 的 kfkaIP/kfkaPort;topic=tl-oplog。
  66. /// 全 try 兜底:日志初始化失败绝不影响业务启动。
  67. /// </summary>
  68. private void InitOperationLog()
  69. {
  70. try
  71. {
  72. string kafkaIp = ConfigurationManager.AppSettings["kfkaIP"]?.ToString() ?? "127.0.0.1";
  73. string kafkaPort = ConfigurationManager.AppSettings["kfkaPort"]?.ToString() ?? "9092";
  74. Aivfo.OperationLog.OperationLogger.Init(o =>
  75. {
  76. o.Project = "operate";
  77. o.KafkaBootstrapServers = $"{kafkaIp}:{kafkaPort}";
  78. o.Topic = "tl-oplog";
  79. // M8 §10 配置热生效:改本程序 exe 同目录的 oplog-config.json 即可按模块开关日志(≤15s 生效,免重启)。
  80. // 跟项目走、随 exe 部署(源文件在项目根 oplog-config.json);文件不存在=全开(开发默认)。
  81. o.ConfigFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "oplog-config.json");
  82. });
  83. Log4netHelper.WriteLog($"[M8-P3b]操作日志组件已初始化 kafka={kafkaIp}:{kafkaPort} topic=tl-oplog");
  84. }
  85. catch (Exception ex)
  86. {
  87. // 兜底:组件本身也兜底,这里再保一层,绝不因日志初始化影响启动。
  88. try { Log4netHelper.WriteLog($"[M8-P3b]操作日志组件初始化失败(已忽略):{ex.Message}"); } catch { }
  89. }
  90. }
  91. /// <summary>
  92. /// 非UI线程未捕获异常处理事件
  93. /// </summary>
  94. /// <param name="sender"></param>
  95. /// <param name="e"></param>
  96. /// <exception cref="NotImplementedException"></exception>
  97. private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  98. {
  99. try
  100. {
  101. if (e.IsTerminating)
  102. {
  103. Log4netHelper.WriteLog($"非UI线程发生致命错误,程序即将终止");
  104. }
  105. if (e.ExceptionObject is Exception ex)
  106. {
  107. if (ex.InnerException != null)
  108. {
  109. Log4netHelper.WriteLog($"非UI线程异常详细:{ex.InnerException.Message}{ex.InnerException.StackTrace}");
  110. }
  111. Log4netHelper.WriteLog($"非UI线程异常:{ex.Message}{ex.StackTrace}");
  112. }
  113. else
  114. {
  115. Log4netHelper.WriteLog($"非UI线程异常:异常对象类型不是Exception");
  116. }
  117. }
  118. catch (Exception exx)
  119. {
  120. if (exx.InnerException != null)
  121. {
  122. Log4netHelper.WriteLog($"捕获非UI线程异常时发生异常详细:{exx.InnerException.Message}{exx.InnerException.StackTrace}");
  123. }
  124. Log4netHelper.WriteLog($"捕获非UI线程异常时发生异常:{exx.Message}{exx.StackTrace}");
  125. }
  126. }
  127. /// <summary>
  128. /// Task线程内未捕获异常处理事件
  129. /// </summary>
  130. /// <param name="sender"></param>
  131. /// <param name="e"></param>
  132. /// <exception cref="NotImplementedException"></exception>
  133. private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
  134. {
  135. try
  136. {
  137. if (e.Exception.InnerException != null)
  138. {
  139. Log4netHelper.WriteLog($"Task线程异常详细:{e.Exception.InnerException.Message}{e.Exception.InnerException.StackTrace}");
  140. }
  141. Log4netHelper.WriteLog($"Task线程异常:{e.Exception.Message}{e.Exception.StackTrace}");
  142. e.SetObserved();//设置该异常已察觉(这样处理后就不会引起程序崩溃)
  143. }
  144. catch (Exception ex)
  145. {
  146. if (ex.InnerException != null)
  147. {
  148. Log4netHelper.WriteLog($"捕获Task线程异常时发生异常详细:{ex.InnerException.Message}{ex.InnerException.StackTrace}");
  149. }
  150. Log4netHelper.WriteLog($"捕获Task线程异常时发生异常:{ex.Message}{ex.StackTrace}");
  151. }
  152. finally
  153. {
  154. e.SetObserved();//设置该异常已察觉(这样处理后就不会引起程序崩溃)
  155. }
  156. }
  157. /// <summary>
  158. /// UI线程未捕获异常处理事件
  159. /// </summary>
  160. /// <param name="sender"></param>
  161. /// <param name="e"></param>
  162. /// <exception cref="NotImplementedException"></exception>
  163. // === 日志洪流抑制(防 8GB 复发)===
  164. // WPF 布局类异常被下面 e.Handled=true 吞掉后,WPF 会逐帧重新测量→同一异常每帧重抛。
  165. // 无节流时同一条异常每秒上千次、每条带完整堆栈(~4.7KB),曾致单日日志涨到 8GB。
  166. // 此处按异常签名节流:同签名 10s 内只放行一条,下次放行时补记期间被抑制的条数。
  167. private static readonly object _logThrottleLock = new object();
  168. private static readonly Dictionary<string, long[]> _logThrottle = new Dictionary<string, long[]>(); // signature -> [lastTicks, suppressedCount]
  169. private static readonly long _logThrottleWindowTicks = TimeSpan.FromSeconds(10).Ticks;
  170. /// <summary>
  171. /// 节流判定:同 <paramref name="signature"/> 在窗口期(10s)内只放行一次。
  172. /// 返回 true=应记录(<paramref name="suppressNote"/> 含上一窗口被抑制的条数提示);false=抑制本条。线程安全。
  173. /// </summary>
  174. private static bool ShouldLogThrottled(string signature, out string suppressNote)
  175. {
  176. suppressNote = string.Empty;
  177. long now = DateTime.Now.Ticks;
  178. lock (_logThrottleLock)
  179. {
  180. if (_logThrottle.TryGetValue(signature, out long[] st))
  181. {
  182. if (now - st[0] < _logThrottleWindowTicks)
  183. {
  184. st[1]++; // 仍在窗口内:累计被抑制条数,不记录
  185. return false;
  186. }
  187. if (st[1] > 0) suppressNote = $"(前 10s 抑制 {st[1]} 条相同异常)";
  188. st[0] = now;
  189. st[1] = 0;
  190. return true;
  191. }
  192. _logThrottle[signature] = new long[] { now, 0 };
  193. return true;
  194. }
  195. }
  196. private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
  197. {
  198. try
  199. {
  200. // 按异常消息节流(布局类异常被吞后会逐帧重抛,见上方说明)。
  201. if (ShouldLogThrottled("UI:" + (e.Exception?.Message ?? "null"), out string note))
  202. {
  203. if (e.Exception.InnerException != null)
  204. {
  205. Log4netHelper.WriteLog($"UI线程异常详细:{e.Exception.InnerException.Message}{e.Exception.InnerException.StackTrace}");
  206. }
  207. Log4netHelper.WriteLog($"UI线程异常{note}:{e.Exception.Message}{e.Exception.StackTrace}");
  208. }
  209. //把 Handled 属性设为true,表示此异常已处理,程序可以继续运行,不会强制退出
  210. }
  211. catch (Exception ex)
  212. {
  213. //此时程序出现严重异常,将强制结束退出
  214. if (ex.InnerException != null)
  215. {
  216. Log4netHelper.WriteLog($"捕获UI线程异常时发生异常详细:{ex.InnerException.Message}{ex.InnerException.StackTrace}");
  217. }
  218. Log4netHelper.WriteLog($"捕获UI线程异常时发生异常:{ex.Message}{ex.StackTrace}");
  219. }
  220. finally
  221. {
  222. e.Handled = true;
  223. }
  224. }
  225. public void ChangeLanguage(string languageName)
  226. {
  227. try
  228. {
  229. ResourceDictionary langRd = null;
  230. #if DEBUG
  231. string xamlFilePath = @"C:\PersonalSpace\work\1 VisualWorkSpace\SurfaceLan\" + languageName;
  232. #else
  233. string xamlFilePath = $"{System.AppDomain.CurrentDomain.BaseDirectory}Resources\\Language\\{languageName}";
  234. #endif
  235. if (!File.Exists(xamlFilePath))
  236. {
  237. Log4netHelper.WriteLog($"切换语言失败,配置文件不存在:{xamlFilePath}");
  238. return;
  239. }
  240. using (var stream = new FileStream(xamlFilePath, FileMode.Open))
  241. {
  242. langRd = System.Windows.Markup.XamlReader.Load(stream) as ResourceDictionary;
  243. }
  244. if (langRd != null)
  245. {
  246. var mds = Application.Current.Resources.MergedDictionaries;
  247. // 【8GB 洪流根因修复】原逻辑 RemoveAt(Count-1) 盲删"最后一个"合并字典。
  248. // 但 App.xaml 里最后一个是 AdaptiveStyles.xaml(全局 TouchMinSize 所在,M4-01-4 加在语言字典之后),
  249. // 故启动时本方法实删的是 AdaptiveStyles 而非旧语言字典 → 全局 TouchMinSize 丢失 →
  250. // SoftKeyboard 按键隐式样式 MinHeight={StaticResource TouchMinSize} 解析成 UnsetValue → 每帧抛 → 单日 8GB。
  251. // 改为:按引用移除"上一次语言字典";首次按 Source 含 /Language/ 匹配移除 App.xaml 预置语言字典,绝不碰 AdaptiveStyles。
  252. if (_currentLangRd != null)
  253. {
  254. mds.Remove(_currentLangRd);
  255. }
  256. else
  257. {
  258. for (int i = mds.Count - 1; i >= 0; i--)
  259. {
  260. string src = mds[i].Source?.OriginalString ?? string.Empty;
  261. if (src.IndexOf("/Language/", StringComparison.OrdinalIgnoreCase) >= 0)
  262. {
  263. mds.RemoveAt(i);
  264. break;
  265. }
  266. }
  267. }
  268. mds.Add(langRd);
  269. _currentLangRd = langRd;
  270. }
  271. else
  272. {
  273. Log4netHelper.WriteLog($"切换语言失败,文件转ResourceDictionary失败;{xamlFilePath}");
  274. }
  275. }
  276. catch (Exception ex)
  277. {
  278. Log4netHelper.WriteLog($"切换语言异常,{JsonConvert.SerializeObject(ex)}");
  279. return;
  280. }
  281. }
  282. }
  283. }