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

Roy*_*son 5 vb6 logging

我想记录在执行我的应用程序期间发生的异常.在此之前我用消息框处理它.我是VB 6的新手.

请提供一些示例代码来创建日志文件并保存异常消息.

谢谢..

Mar*_*rkJ 8

您需要使用错误处理程序,On Error Goto以便在发生错误时执行自己的代码.(在VB6中BTW它们被称为错误而不是异常.)免费工具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
Run Code Online (Sandbox Code Playgroud)

奖金建议:滚动自己的堆栈跟踪.
奖金建议2:If Not IsInIDE() Then On Error Goto Handler使用此处IsInIDE功能关闭IDE中的错误处理程序