using HMI.Core.Api;
|
using HMI.Core.Util;
|
using log4net;
|
using System;
|
using System.IO;
|
|
namespace WPFProject.Utils
|
{
|
class CommonLogger : ILogWriter
|
{
|
private static ILog log = LogManager.GetLogger("CommonLogger");
|
private SqliteHelper sqliteHelper;
|
private DateTime currentDate;
|
|
public CommonLogger()
|
{
|
RefreshConnection();
|
}
|
|
private SqliteHelper InitHelper(DateTime date)
|
{
|
string file = Path.Combine(PathHelper.LogViewerDir, $"log_{date.ToString("yyyy-MM-dd")}.db");
|
if (!File.Exists(file))
|
{
|
SqliteHelper.CreateDatabase(file);
|
}
|
var sqliteHelper = new SqliteHelper(file);
|
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
|
);");
|
return sqliteHelper;
|
}
|
|
private void RefreshConnection()
|
{
|
if (sqliteHelper == null)
|
{
|
currentDate = DateTime.Today;
|
sqliteHelper = InitHelper(currentDate);
|
return;
|
}
|
else
|
{
|
lock (this)
|
{
|
try
|
{
|
var current = DateTime.Today;
|
if (current == currentDate) return;
|
sqliteHelper?.Close();
|
sqliteHelper = null;
|
currentDate = current;
|
sqliteHelper = InitHelper(currentDate);
|
}
|
catch (Exception ex)
|
{
|
log.Error("RefreshConnection Failed.", ex);
|
sqliteHelper = null;
|
}
|
}
|
}
|
}
|
|
public void Debug(string source, string content)
|
{
|
DoLog("Debug", source, content);
|
}
|
|
public void Info(string source, string content)
|
{
|
DoLog("Info", source, content);
|
}
|
public void Warn(string source, string content)
|
{
|
DoLog("Warn", source, content);
|
}
|
|
public void Error(string source, string content)
|
{
|
DoLog("Error", source, content);
|
}
|
|
private void DoLog(string level, string source, string content)
|
{
|
if (currentDate != DateTime.Today || sqliteHelper == null)
|
{
|
RefreshConnection();
|
}
|
if (sqliteHelper == null)
|
{
|
log.Warn($"Level:{level} Source:{source} {content}");
|
}
|
else
|
{
|
sqliteHelper.ExecuteSql($"INSERT INTO log (level, text, source, time) VALUES ('{level}', '{content}', '{source}', '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}');");
|
}
|
}
|
}
|
}
|