using System; using System.IO; using System.Reflection; namespace Monitor.LogService { public enum LogType { Information, Debug, Run, Failure, Warning, Error } public class Log { #region 实例化 /// /// log文件锁 /// private static object logLock; /// /// Log实例 /// private static Log logInstance; /// /// 日志文件名 /// private static string logFileName; private Log() { } /// /// Log实例 /// public static Log LogInstance { get { if (logInstance == null) { logInstance = new Log(); logLock = new object(); logFileName = Guid.NewGuid() + ".log"; } return logInstance; } } #endregion /// /// 写日志到日志文件 /// /// Log内容 /// Log类型 public void WriteLog(string logContent, LogType logType = LogType.Information, string fileName = null) { try { string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); basePath = @"D:\TruckSwappingLog\"; if (!Directory.Exists(basePath)) { Directory.CreateDirectory(basePath); } string strData = DateTime.Now.ToString("yyyy-MM-dd"); if (!Directory.Exists(basePath + strData)) { Directory.CreateDirectory(basePath + strData); } string[] logText = new string[] { DateTime.Now.ToString("HH:mm:ss.fff") + ": " + logType.ToString() + ": " + logContent }; if (!string.IsNullOrEmpty(fileName)) { fileName = fileName + "_" + DateTime.Now.Hour.ToString(); } else { fileName = logFileName; } lock (logLock) { File.AppendAllLines(basePath + strData + "\\" + fileName + ".log", logText); } } catch (Exception) { } } /// /// 写异常日志到文件中 /// /// 异常类型 public void WriteExceptionInfo(Exception exception, string specText = null) { if (exception != null) { Type exceptionType = exception.GetType(); string text = string.Empty; if (!string.IsNullOrEmpty(specText)) { text = text + specText + 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); } } } }