alielie
2025-03-23 40014e6e41f1ec017a07b7a620b3c700807d0519
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
using HMI.Base;
using HMI.Core.Util;
using HMI.UI.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
 
namespace HMI.LogViewer
{
    /// <summary>
    /// UserControl1.xaml 的交互逻辑
    /// </summary>
    public partial class LogViewer : PluginControl
    {
        private string logDir;
        private string todayLogFile;
 
        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()
        {
            string logDir = Path.Combine(PathHelper.AppFolder, "Log");
            todayLogFile = Path.Combine(logDir, $"log{DateTime.Now.ToString("yyyy-MM-dd")}.db");
 
            if (!Directory.Exists(logDir))
            {
                Directory.CreateDirectory(logDir);
            }
            this.logDir = logDir;
            DataContext = this;
            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,
                    type 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)
        {
            autoRfhTimer = new Timer
            {
                Enabled = false,
                Interval = 1000
            };
            autoRfhTimer.Elapsed += AutoRfhTimer_Elapsed;
            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
            {
                queryBtn.IsEnabled = false;
                autoRfhInput.IsEnabled = false;
                Filtrate();
                queryBtn.IsEnabled = true;
                autoRfhInput.IsEnabled = true;
            }
            catch (Exception ex)
            {
                log.Error("Log Query Failed.", ex);
                this.Error($"查询失败!{ex.Message}");
            }
        }
 
        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 = Directory.GetFiles(logDir, "*.db");
            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;
        }
 
        /// <summary>
        /// 加载界面判断数据库语句
        /// </summary>
        /// <returns> str数据库的语句 </returns>
        private string LoadSql()
        {
            string sql = " select type,time,source,text from log";
 
            List<string> datas = new List<string>();
            if (!string.IsNullOrEmpty(levelInput.Text))
            {
                datas.Add($"type='{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
            {
                if (!File.Exists(todayLogFile)) return;
                string str = "select type,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}");
            }
        }
    }
}