diff --git a/TRI_TCP_Client/TRI_TCP_Client/Log/Logger.cs b/TRI_TCP_Client/TRI_TCP_Client/Log/Logger.cs new file mode 100644 index 0000000..e072e39 --- /dev/null +++ b/TRI_TCP_Client/TRI_TCP_Client/Log/Logger.cs @@ -0,0 +1,94 @@ +using System; +using System.IO; +using System.Reflection; +using TRI_TCP_Client.Log; + +namespace TRI_TCP_Client +{ + public class Logger + { + #region Instance + private static object logLock; + + + private static string dataString = DateTime.Now.ToString("yyyyMMdd_HHmm"); + + private static Logger _instance; + + private static string logFileName; + private Logger() { } + + /// + /// Logger instance + /// + public static Logger Instance + { + get + { + if (_instance == null) + { + _instance = new Logger(); + logLock = new object(); + logFileName = "TRI_Log_" + dataString + ".txt"; + } + return _instance; + } + } + #endregion + + /// + /// 写Log + /// + /// Log content + /// information + public void WriteLog(string logContent, LogType logType = LogType.Information, string fileName = null) + { + try + { + string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + basePath = @"D:\Log"; + if (!Directory.Exists(basePath)) + { + Directory.CreateDirectory(basePath); + } + string[] logText = new string[] { DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + " " + logType.ToString() + ": " + logContent }; + if (!string.IsNullOrEmpty(fileName)) + { + fileName = fileName + "_" + logFileName; + } + else + { + fileName = logFileName; + } + + lock (logLock) + { + File.AppendAllLines(basePath + "\\" + fileName, logText); + } + } + catch (Exception) { } + } + + /// + /// Write exception to log file + /// + /// Exception + public void WriteException(Exception exception, string specialText = null) + { + if (exception != null) + { + Type exceptionType = exception.GetType(); + string text = string.Empty; + if (!string.IsNullOrEmpty(specialText)) + { + text = text + specialText + Environment.NewLine; + } + text = "Exception: " + exceptionType.Name + Environment.NewLine; + text += " " + "Message: " + exception.Message + Environment.NewLine; + text += " " + "Source: " + exception.Source + Environment.NewLine; + text += " " + "StackTrace: " + exception.StackTrace + Environment.NewLine; + WriteLog(text, LogType.Error); + } + } + } +}