Windows 環境搭配 ASP.NET時,使用Log4Net的方式如下:
下載Log4net
1. 放置Log4Net元件(log4net.dll)至VS.NET /bin/ 目錄 (要留意.NET版本)
2. 在VS.NET專案內引用log4net.dll元件
3. 修改「log4net設定檔」,放置在虛擬應用程式的根目錄(http://xxx/AP/log4net.config)
4. 修改global.asa.cs, 當虛擬應用程式啟動時, 載入「log4net設定檔」
protected void Application_Start(Object sender, EventArgs e) { log4net.Config.XmlConfigurator.ConfigureAndWatch (new System.IO.FileInfo(Server.MapPath("~/log4net.config"))); }
5. 程式內進行Log的寫法
5.1 引用log4net namespace
using log4net; using log4net.Config;
5.2 宣告class層級的ILog靜態唯讀變數
private static readonly ILog logger = LogManager.GetLogger("com.xxx.db.DBAccess");
5.3 使用ILog.Info("欲紀錄的字串")執行紀錄
logger.Info("紀錄字串\t紀錄字串");
參考範例:紀錄SQL Statement的執行時間與執行敘述
using System; using System.Data; using System.Data.Common; using System.Data.SqlClient; using log4net; using log4net.Config; namespace com.xxx.db { public class DBAccess { private static readonly ILog logger = LogManager.GetLogger("com.acer.db.DBAccess"); public DBAccess() { } public static int executeSelectQuery (string SqlStatement, DbConnection Connection, DataTable dt) { if (SqlStatement.Trim() == "") return -1; int returnRows = -1; try { DateTime t1 = DateTime.Now; DbDataAdapter adapter = getAdapter(SqlStatement, Connection); returnRows = adapter.Fill(dt); TimeSpan t = DateTime.Now.Subtract(t1); logger.Info("\t" + t.TotalMilliseconds + " \"" + SqlStatement + "\""); } catch (Exception e) { throw e; } return returnRows; } } }
全站熱搜