最近寫了一支定時執行工作的程式,想在工作結束時將寫入情況、耗費時間寫入到Log檔。無意中發現微軟已經把寫入到Log檔的功能已經包好了,真是佛心來的。
只要透過My.Application.Log.WriteEntry這支function就能寫入到Log檔。而預設的Log檔是存放在一個隱藏的資料夾中:
C:\Documents and Settings\登入的使用者名稱\Application Data\專案名稱\1.0.0.0 'Application Data為隱藏的資料夾
我們也能在程式裡去指定存放的路徑。完整程式碼如下 :
Public Sub SaveLog()
Private path As String = Application.StartupPath + "\Log" '指定Log資料夾的路徑與應用程式的路徑相同
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
End If
With My.Application.Log.DefaultFileLogWriter
.BaseFileName = "Log" 'Log檔的檔名
.CustomLocation = path '自訂Log檔的存放路徑
.AutoFlush = True 'Log檔寫完後自動清除緩衝
.LogFileCreationSchedule = Logging.LogFileCreationScheduleOption.Daily '設定一天產生一個Log檔
End With
My.Application.Log.WriteEntry(String.Format("{0} {1} {2}",
SchDesc, '排程描述
SchStartTime, '開始執行時間
SchEndTime '結束執行時間
), TraceEventType.Information, EventLogEntryType.Information)
End Sub
備註:My.Application.Log 物件只適用於用戶端應用程式。至於 Web 應用程式,請使用 My.Log。