using System; using System.Text; using System.IO; namespace YOLODetectProcessLib { /// /// 日志类 /// public class LogHelper { private static LogHelper logHelper = new LogHelper(); private static DateTime _starTime; private static string _folder; private static volatile object _logLocker = new object(); private static volatile object _errorLogLocker = new object(); private static volatile object _warnLogLocker = new object(); private static volatile object _infoLogLocker = new object(); private static string _errorLogFileName = string.Empty; private static string _warnLogFileName = string.Empty; private static string _infoLogFileName = string.Empty; private LogHelper() { #if ENABLE_AI_LOGS _folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AILogs"); if (!Directory.Exists(_folder)) { Directory.CreateDirectory(_folder); } #endif } /// /// info /// /// /// public static void InfoLog(params string[] msgs) { Log(EnumLogType.InfoLog, msgs); } /// /// warn /// /// /// public static void WarnLog(string msg, string stackTrace) { Log(EnumLogType.WarnLog, msg, stackTrace); } /// /// error /// /// /// public static void ErrorLog(params string[] msgs) { Log(EnumLogType.ErrorLog, msgs); } /// /// fatal /// /// /// public static void FatalLog(string msg, string stackTrace) { Log(EnumLogType.FatalLog, msg, stackTrace); } /// /// 记录 /// /// /// private static void Log(EnumLogType ltype, params string[] logs) { #if ENABLE_AI_LOGS DateTime currentTime = DateTime.Now; if ((currentTime - _starTime).TotalDays >= 1) { lock (_errorLogLocker) { _errorLogFileName = _folder + "\\" + currentTime.ToString("yyyyMMdd") + "_error.log"; } lock (_warnLogLocker) { _warnLogFileName = _folder + "\\" + currentTime.ToString("yyyyMMdd") + "_warn.log"; } lock (_infoLogLocker) { _infoLogFileName = _folder + "\\" + currentTime.ToString("yyyyMMdd") + "_info.log"; } _starTime = currentTime; } string msg = DateTime.Now.ToString("yyyyMMdd_hhmmss_fffff ") + string.Join("\n", logs); switch (ltype) { case EnumLogType.InfoLog: lock (_infoLogLocker) { WriteLog(_infoLogFileName, msg); } break; case EnumLogType.WarnLog: lock (_infoLogLocker) { WriteLog(_warnLogFileName, msg); } break; case EnumLogType.ErrorLog: lock (_infoLogLocker) { WriteLog(_errorLogFileName, msg); } break; case EnumLogType.FatalLog: lock (_infoLogLocker) { WriteLog(_errorLogFileName, msg); } break; } #endif } private static void WriteLog(string fileName, string msg) { StreamWriter sw = new StreamWriter(fileName, true, Encoding.Default); sw.WriteLine(msg); sw.Flush(); sw.Close(); } } }