VB6如何在启动应用程序时创建日志文件

5

我希望记录应用程序执行过程中发生的异常情况。之前我使用消息框处理异常。我是VB 6的新手。

请提供一些示例代码,以创建日志文件并保存异常信息。

谢谢。


这篇文章似乎正是你想要的。 - johnnyArt
1个回答

10
你需要错误处理程序,使用 On Error Goto,以便在出现错误时执行自己的代码。(顺便提一句,在VB6中它们被称为“错误”,而不是“异常”)免费工具MZTools非常好用 - 它可以自动插入On Error Goto和一个包括当前程序名称的错误处理程序。
你还需要一个通用程序来将错误详细信息记录到文件中,就像下面这个例子一样。注意:我只是直接打了这段代码,没有进行测试(空气代码)。
Sub MySub()
  On Error Goto ErrHandler
  '... Do something ...'
  On Error Goto 0
  Exit Sub

ErrHandler:
  Call LogError("MySub", Err, Error$) ' passes name of current routine '
End Sub 

' General routine for logging errors '
Sub LogError(ProcName$, ErrNum&, ErrorMsg$)
  On Error Goto ErrHandler
  Dim nUnit As Integer
  nUnit = FreeFile
  ' This assumes write access to the directory containing the program '
  ' You will need to choose another directory if this is not possible '
  Open App.Path & App.ExeName & ".log" For Append As nUnit
  Print #nUnit, "Error in " & ProcName
  Print #nUnit, "  " & ErrNum & ", " & ErrorMsg
  Print #nUnit, "  " & Format$(Now)
  Print #nUnit
  Close nUnit
  Exit Sub

ErrHandler:
  'Failed to write log for some reason.'
  'Show MsgBox so error does not go unreported '
  MsgBox "Error in " & ProcName & vbNewLine & _
    ErrNum & ", " & ErrorMsg
End Sub

额外建议:自己编写堆栈跟踪
额外建议2:在IDE中关闭错误处理程序,可以使用类似于 If Not IsInIDE() Then On Error Goto Handler 的语句,并使用IsInIDE函数


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接