C# 記錄日誌
阿新 • • 發佈:2017-06-21
datetime appdomain als pac ide dom con gen pla
/// <summary> /// 日誌部分 /// </summary> /// <param name="fileName"></param> /// <param name="type"></param> /// <param name="content"></param> public static void WriteLogs(string fileName, string type, string content) {string path = AppDomain.CurrentDomain.BaseDirectory; if (!string.IsNullOrEmpty(path)) { path = AppDomain.CurrentDomain.BaseDirectory + fileName; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path= path + "\\" + DateTime.Now.ToString("yyyyMMdd"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path = path + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt"; if (!File.Exists(path)) { FileStream fs= File.Create(path); fs.Close(); } if (File.Exists(path)) { StreamWriter sw = new StreamWriter(path, true, System.Text.Encoding.Default); sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + type + "-->" + content); // sw.WriteLine("----------------------------------------"); sw.Close(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace Utils { /// <summary> /// <para> </para> /// 常用工具類——系統日誌類 /// <para> ---------------------------------------------------</para> /// <para> WriteEventLog:寫入系統日誌(2個方法重載)</para> /// <para> DelEventName:刪除日誌事件源分類</para> /// </summary> public class EventLogHelper { #region 寫入系統日誌 /// <summary> /// 寫入系統日誌 /// </summary> /// <param name="EventName">事件源名稱</param> /// <param name="LogStr">日誌內容</param> public static void WriteEventLog(string EventName, string LogStr) { try { if (!EventLog.SourceExists(EventName)) { EventLog.CreateEventSource(EventName, EventName); } EventLog.WriteEntry(EventName, LogStr); } catch (Exception) { } } /// <summary> /// 寫入系統日誌 /// </summary> /// <param name="EventName">事件源名稱</param> /// <param name="LogType">日誌類型</param> /// <param name="LogStr">日誌內容</param> public static void WriteEventLog(string EventName, string LogStr, EventLogEntryType LogType) { try { if (!EventLog.SourceExists(EventName)) { EventLog.CreateEventSource(EventName, EventName); } EventLog.WriteEntry(EventName, LogStr, LogType); } catch (Exception) { } } #endregion #region 刪除日誌事件源分類 /// <summary> /// 刪除日誌事件源分類 /// </summary> /// <param name="EventName">事件源名</param> /// <returns></returns> public static bool DelEventName(string EventName) { bool flag = false; try { if (EventLog.SourceExists(EventName)) { EventLog.DeleteEventSource(EventName,"."); flag = true; } } catch (Exception) { } return flag; } #endregion } }EventLogHelper
C# 記錄日誌