C#写日志类实例
本文实例讲述了C#写日志类,分享给大家供大家参考。
具体实现方法如下:
usingSystem; usingSystem.Configuration; usingSystem.IO; usingSystem.Threading;
namespaceFQDService.Utils { ///<summary> ///写日志类 ///</summary> publicclassFileLogger { #region字段 publicstaticreadonlyobject_lock=newobject(); #endregion
#region写文件 ///<summary> ///写文件 ///</summary> publicstaticvoidWriteFile(stringlog,stringpath) { Threadthread=newThread(newParameterizedThreadStart(delegate(objectobj) { lock(_lock) { if(!File.Exists(path)) { using(FileStreamfs=newFileStream(path,FileMode.Create)){} }
using(FileStreamfs=newFileStream(path,FileMode.Append,FileAccess.Write)) { using(StreamWritersw=newStreamWriter(fs)) { #region日志内容 stringvalue=string.Format(@"{0} -------------------------------------------------------- {1}
",DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss"),obj.ToString()); #endregion
sw.WriteLine(value); sw.Flush(); } } } })); thread.Start(log); } #endregion
#region写日志 ///<summary> ///写日志 ///</summary> publicstaticvoidWriteLog(stringlog) { stringlogPath=ConfigurationManager.AppSettings["LogPath"]+"\\FQDService_Log.txt"; WriteFile(log,logPath); } #endregion
#region写错误日志 ///<summary> ///写错误日志 ///</summary> publicstaticvoidWriteErrorLog(stringlog) { stringlogPath=ConfigurationManager.AppSettings["LogPath"]+"\\FQDService_ErrorLog.txt"; WriteFile(log,logPath); } #endregion
} }