终端一体化运控平台
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

262 líneas
9.7 KiB

  1. using BPASmartClient.CustomResource.UserControls;
  2. using BPASmartClient.CustomResource.UserControls.MessageShow;
  3. using BPASmartClient.Helper;
  4. using BPASmartClient.Model;
  5. using Microsoft.Toolkit.Mvvm.ComponentModel;
  6. using Microsoft.Toolkit.Mvvm.Input;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Collections.ObjectModel;
  10. using System.ComponentModel;
  11. using System.Data;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Text;
  15. using System.Text.RegularExpressions;
  16. using System.Threading.Tasks;
  17. using System.Windows.Media;
  18. namespace BPASmartClient.ViewModel
  19. {
  20. /// <summary>
  21. /// 告警/日志查询界面
  22. /// </summary>
  23. public class LogOrAlarmViewModel : ObservableObject
  24. {
  25. #region 单一变量
  26. private volatile static LogOrAlarmViewModel _Instance;
  27. public static LogOrAlarmViewModel GetInstance() => _Instance ?? (_Instance = new LogOrAlarmViewModel());
  28. private LogOrAlarmViewModel()
  29. {
  30. Init();
  31. }
  32. #endregion
  33. #region 变量
  34. string path = $"{System.AppDomain.CurrentDomain.BaseDirectory}LogDir\\HBL.LogDir2022_5_13.log";
  35. private string _SelectedText = "";
  36. public string SelectedText
  37. {
  38. get
  39. {
  40. return _SelectedText;
  41. }
  42. set
  43. {
  44. if (_SelectedText == value)
  45. return;
  46. _SelectedText = value;
  47. OnPropertyChanged("SelectedText");
  48. }
  49. }
  50. /// <summary>
  51. /// 时间条件
  52. /// </summary>
  53. private DateTime _DateTime;
  54. public DateTime DateTimeStr
  55. {
  56. get
  57. {
  58. return _DateTime;
  59. }
  60. set
  61. {
  62. if (_DateTime == value)
  63. return;
  64. _DateTime = value;
  65. OnPropertyChanged("DateTimeStr");
  66. }
  67. }
  68. public ObservableCollection<BookEx> SelectBookExs { set; get; }
  69. private ObservableCollection<BookEx> _books;
  70. public ObservableCollection<BookEx> BookExs
  71. {
  72. get
  73. {
  74. if (_books == null)
  75. {
  76. _books = new ObservableCollection<BookEx>();
  77. _books.CollectionChanged += (sender, e) =>
  78. {
  79. if (e.OldItems != null)
  80. {
  81. foreach (BookEx bookEx in e.OldItems)
  82. {
  83. bookEx.PropertyChanged -= ItemPropertyChanged;
  84. }
  85. }
  86. if (e.NewItems != null)
  87. {
  88. foreach (BookEx bookEx in e.NewItems)
  89. {
  90. bookEx.PropertyChanged += ItemPropertyChanged;
  91. }
  92. }
  93. };
  94. }
  95. return _books;
  96. }
  97. }
  98. private ObservableCollection<LogModel> _LogModels; public ObservableCollection<LogModel> LogDataGrid
  99. {
  100. get
  101. {
  102. return _LogModels;
  103. }
  104. set
  105. {
  106. if (_LogModels == value)
  107. return;
  108. _LogModels = value;
  109. OnPropertyChanged("LogDataGrid");
  110. }
  111. }
  112. #endregion
  113. #region Command
  114. public RelayCommand QueryCommand { get; set; }
  115. public RelayCommand OpenCommand { get; set; }
  116. #endregion
  117. #region 函数
  118. public void Init()
  119. {
  120. LogDataGrid = new ObservableCollection<LogModel>();
  121. DateTimeStr = DateTime.Now;
  122. BookExs.Add(new BookEx(new Book() { Name = "一般日志条件", Tag = "Info" }) { IsChecked = true });
  123. BookExs.Add(new BookEx(new Book() { Name = "设备日志条件", Tag = "DeviceLog" }) { IsChecked = true });
  124. BookExs.Add(new BookEx(new Book() { Name = "错误日志条件", Tag = "Error" }) { IsChecked = true });
  125. BookExs.Add(new BookEx(new Book() { Name = "设备告警条件", Tag = "DeviceAlarm" }) { IsChecked = true });
  126. SelectBookExs = new ObservableCollection<BookEx>();
  127. ItemPropertyChanged(new BookEx(new Book()) { IsChecked = true },new PropertyChangedEventArgs("IsChecked"));
  128. //查询
  129. QueryCommand = new RelayCommand(() =>
  130. {
  131. string sql = string.Empty;
  132. if (SelectBookExs.Count <= 0)
  133. {
  134. NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance().window, "提示", $"至少选中一个条件!");
  135. return;
  136. }
  137. SelectBookExs?.ToList().ForEach(par =>
  138. {
  139. if (string.IsNullOrEmpty(sql))
  140. sql += $"LOGGER='{par.BookN.Tag}'";
  141. else
  142. sql += $" OR LOGGER='{par.BookN.Tag}'";
  143. });
  144. //1.找到某天的文件
  145. string path = $"{System.AppDomain.CurrentDomain.BaseDirectory}LogDir\\HBL.LogDir{DateTimeStr.ToString("yyyy_M_d")}.log";
  146. if (File.Exists(path))
  147. {
  148. LogDataGrid.Clear();
  149. //2.根据选中查询日志
  150. DataTable dataTable = ReadFile(path);
  151. List<DataRow> datas = dataTable.Select($"({sql})").OrderByDescending(o => o["TIME"])?.ToList();
  152. if (datas==null || datas.Count() <= 0)
  153. {
  154. NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance().window, "提示", $"查询结果为空!");
  155. return;
  156. }
  157. foreach (DataRow item in datas)
  158. {
  159. LogDataGrid.Add(new LogModel
  160. {
  161. time = item["TIME"].ToString(),
  162. type = item["LOGGER"].ToString(),
  163. message = item["MESSAGE"].ToString()
  164. // foreground = (item["LOGGER"].ToString() == "ERROR" || item["LOGGER"].ToString() == "DEVICEALARM") ? new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#ed0032")) : new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#21bb2e"))
  165. });
  166. }
  167. }
  168. else
  169. {
  170. NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance().window, "提示", $"文件不存在,{path}!");
  171. }
  172. });
  173. //打开文件目录
  174. OpenCommand = new RelayCommand(() =>
  175. {
  176. System.Diagnostics.Process.Start("Explorer", "/select," + logHelper.GetLogConfigInstance().directRollfileAppender.File);
  177. logHelper.GetLogConfigInstance().OpenFile(logHelper.GetLogConfigInstance().directRollfileAppender.File);
  178. });
  179. }
  180. /// <summary>
  181. /// 读取文件
  182. /// </summary>
  183. /// <param name="path"></param>
  184. public DataTable ReadFile(string path)
  185. {
  186. DataTable dt = new DataTable();
  187. dt.Columns.AddRange(new[]
  188. {
  189. new DataColumn("TIME"),
  190. new DataColumn("LOGGER"),
  191. new DataColumn("NAME"),
  192. new DataColumn("PRIORITY"),
  193. new DataColumn("MESSAGE"),
  194. });
  195. //读取文件
  196. string s = "";
  197. using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  198. {
  199. using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default))
  200. {
  201. s = sr.ReadToEnd();
  202. }
  203. }
  204. //正则表达式匹配,注意RegexOptions.RightToLeft
  205. var matches = Regex.Matches(s, @"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) ([A-Z, ]{0,15}) ([A-Z,a-z]{0,20}) (\[\d{1}\]) (.*)", RegexOptions.RightToLeft);
  206. foreach (Match m in matches)
  207. {
  208. var time = m.Groups[1].Value;
  209. var logger = m.Groups[2].Value;
  210. var name = m.Groups[3].Value;
  211. var priority = m.Groups[4].Value;
  212. var msg = m.Groups[5].Value;
  213. var dr = dt.NewRow();
  214. dr.ItemArray = new[] { time, logger, name, priority, msg };
  215. dt.Rows.InsertAt(dr, 0);
  216. }
  217. return dt;
  218. }
  219. /// <summary>
  220. /// 选中改变
  221. /// </summary>
  222. /// <param name="sender"></param>
  223. /// <param name="e"></param>
  224. private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
  225. {
  226. if (e.PropertyName == "IsChecked")
  227. {
  228. BookEx bookEx = sender as BookEx;
  229. if (bookEx != null)
  230. {
  231. IEnumerable<BookEx> bookExs = BookExs.Where(b => b.IsChecked == true);
  232. StringBuilder builder = new StringBuilder();
  233. SelectBookExs.Clear();
  234. foreach (BookEx item in bookExs)
  235. {
  236. builder.Append(item.BookN.Name + " ");
  237. SelectBookExs.Add((BookEx)item);
  238. }
  239. SelectedText = builder == null ? string.Empty : builder.ToString();
  240. }
  241. }
  242. }
  243. #endregion
  244. }
  245. }