终端一体化运控平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LogOrAlarmViewModel.cs 10 KiB

1 jaar geleden
1 jaar geleden
4 maanden geleden
2 jaren geleden
2 jaren geleden
1 jaar geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
1 jaar geleden
4 maanden geleden
2 jaren geleden
2 jaren geleden
4 maanden geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
4 maanden geleden
1 jaar geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. using BPASmartClient.CustomResource.UserControls;
  2. using BPASmartClient.CustomResource.UserControls.MessageShow;
  3. using BPA.Helper;
  4. using BPASmartClient.Model;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Collections.ObjectModel;
  8. using System.ComponentModel;
  9. using System.Data;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Text.RegularExpressions;
  14. using System.Threading.Tasks;
  15. using System.Windows.Media;
  16. namespace BPASmartClient.ViewModel
  17. {
  18. /// <summary>
  19. /// 告警/日志查询界面
  20. /// </summary>
  21. public class LogOrAlarmViewModel : NotifyBase
  22. {
  23. #region 单一变量
  24. private volatile static LogOrAlarmViewModel _Instance;
  25. public static LogOrAlarmViewModel GetInstance => _Instance ?? (_Instance = new LogOrAlarmViewModel());
  26. private LogOrAlarmViewModel()
  27. {
  28. Init();
  29. }
  30. #endregion
  31. #region 变量
  32. string path = $"{System.AppDomain.CurrentDomain.BaseDirectory}LogDir\\HBL.LogDir2022_5_13.log";
  33. private string _SelectedText = "";
  34. public string SelectedText
  35. {
  36. get
  37. {
  38. return _SelectedText;
  39. }
  40. set
  41. {
  42. if (_SelectedText == value)
  43. return;
  44. _SelectedText = value;
  45. OnPropertyChanged("SelectedText");
  46. }
  47. }
  48. /// <summary>
  49. /// 时间条件
  50. /// </summary>
  51. private DateTime _DateTime;
  52. public DateTime DateTimeStr
  53. {
  54. get
  55. {
  56. return _DateTime;
  57. }
  58. set
  59. {
  60. if (_DateTime == value)
  61. return;
  62. _DateTime = value;
  63. OnPropertyChanged("DateTimeStr");
  64. }
  65. }
  66. public ObservableCollection<BookEx> SelectBookExs { set; get; }
  67. private ObservableCollection<BookEx> _books;
  68. public ObservableCollection<BookEx> BookExs
  69. {
  70. get
  71. {
  72. if (_books == null)
  73. {
  74. _books = new ObservableCollection<BookEx>();
  75. _books.CollectionChanged += (sender, e) =>
  76. {
  77. if (e.OldItems != null)
  78. {
  79. foreach (BookEx bookEx in e.OldItems)
  80. {
  81. bookEx.PropertyChanged -= ItemPropertyChanged;
  82. }
  83. }
  84. if (e.NewItems != null)
  85. {
  86. foreach (BookEx bookEx in e.NewItems)
  87. {
  88. bookEx.PropertyChanged += ItemPropertyChanged;
  89. }
  90. }
  91. };
  92. }
  93. return _books;
  94. }
  95. }
  96. private ObservableCollection<LogModel> _LogModels; public ObservableCollection<LogModel> LogDataGrid
  97. {
  98. get
  99. {
  100. return _LogModels;
  101. }
  102. set
  103. {
  104. if (_LogModels == value)
  105. return;
  106. _LogModels = value;
  107. OnPropertyChanged("LogDataGrid");
  108. }
  109. }
  110. public string SearchText { get { return _mSearchText; } set { _mSearchText = value; OnPropertyChanged(); } }
  111. private string _mSearchText;
  112. #endregion
  113. #region Command
  114. public BPARelayCommand QueryCommand { get; set; }
  115. public BPARelayCommand 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 BPARelayCommand(() =>
  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. if (SearchText?.Length > 0)
  168. {
  169. var SearchList = LogDataGrid.Where(p => p.message.Contains(SearchText)).ToList();
  170. if (SearchList != null && SearchList.Count > 0)
  171. {
  172. LogDataGrid.Clear();
  173. SearchList.ForEach((item) => { LogDataGrid.Add(item); });
  174. }
  175. }
  176. }
  177. else
  178. {
  179. NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance.window, "提示", $"文件不存在,{path}!");
  180. }
  181. });
  182. //打开文件目录
  183. OpenCommand = new BPARelayCommand(() =>
  184. {
  185. System.Diagnostics.Process.Start("Explorer", "/select," + logHelper.GetLogConfigInstance().directRollfileAppender.File);
  186. logHelper.GetLogConfigInstance().OpenFile(logHelper.GetLogConfigInstance().directRollfileAppender.File);
  187. });
  188. }
  189. /// <summary>
  190. /// 读取文件
  191. /// </summary>
  192. /// <param name="path"></param>
  193. public DataTable ReadFile(string path)
  194. {
  195. DataTable dt = new DataTable();
  196. dt.Columns.AddRange(new[]
  197. {
  198. new DataColumn("TIME"),
  199. new DataColumn("LOGGER"),
  200. new DataColumn("NAME"),
  201. new DataColumn("PRIORITY"),
  202. new DataColumn("MESSAGE"),
  203. });
  204. //读取文件
  205. string s = "";
  206. using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  207. {
  208. using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default))
  209. {
  210. s = sr.ReadToEnd();
  211. }
  212. }
  213. //正则表达式匹配,注意RegexOptions.RightToLeft
  214. 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);
  215. foreach (Match m in matches)
  216. {
  217. var time = m.Groups[1].Value;
  218. var logger = m.Groups[2].Value;
  219. var name = m.Groups[3].Value;
  220. var priority = m.Groups[4].Value;
  221. var msg = m.Groups[5].Value;
  222. var dr = dt.NewRow();
  223. dr.ItemArray = new[] { time, logger, name, priority, msg };
  224. dt.Rows.InsertAt(dr, 0);
  225. }
  226. return dt;
  227. }
  228. /// <summary>
  229. /// 选中改变
  230. /// </summary>
  231. /// <param name="sender"></param>
  232. /// <param name="e"></param>
  233. private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
  234. {
  235. if (e.PropertyName == "IsChecked")
  236. {
  237. BookEx bookEx = sender as BookEx;
  238. if (bookEx != null)
  239. {
  240. IEnumerable<BookEx> bookExs = BookExs.Where(b => b.IsChecked == true);
  241. StringBuilder builder = new StringBuilder();
  242. SelectBookExs.Clear();
  243. foreach (BookEx item in bookExs)
  244. {
  245. builder.Append(item.BookN.Name + " ");
  246. SelectBookExs.Add((BookEx)item);
  247. }
  248. SelectedText = builder == null ? string.Empty : builder.ToString();
  249. }
  250. }
  251. }
  252. #endregion
  253. }
  254. }