终端一体化运控平台
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

277 rindas
10 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. public string SearchText { get { return _mSearchText; } set { _mSearchText = value; OnPropertyChanged(); } }
  113. private string _mSearchText;
  114. #endregion
  115. #region Command
  116. public RelayCommand QueryCommand { get; set; }
  117. public RelayCommand OpenCommand { get; set; }
  118. #endregion
  119. #region 函数
  120. public void Init()
  121. {
  122. LogDataGrid = new ObservableCollection<LogModel>();
  123. DateTimeStr = DateTime.Now;
  124. BookExs.Add(new BookEx(new Book() { Name = "一般日志条件", Tag = "Info" }) { IsChecked = true });
  125. BookExs.Add(new BookEx(new Book() { Name = "设备日志条件", Tag = "DeviceLog" }) { IsChecked = true });
  126. BookExs.Add(new BookEx(new Book() { Name = "错误日志条件", Tag = "Error" }) { IsChecked = true });
  127. BookExs.Add(new BookEx(new Book() { Name = "设备告警条件", Tag = "DeviceAlarm" }) { IsChecked = true });
  128. SelectBookExs = new ObservableCollection<BookEx>();
  129. ItemPropertyChanged(new BookEx(new Book()) { IsChecked = true }, new PropertyChangedEventArgs("IsChecked"));
  130. //查询
  131. QueryCommand = new RelayCommand(() =>
  132. {
  133. string sql = string.Empty;
  134. if (SelectBookExs.Count <= 0)
  135. {
  136. NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance().window, "提示", $"至少选中一个条件!");
  137. return;
  138. }
  139. SelectBookExs?.ToList().ForEach(par =>
  140. {
  141. if (string.IsNullOrEmpty(sql))
  142. sql += $"LOGGER='{par.BookN.Tag}'";
  143. else
  144. sql += $" OR LOGGER='{par.BookN.Tag}'";
  145. });
  146. //1.找到某天的文件
  147. string path = $"{System.AppDomain.CurrentDomain.BaseDirectory}LogDir\\HBL.LogDir{DateTimeStr.ToString("yyyy_M_d")}.log";
  148. if (File.Exists(path))
  149. {
  150. LogDataGrid.Clear();
  151. //2.根据选中查询日志
  152. DataTable dataTable = ReadFile(path);
  153. List<DataRow> datas = dataTable.Select($"({sql})").OrderByDescending(o => o["TIME"])?.ToList();
  154. if (datas == null || datas.Count() <= 0)
  155. {
  156. NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance().window, "提示", $"查询结果为空!");
  157. return;
  158. }
  159. foreach (DataRow item in datas)
  160. {
  161. LogDataGrid.Add(new LogModel
  162. {
  163. time = item["TIME"].ToString(),
  164. type = item["LOGGER"].ToString(),
  165. message = item["MESSAGE"].ToString()
  166. // 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"))
  167. });
  168. }
  169. if (SearchText?.Length > 0)
  170. {
  171. var SearchList = LogDataGrid.Where(p => p.message.Contains(SearchText)).ToList();
  172. if (SearchList != null && SearchList.Count > 0)
  173. {
  174. LogDataGrid.Clear();
  175. SearchList.ForEach((item) => { LogDataGrid.Add(item); });
  176. }
  177. }
  178. }
  179. else
  180. {
  181. NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance().window, "提示", $"文件不存在,{path}!");
  182. }
  183. });
  184. //打开文件目录
  185. OpenCommand = new RelayCommand(() =>
  186. {
  187. System.Diagnostics.Process.Start("Explorer", "/select," + logHelper.GetLogConfigInstance().directRollfileAppender.File);
  188. logHelper.GetLogConfigInstance().OpenFile(logHelper.GetLogConfigInstance().directRollfileAppender.File);
  189. });
  190. }
  191. /// <summary>
  192. /// 读取文件
  193. /// </summary>
  194. /// <param name="path"></param>
  195. public DataTable ReadFile(string path)
  196. {
  197. DataTable dt = new DataTable();
  198. dt.Columns.AddRange(new[]
  199. {
  200. new DataColumn("TIME"),
  201. new DataColumn("LOGGER"),
  202. new DataColumn("NAME"),
  203. new DataColumn("PRIORITY"),
  204. new DataColumn("MESSAGE"),
  205. });
  206. //读取文件
  207. string s = "";
  208. using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  209. {
  210. using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default))
  211. {
  212. s = sr.ReadToEnd();
  213. }
  214. }
  215. //正则表达式匹配,注意RegexOptions.RightToLeft
  216. 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);
  217. foreach (Match m in matches)
  218. {
  219. var time = m.Groups[1].Value;
  220. var logger = m.Groups[2].Value;
  221. var name = m.Groups[3].Value;
  222. var priority = m.Groups[4].Value;
  223. var msg = m.Groups[5].Value;
  224. var dr = dt.NewRow();
  225. dr.ItemArray = new[] { time, logger, name, priority, msg };
  226. dt.Rows.InsertAt(dr, 0);
  227. }
  228. return dt;
  229. }
  230. /// <summary>
  231. /// 选中改变
  232. /// </summary>
  233. /// <param name="sender"></param>
  234. /// <param name="e"></param>
  235. private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
  236. {
  237. if (e.PropertyName == "IsChecked")
  238. {
  239. BookEx bookEx = sender as BookEx;
  240. if (bookEx != null)
  241. {
  242. IEnumerable<BookEx> bookExs = BookExs.Where(b => b.IsChecked == true);
  243. StringBuilder builder = new StringBuilder();
  244. SelectBookExs.Clear();
  245. foreach (BookEx item in bookExs)
  246. {
  247. builder.Append(item.BookN.Name + " ");
  248. SelectBookExs.Add((BookEx)item);
  249. }
  250. SelectedText = builder == null ? string.Empty : builder.ToString();
  251. }
  252. }
  253. }
  254. #endregion
  255. }
  256. }