using HMI.Simple.Util; using System; using System.Data.SQLite; using System.IO; namespace HMI.LogUtil { public class LogHelper { private static string FileName = "log"; private static string createTableSql = @"CREATE TABLE IF NOT EXISTS log ( id INTEGER PRIMARY KEY AUTOINCREMENT, level TEXT NOT NULL, text TEXT NOT NULL, source TEXT, time TIME );"; /// /// 防止多线程创建文件(但是不知道teststand会不会多进程调用) /// private static object fileLock = new object(); private static string GetConnectionStr(string dbFile) { return $"DataSource={dbFile};Version=3;Pooling=False;Max Pool Size=100"; } private static string GetDbFile() { string value = RegUtil.GetLocaltion(); string path = Path.Combine(value, "Config", "LogViewer", $"{FileName}_{DateTime.Now:yyyy-MM-dd}.db"); if (!File.Exists(path)) { CreateDbFile(path); } return path; } private static void CreateDbFile(string dbFile) { lock (fileLock) { if (!File.Exists(dbFile)) { string dir = Path.GetDirectoryName(dbFile); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } SQLiteConnection.CreateFile(dbFile); using (SQLiteConnection conn = new SQLiteConnection()) using (SQLiteCommand cmd = new SQLiteCommand(conn)) { conn.ConnectionString = GetConnectionStr(dbFile); conn.Open(); cmd.CommandText = createTableSql; cmd.ExecuteNonQuery(); } } } } private static bool DoLog(string level, string source, string content, out string errMsg) { errMsg = string.Empty; try { string dbFile = GetDbFile(); using (SQLiteConnection conn = new SQLiteConnection()) using (SQLiteCommand cmd = new SQLiteCommand(conn)) { conn.ConnectionString = GetConnectionStr(dbFile); conn.Open(); cmd.CommandText = $@"INSERT INTO log (level, text, source, time) VALUES ('{level}', '{content}', '{source}', '{DateTime.Now:yyyy-MM-dd HH:mm:ss}');"; if (cmd.ExecuteNonQuery() > 0) { return true; } errMsg = "写入日志失败"; return false; } } catch (Exception ex) { errMsg = ex.Message; return false; } } public static bool Debug(string source, string content, out string errMsg) { return DoLog("Debug", source, content, out errMsg); } public static bool Info(string source, string content, out string errMsg) { return DoLog("Info", source, content, out errMsg); } public static bool Warn(string source, string content, out string errMsg) { return DoLog("Warn", source, content, out errMsg); } public static bool Error(string source, string content, out string errMsg) { return DoLog("Error", source, content, out errMsg); } } }