Thursday, December 11, 2008

Creating errorlogs in Asp.net

Public Sub WriteErrorsInLog(ByVal ErrorString As String)
Dim sDirecPath As String
sDirecPath = "~/ErrorDirectory" 'variable: directory path for error log.
'for checking that directory exists , if not then create it.
If Directory.Exists(HttpContext.Current.Server.MapPath(sDirecPath)) = False Then
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(sDirecPath))
End If
Dim fpath As String 'variable: file path
fpath = Path.Combine(sDirecPath, Format(Today, "yyyyMMdd").ToString() & ".txt")
'for checking file exists or not . if not then create the file and append the file
If File.Exists(HttpContext.Current.Server.MapPath(fpath)) = False Then
File.WriteAllText(HttpContext.Current.Server.MapPath(fpath), " ")
WriteInErrorLogFile(HttpContext.Current.Server.MapPath(fpath), ErrorString)
Else
WriteInErrorLogFile(HttpContext.Current.Server.MapPath(fpath), ErrorString)
End If
End Sub
'''
''' To append the file for entry of errors into the file.
'''

''' path for file location
''' errors in string format
'''
Private Sub WriteInErrorLogFile(ByVal fpath As String, ByVal ErrorString As String)
Dim wr As System.IO.StreamWriter
Try
wr = New System.IO.StreamWriter(fpath, True)
Dim str As String = ""
str = System.DateTime.Now.ToString() & " ---- " & ErrorString
str = str & System.Environment.NewLine
wr.WriteLine(str)
wr.Flush()
wr.Dispose()
Catch ex As Exception
End Try
End Sub

No comments:

Post a Comment