C#输出log信息
在写程序的过程中,有时候我们需要添加一些log信息,这个时候,可以采用下面的方法来实现。
public static void WriteLog(string ExtraMsg, Exception e) { string logPath = Environment.CurrentDirectory + "\\Log"; if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } string logFilePath = Path.Combine(logPath, string.Format("{0}.log", DateTime.Now.Date.ToString("yyyyMMdd"))); if (e is System.Threading.ThreadAbortException) return; string strMsg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + e.Message; string detailMsg = string.Format("类型:{0}\r\n堆栈:{1})", e.GetType().Name, e.StackTrace); using (StreamWriter sw = new StreamWriter(logFilePath, true)) { sw.WriteLine(strMsg); sw.WriteLine(ExtraMsg); sw.WriteLine(detailMsg); sw.WriteLine(); sw.Close(); } }