我有一个运行Try Catch的vb.net程序。我想要发生的事情,如果有异常,它会将该异常记录到文本文件中。我有:
Catch ex As Exception
MsgBox(ex.Message)
My.Application.Log.WriteException(ex, TraceEventType.Error, "Exception " & "with argument " & "C:\Log.txt" & ".")
End Try
但是它没有将异常发送到日志文件。我错过了什么?
答案 0 :(得分:1)
我认为这里的例子:http://msdn.microsoft.com/en-us/library/dsxzceby(v=vs.90).aspx可能会误导你一点。我觉得有点奇怪。
我认为这可能更好:
Public Sub SomeMethodWhichMightGenerateException(byval someArg as String)
Try
' Code that might generate an exception goes here.
' For example:
' Dim x As Object
' MsgBox(x.ToString)
Catch ex As Exception
My.Application.Log.WriteException(ex, _
TraceEventType.Error, _
"Exception with argument " & someArg & ".")
End Try
End Sub
fileName
只是msdn示例中的一个随机变量,与Exception
的记录位置无关......
在此处http://msdn.microsoft.com/en-us/library/7fx0fexe(v=vs.90).aspx查看My.Application.Log.WriteException
将数据写入的位置。
或者你也可以这样做:
Catch ex As Exception
IO.File.AppendAllText("C:\Log.txt", String.Format("{0}{1}", Environment.NewLine, ex.ToString()))
End Try
然而,正如其他人所说,您最好使用现有的错误记录框架。
答案 1 :(得分:1)
Public Function logerrors(ByVal [error] As String)
Dim filename As String = "Log_" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt"
Dim filepath As String = HttpContext.Current.Server.MapPath(Convert.ToString("~/ErrorLog/") & filename)
If File.Exists(filepath) Then
Using stwriter As New StreamWriter(filepath, True)
stwriter.WriteLine("-------------------START-------------" + DateTime.Now)
stwriter.WriteLine(Convert.ToString("Page :"))
stwriter.WriteLine([error])
stwriter.WriteLine("-------------------END-------------" + DateTime.Now)
End Using
Else
Dim stwriter As StreamWriter = File.CreateText(filepath)
stwriter.WriteLine("-------------------START-------------" + DateTime.Now)
stwriter.WriteLine(Convert.ToString("Page :"))
stwriter.WriteLine([error])
stwriter.WriteLine("-------------------END-------------" + DateTime.Now)
stwriter.Close()
End If
Return [error]
End Function
答案 2 :(得分:0)
在日志文件中添加时间戳
expires_in