第一種 直接文件IO流寫日志文件
using System.IO; public static void WriteLog(string strLog) { string sFilePath="d:\\"+DateTime.Now.ToString("yyyyMM"); string sFileName = "rizhi" + DateTime.Now.ToString("dd") + ".log"; sFileName = sFilePath+ "\\"+sFileName; //文件的絕對路徑 if (!Directory.Exists(sFilePath))//驗證路徑是否存在 { Directory.CreateDirectory(sFilePath); //不存在則創建 } FileStream fs; StreamWriter sw; if (File.Exists(sFileName)) //驗證文件是否存在,有則追加,無則創建 { fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write); } else { fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write); } sw = new StreamWriter(fs); sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + " --- " + strLog); sw.Close(); fs.Close(); }
第二種 使用log4net類庫輸出日志
1.下載log4net類庫 並選擇項目對應的框架版本
下載地址:http://logging.apache.org/log4net/download_log4net.cgi
2.添加log4net引用,創建LogHelper類。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; using log4net.Core; [assembly: log4net.Config.XmlConfigurator(Watch = true)] namespace BoilerDashboard.Common { public class LogHelper { /// <summary> /// 輸出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="ex"></param> #region static void WriteLog(Type t, Exception ex) public static void WriteLog(Type t, Exception ex) { log4net.ILog log = log4net.LogManager.GetLogger(t); log.Error("Error", ex); } #endregion /// <summary> /// 輸出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="msg"></param> #region static void WriteLog(Type t, string msg) public static void WriteLog(Type t, string msg) { log4net.ILog log = log4net.LogManager.GetLogger(t); log.Error(msg); } #endregion } }
第三種 Microsoft Enterprise Library里面的Log功能
以VS2012里面建立的一個控制台程序為例
1. 安裝Microsoft Enterprise Library里面的Logging Application模塊。
在需要使用Log功能的項目上面右鍵,選擇Manage NuGet Packeages...
2. 在Manage NuGet Packeages窗口里面找到Enterprise Library - Logging Application Block,然后安裝
安裝成功以后,項目引用中會增加兩個新的引用。
3. 我們需要對App.config文件進行配置。在這里我們使用配置編輯工具:Microsoft.Practices.EnterpriseLibrary.ConfigConsoleV6.vsix。這個工具的下載地址:http://www.microsoft.com/en-us/download/details.aspx?id=38789
4. 配置App.config文件。右鍵App.config文件選擇Edit configuration file v6,打開配置工具窗口。
5. 選擇菜單命令Block -> Add Logging Settings
6. 在Logging Target Listeners里面點加號按鈕,然后選擇Add Rolling Flat File Trace Listener(生成可以進行自動分割的文本文件)。
7. 一般需要設置的參數有:Asynchronous(選true則進行異步log), File Exist Behavior(選), File Name, Formatter Name, Max Archived Files, Roll Interval, Roll Size KB。
其中Formatter Name的值從Log Message Formatters中生成的值中選取。
8. 生成 Message Format。在Log Message Formatters中點擊加號按鈕,選擇Add Text Formatter
點擊Template右側的...按鈕,打開Template Editor對話框,對Template的內容進行編輯
編輯后在App.config中生成的xml代碼如下:
Logging formatter
9. 在窗口左側區域中點擊Cotegories右邊的加號按鈕。生成一個新的Category
10. 在新生成的Category區域中修改Name屬性,然后點擊Listeners右邊的加號按鈕,選擇在Logging Target Listeners區域中已經生成的Listener。
11. 對已經進行的設置保
12. 寫個簡單的測試程序看看生成的Log效果如何