using System; using System.IO; using System.Threading.Tasks; namespace Edu.Common.Plugin { /// /// 日志帮助类 /// public class LogHelper { private static readonly string logDir = Config.LogPath; private static readonly string infoLogDir = Config.InofLogPath; private static readonly string requestLogDir = Config.RequestLogPath; private static readonly object objError = new object(); private static readonly object objInfo = new object(); private static readonly object objRequest = new object(); /// /// 构造函数 /// static LogHelper() { if (!Directory.Exists(logDir)) Directory.CreateDirectory(logDir); if (!Directory.Exists(infoLogDir)) Directory.CreateDirectory(infoLogDir); if (!Directory.Exists(requestLogDir)) Directory.CreateDirectory(requestLogDir); } /// /// 写日志(异常日志) /// /// 异常内容 public static void Write(Exception ex) { Write(ex, ""); } /// /// 写日志(异常日志) /// /// 信息 public static void Write(string msg) { Write(null, msg); } /// /// 写日志(异常日志) /// /// 异常信息 /// 其他信息 public static void Write(Exception exception, string otherMsg) { Task.Run(() => WriteLog(exception, otherMsg, LogEnum.Error)); } /// /// 打印信息(记录信息) /// /// 信息 public static void WriteInfo(string msg) { Task.Run(() => WriteLog(null, msg, LogEnum.Info)); } /// /// 写日志 /// /// 异常信息 /// 其他信息 /// 日志类型 private static void WriteLog(Exception exception, string otherMsg, LogEnum logType) { string str = ""; try { str += string.Format(@" DateTime:{0}", DateTime.Now.ToString()); if (exception != null) { if (exception.InnerException != null) { exception = exception.InnerException; } str += string.Format(@" Message:{0} StackTrace: {1} Source:{2} " , exception.Message , exception.StackTrace , exception.Source ); } str += string.Format(@" ExtMessage:{0}", otherMsg); string filePath = ""; object lockObj = new object(); switch (logType) { case LogEnum.Error: filePath = Path.Combine(logDir, DateTime.Now.ToString("yyyyMMdd") + ".txt"); lockObj = objError; break; case LogEnum.Info: filePath = Path.Combine(infoLogDir, DateTime.Now.ToString("yyyyMMdd") + ".txt"); lockObj = objInfo; break; case LogEnum.Request: filePath = Path.Combine(requestLogDir, DateTime.Now.ToString("yyyyMMdd") + ".txt"); lockObj = objRequest; break; } lock (lockObj) { StreamWriter sw = new StreamWriter(filePath, true); sw.WriteLine(str); sw.Close(); } } catch { } } } /// /// 日志枚举 /// public enum LogEnum { /// /// 错误日志 /// Error = 1, /// /// 信息记录 /// Info = 2, /// /// 接口请求 /// Request = 3 } }