alielie
2025-06-12 c1c3772a11b1f3fbad8846cc714120771d85fa53
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
using HMI.Base;
using HMI.Core.Util;
using HMI.UI.Util;
using log4net.Core;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using static System.Net.Mime.MediaTypeNames;
 
namespace HMI.LogViewer
{
    /// <summary>
    /// UserControl1.xaml 的交互逻辑
    /// </summary>
    public partial class LogViewer : PluginControl
    {
 
        private bool autoRfh;
 
        public bool AutoRfh
        {
            get { return autoRfh; }
            set
            {
                Set(ref autoRfh, value);
                if (autoRfhTimer != null) autoRfhTimer.Enabled = value;
            }
        }
 
        private Timer autoRfhTimer;
 
 
        public LogViewer()
        {
            DataContext = this;
            autoRfhTimer = new Timer
            {
                Enabled = false,
                Interval = 1000,
                AutoReset = false
            };
            autoRfhTimer.Elapsed += AutoRfhTimer_Elapsed;
            InitializeComponent();
        }
 
        public override void InitFinish()
        {
            //base.InitFinish();
            //string baseFile = Path.Combine(logDir, "log.db");
 
            //try
            //{
            //    if (!File.Exists(baseFile))
            //    {
            //        SqliteHelper.CreateDatabase(baseFile);
            //    }
            //    SqliteHelper sqliteHelper = new SqliteHelper(baseFile);
            //    sqliteHelper.ExecuteSql(@"CREATE TABLE IF NOT EXISTS log (
            //        id INTEGER PRIMARY KEY AUTOINCREMENT,
            //        level TEXT NOT NULL,
            //        text TEXT NOT NULL,
            //        source TEXT,
            //        time TIME
            //        );");
            //}
            //catch (Exception ex)
            //{
            //    log.Error("Create Log File Failed.", ex);
            //}
        }
 
 
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            Loaded -= UserControl_Loaded;
        }
 
        private void AutoRfhTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Refresh100items();
        }
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            switch (btn.Name)
            {
                case "queryBtn":
                    QueryLog();
                    break;
                case "resetBtn":
                    QueryReset();
                    break;
                case "exportBtn":
                    break;
                default:
                    break;
            }
        }
 
        private void QueryLog()
        {
            try
            {
                if (startTimeInput.SelectedDateTime == null && endTimeInput.SelectedDateTime == null)
                {
                    ToastHelper.Error(this.lang("log.timeCantBeNull"));
                    return;
                }
 
                if (endTimeInput.SelectedDateTime != null && startTimeInput.SelectedDateTime != null &&
                endTimeInput.SelectedDateTime < startTimeInput.SelectedDateTime)
                {
                    ToastHelper.Error(this.lang("log.timeRangeError"));
                    return;
                }
 
                queryBtn.IsEnabled = false;
                autoRfhInput.IsEnabled = false;
                Filtrate();
            }
            catch (Exception ex)
            {
                log.Error("Log Query Failed.", ex);
                this.Error($"查询失败!{ex.Message}");
            }
            finally
            {
                queryBtn.IsEnabled = true;
                autoRfhInput.IsEnabled = true;
            }
        }
 
        private void QueryReset()
        {
            levelInput.Text = null;
            startTimeInput.SelectedDateTime = null;
            endTimeInput.SelectedDateTime = null;
            startTimeInput.Text = null;
            table.ItemsSource = null;
        }
 
        private void Filtrate()
        {
            string str = LoadSql();
            DataTable dt = new DataTable();
            var files = GetOldDbFiles(PathHelper.LogViewerDir, new DateTime?[] { startTimeInput.SelectedDateTime,
                endTimeInput.SelectedDateTime });
            foreach (string file in files)
            {
                SqliteHelper sql = new SqliteHelper(file);
                dt.Merge(sql.GetDataTable(str));
                sql.Close();
            }
            dt.DefaultView.Sort = "time Desc";
            table.ItemsSource = dt.DefaultView;
        }
 
        public static string[] GetOldDbFiles(string folderPath, DateTime?[] range)
        {
            if (!Directory.Exists(folderPath))
            {
                return new string[0];
            }
            // 获取所有.db文件并筛选出7天前更新的文件
            var oldFiles = Directory.GetFiles(folderPath, "*.db");
            try
            {
                oldFiles = oldFiles.Where(file =>
                {
                    var lastWriteTime = File.GetLastWriteTime(file);
                    bool flag = true;
                    if (range[0] != null) flag &= lastWriteTime >= range[0];
                    if (range[1] != null) flag &= lastWriteTime <= range[1];
                    return flag;
                }).ToArray();
 
                return oldFiles;
            }
            catch (Exception ex)
            {
                return new string[0];
            }
        }
 
        /// <summary>
        /// 加载界面判断数据库语句
        /// </summary>
        /// <returns> str数据库的语句 </returns>
        private string LoadSql()
        {
            string sql = " select level,time,source,text from log";
            List<string> datas = new List<string>();
            if (!string.IsNullOrEmpty(levelInput.Text))
            {
                datas.Add($"level='{levelInput.Text}'");
            }
            if (!string.IsNullOrEmpty(startTimeInput.Text))
            {
                datas.Add($"time>='{startTimeInput.Text}'");
            }
            if (!string.IsNullOrEmpty(endTimeInput.Text))
            {
                datas.Add($"time<='{endTimeInput.Text}'");
            }
            if (!string.IsNullOrEmpty(sourceInput.Text))
            {
                datas.Add($"source='{sourceInput.Text}'");
            }
 
            string condition = string.Join(" AND ", datas);
            condition = string.IsNullOrEmpty(condition) ? string.Empty : $" WHERE {condition}";
 
            sql = $"{sql}{condition} order by time desc";
            return sql;
        }
 
        /// <summary>
        /// 刷新100条数据
        /// </summary>
        private void Refresh100items()
        {
            try
            {
                autoRfhTimer.Enabled = false;
                string todayLogFile = Path.Combine(PathHelper.LogViewerDir, $"log_{DateTime.Today:yyyy-MM-dd}.db");
                if (!File.Exists(todayLogFile)) return;
                string str = "select level,time,source,text from log order by time desc limit 100";
                SqliteHelper sql = new SqliteHelper(todayLogFile);
                var dt = sql.GetDataTable(str);
                this.Dispatcher.BeginInvoke((Action)delegate ()
                {
                    table.ItemsSource = dt.DefaultView;
                });
            }
            catch (Exception ex)
            {
                log.Error("Log Auto Refresh Failed.", ex);
                this.Error($"自动刷新失败!{ex.Message}");
            }
            finally
            {
                autoRfhTimer.Enabled = AutoRfh;
            }
        }
    }
}