應用範圍:
隨時記錄AP的運作狀況,以確定它正常運作。
記錄錯誤發生時的各項資訊,以利之後的Debug作業。
供使用者查詢應用程式運作的記錄。(或是應用程式無法運作時的回報記錄)
錯誤發生時通知相關人員處理問題。
步驟:
1.下載Log4net Library http://logging.apache.org/log4net/download.html
2.專案加入Log4net.dll(檔案於解壓縮資料夾下,bin\net\2.0\release)
3.在你的專案加入應用程式組態檔(App.config)[若是web專案的話,請加入在web.config],並加入下面組態:
PS.Log方式除上面的FileLog及ApplicationEventLog外,還有資料庫(DB2,MS SQL ...),UDP ....
有需要其它Log方式的話,請參照http://logging.apache.org/log4net/release/config-examples.html
基本上,一個logger內會設定一個level;但可以設定多個appender-ref.
4.在專案中,加入Log:
Public Class Form1
Private Log As Log4Net.ILog
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Log4Net.Config.XmlConfigurator.Configure()
Log = Log4Net.LogManager.GetLogger("LoggingExample")
Log.Info("INFO Message")
Log.Warn("WARN Message")
Log.Debug("DEBUG Message")
Log.Fatal("FATAL Message")
Log.Error("ERROR Message!")
End Sub
End Class
5. 執行的結果,會寫到文件(rolling-log-20081110.log)及系統事件簿中的應用程式事件中;文件的部份內容如下:
[Header]
2008-11-07 16:23:42,862 [10] INFO LoggingExample [file:D:\Job\VACSS\Program\Server\Log4Net\Log4Net\Form1.vb (line:8)] - INFO Message
2008-11-07 16:23:42,908 [10] WARN LoggingExample [file:D:\Job\VACSS\Program\Server\Log4Net\Log4Net\Form1.vb (line:9)] - WARN Message
2008-11-07 16:23:42,908 [10] DEBUG LoggingExample [file:D:\Job\VACSS\Program\Server\Log4Net\Log4Net\Form1.vb (line:10)] - DEBUG Message
2008-11-07 16:23:42,908 [10] FATAL LoggingExample [file:D:\Job\VACSS\Program\Server\Log4Net\Log4Net\Form1.vb (line:11)] - FATAL Message
2008-11-07 16:23:42,908 [10] ERROR LoggingExample [file:D:\Job\VACSS\Program\Server\Log4Net\Log4Net\Form1.vb (line:12)] - ERROR Message!
[Footer]
你可以在App.config中,宣告多告logger,在不同狀況下使用不同的記錄log方式。