1. 程式人生 > >VB.NET 寫日誌檔案

VB.NET 寫日誌檔案

''' <summary>
    ''' 寫日誌
    ''' </summary>
    ''' <param name="msg">日誌內容</param>
    ''' <param name="context">上下文物件</param>
    ''' <remarks></remarks>
    Sub WriteLog(msg As String, Optional context As System.Web.HttpContext = Nothing)
        Dim filepath As String = ""
        If context Is Nothing Then
            filepath = Me.LogFilePath
        Else
            filepath = context.Server.MapPath("..") + "\File\LogFile\"
        End If
        filepath &= Now.ToString("yyyyMMdd") & ".txt"
        Dim content As String
        If context IsNot Nothing Then
            content = "<-------------異常時間:" & Now.ToString("yyyy-MM-dd HH:mm:ss") & _
                Chr(13) & msg & "來源:" & context.Request.Url.ToString & _
                "錯誤資訊:" & context.Error.Message & _
                Chr(13) & "錯誤詳情:" & Chr(13) & context.Error.StackTrace & Chr(13) & _
                "--------------->" & Chr(13)
        Else
            content = "異常時間:" & Now.ToString("yyyy-MM-dd HH:mm:ss") + Chr(13) & msg & Chr(13)
        End If
        File.AppendAllText(filepath, content)
    End Sub