【C#通用类】日志记录类
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace KTCommon.LOG { public class TraceLog { /// <summary> /// 全局日志对象 /// </summary> public static TraceLog m_Trace = new TraceLog((HttpRuntime.AppDomainAppId == null) ? "d://LOG" : HttpRuntime.AppDomainAppPath + "//", "KTGJ"); public string m_LogFilePath = "";//当前日志文件路径 private string m_xmlPath = ""; //Log的目录 private string m_FileNamePrefix = ""; StreamWriter SW; public TraceLog(string filePath, string fileNamePrefix) { m_xmlPath = filePath; m_FileNamePrefix = fileNamePrefix; } #region //将显示的提示信息写到Log文件 public void Trace(string tipMsg) { string nodeTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); Trace(nodeTime, tipMsg); tipMsg = null; } public void Trace(string nodeTime, string tipMsg) { try { //一小时写一个文件 string strNowY = DateTime.Now.Year.ToString(); string strNowM = DateTime.Now.Month.ToString(); string strNowD = DateTime.Now.Day.ToString(); string strNowH = DateTime.Now.Hour.ToString(); string fileName = m_FileNamePrefix + "_" + strNowH + "0000.log"; string filePath = m_xmlPath + "\\LOG\\" + strNowY + "\\" + strNowM + "\\" + strNowD + "\\"; if (nodeTime != "") { nodeTime = "[" + nodeTime + "] "; } //LOG目录不存在,则创建 if (Directory.Exists(filePath) == false) { Directory.CreateDirectory(filePath); } m_LogFilePath = filePath + fileName; //日志文件不存在,则创建 if (File.Exists(filePath + fileName) == false) { if (SW != null) { SW.Flush(); SW.Close(); } File.Create(filePath + fileName).Close(); SW = new StreamWriter(filePath + fileName, true, Encoding.UTF8); } //创建实例 if (SW == null) { SW = new StreamWriter(filePath + fileName, true, Encoding.UTF8); } //将内容写到log文件中 SW.WriteLine(nodeTime + tipMsg); //刷新,实时保存 SW.Flush(); } catch (Exception ex) { System.Diagnostics.Debug.Print("TraceLog Error:" + ex.Message.ToString()); } } #endregion //将消息写到Log文件 } }