[code]public class LogClass { private static LogClass mInstance = null; private static readonly object lockAssistant = new object(); public static LogClass Instance { get { if (mInstance == null) { lock (lockAssistant) { if (mInstance == null) { mInstance = new LogClass(); } } } return mInstance; } } private LogClass() { } /// <summary> /// 写日志(追加到上次日志下一行) /// </summary> /// <param name=\"logText\">日志内容</param> public void WriteLogFile(string logText) { string logPath = System.Windows.Forms.Application.StartupPath; if (!Directory.Exists(logPath)) Directory.CreateDirectory(logPath);//Directory.GetCurrentDirectory() string fname = logPath + \"\\\\LogFile.log\"; FileInfo finfo = new FileInfo(fname); if (!finfo.Exists) { FileStream fs; fs = File.Create(fname); fs.Close(); finfo = new FileInfo(fname); } if (finfo.Length > 1024 * 1024 * 10) { DateTime dtnow = DateTime.Now; string newPath = System.Windows.Forms.Application.StartupPath + \"\\\\\" + dtnow.ToString(\"yyyyMMddHHmmss\") + \"之前LogFile\"; if (!Directory.Exists(newPath)) Directory.CreateDirectory(newPath); File.Move(fname, newPath + \"\\\\LogFile.log\"); } FileStream fs2 = finfo.OpenWrite(); { StreamWriter w = new StreamWriter(fs2); w.BaseStream.Seek(0, SeekOrigin.End); w.WriteLine(\"{0} {1}\", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString()); w.WriteLine(logText); w.WriteLine(\"------------------------------------\"); w.Flush(); w.Close(); } fs2.Close(); fs2.Dispose(); fs2 = null; } }
调用时使用LogClass.Instance.WriteLogFile(ex.ToString());