终端一体化运控平台
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.
 
 
 

272 lines
9.9 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="time"></param>
  184. /// <param name="info"></param>
  185. public void QueryLogOrAlarm(DateTime time, string info)
  186. {
  187. }
  188. /// <summary>
  189. /// 读取文件
  190. /// </summary>
  191. /// <param name="path"></param>
  192. public DataTable ReadFile(string path)
  193. {
  194. DataTable dt = new DataTable();
  195. dt.Columns.AddRange(new[]
  196. {
  197. new DataColumn("TIME"),
  198. new DataColumn("LOGGER"),
  199. new DataColumn("NAME"),
  200. new DataColumn("PRIORITY"),
  201. new DataColumn("MESSAGE"),
  202. });
  203. //读取文件
  204. string s = "";
  205. using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  206. {
  207. using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default))
  208. {
  209. s = sr.ReadToEnd();
  210. }
  211. }
  212. //正则表达式匹配,注意RegexOptions.RightToLeft
  213. 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);
  214. foreach (Match m in matches)
  215. {
  216. var time = m.Groups[1].Value;
  217. var logger = m.Groups[2].Value;
  218. var name = m.Groups[3].Value;
  219. var priority = m.Groups[4].Value;
  220. var msg = m.Groups[5].Value;
  221. var dr = dt.NewRow();
  222. dr.ItemArray = new[] { time, logger, name, priority, msg };
  223. dt.Rows.InsertAt(dr, 0);
  224. }
  225. return dt;
  226. }
  227. /// <summary>
  228. /// 选中改变
  229. /// </summary>
  230. /// <param name="sender"></param>
  231. /// <param name="e"></param>
  232. private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
  233. {
  234. if (e.PropertyName == "IsChecked")
  235. {
  236. BookEx bookEx = sender as BookEx;
  237. if (bookEx != null)
  238. {
  239. IEnumerable<BookEx> bookExs = BookExs.Where(b => b.IsChecked == true);
  240. StringBuilder builder = new StringBuilder();
  241. SelectBookExs.Clear();
  242. foreach (BookEx item in bookExs)
  243. {
  244. builder.Append(item.BookN.Name + " ");
  245. SelectBookExs.Add((BookEx)item);
  246. }
  247. SelectedText = builder == null ? string.Empty : builder.ToString();
  248. }
  249. }
  250. }
  251. #endregion
  252. }
  253. }