Solved

Error Logging for VB6 App

Posted on 2001-09-08
8
342 Views
Last Modified: 2012-06-22
Hi,
I was wanting to make my program write a log of errors to a text file when something goes wrong - so I can atleast know where to go and fix the problem.
Any other comments regarding Error handeling would be appreciated.

Thanks
Dave Steers
0
Comment
Question by:dsteers
8 Comments
 
LVL 39

Expert Comment

by:appari
ID: 6466611
this is what i use in my applications. it creates a log file in application path with err_YYYYMM.log


write a public procedure in a module to which you can pass error number, error description, sub/function name where error has occured. in this sub open a text file (extension .log ) and write it to the file with date and time. call this sub from all error handling routines.
sample code something like this


Public Sub showError(Optional ByVal strProcName As String = "UNKNOWN", _
Optional bShowMsgBox As Boolean = True, _
Optional errObj As ErrObject,
Optional errLine As integer)
Dim intFileNumber As Integer
   
    intFileNumber = FreeFile
   
    ' Opening the file in append mode
    Open app.path  + "\Err_" & Format(Date, "YYYYMM") + ".log" For Append As #intFileNumber
   
    ' Writing the error message along with the additional info in this file
    Write #intFileNumber, Format(Date, "YYYY-MM-DD") & " " & Format(Time, "HH:MM") & "   " & strProcName
   
    If Not errObj Is Nothing Then
        Write #intFileNumber, "VB " & Str(errObj.Number) & " " & errObj.Description
        Write #intFileNumber, "Error in Line No: " & errLine

        Write #intFileNumber, "----------------------------------------------------------------------------------"
       
        If (bShowMsgBox) Then
            If Len(errObj.Description) > 0 Then
                MsgBox "Error occued in : " & strProcName & vbNewLine & errObj.Number & " : " & errObj.Description, vbExclamation, AppName
            ElseIf Len(err.Description) > 0 Then
               MsgBox "Error occued in : " & strProcName & vbNewLine & err.Number & " : " & err.Description, vbExclamation, AppName
            End If
        End If
       
        err.Clear
        errObj.Clear
    End If
   
    Close #intFileNumber
   
   
   
End Sub


call the above from any sub like this

Sub Test()
on error goto ErrX
Dim i as integer , J as integer
10    I=10
20    J=i/0
30    msgbox i
SafeExit:
    exit sub
ErrX:
    showerror "Test",True , err,erL
    resume SafeExit
end sub


hope this helps

0
 

Author Comment

by:dsteers
ID: 6466665
Thanks,
I'll check it out and get back to you in a few days.

Dave
0
 
LVL 17

Accepted Solution

by:
inthedark earned 100 total points
ID: 6467047
Further to appari's suggestion in your error trap ALWAYS set ON ERROR RESUME NEXT.  If there is an error in the error handling your hard disk will fill up.

e.g.

Sub Test()
on error goto ErrX
Dim i as integer , J as integer
10    I=10
20    J=i/0
30    msgbox i
SafeExit:
   exit sub
ErrX:
   on error resume next
   showerror "Test",True , err,erL
   resume SafeExit
end sub

But here is a better way of setting errors.

Create a Function to see if you are running in IDE or compiled DLL or EXE.


Public Function DebugMode() as Boolean

On error resume next
err.clear
debug.print 1/0
If err.number=0 then
  DebugMode=False
Else
    DebudMode = True
End If

End Function

So you test sub now starts like this:

Sub Test()

If DebugMode Then
    On Error Goto 0
Else
    on error goto ErrX
End If

Now any errors you find when testing will not be so easy to miss.


If you are developing a Web application you may get faults in some strange conditions.  But over a weekend you may get 1000's of logs so it makes sense to log as much detail as possible in a format that can be loaded into a database. So generate a CSV compaible log file.

Also it is a good idea to log the UserID so that you know who had the problem.  If it was the MD you can tell him its fixed before you the hassel.  Or on a web site you can also save the URL that caused the error.

Sub Logger(LogFile As String, WebConID, PageID, Message$)

If Len(LogFile) = 0 Then Exit Sub

Dim wlfn As Integer
Dim ok
wlfn = FreeFile
If Len(Dir(LogFile)) = 0 Then
    Open LogFile For Output As #wlfn
    Print #wlfn, """Date Logged"", ""WebConnID"", ""PageID"", ""Message"""
Else
    On Error Resume Next
    Open LogFile$ For Append As #wlfn
End If

Print #wlfn, Format$(Now, "DD/MMM/YY HH:NN:SS"), CStr(WebConID), CStr(PageID), Message$

Close wlfn

End Sub

I always build function libs to do standard routines that never fail.  Normally I decare these libs as a global variables so that the are always avaiable.  And it saves you having to remember what you called a routine.  Just type ADO. and the info pops up.

So you code becomes a little more usfull:

Sub Test()

Dim Step as long
Dim CN as ADODB.Connection
Dim RS as ADODB.Recordset
Dim ADO as New ADOLIB ' your ADO functions (normally a global variable)
Dim GF as New GFLIB ' your general purpose functions

If DebugMode Then
    On Error Goto 0
Else
    on error goto ErrX
End If


Step = 1000

Ok=ADO.OpenConnectionOK(CN) ' will never crash but returns Ok=True or False
If Not Ok Then
   Message=ADO.GetLastError(CN)
   Goto ErrX
End If

Step = 1010

SQL="Select * from YourTable;"

Ok=ADO.OpenRSOK(CN, RS, SQL)
If Not Ok Then
   Message=SQL: "+sql+" ~ "+ADO.GetLastError(CN)
   Goto ErrX
End If

Step = 1050
' etc.

SafeExit:
On Error Resume Next
if Not RS Is Nothing Then
    RS.Close
    Set RS=Nothing
End if

If Not CN Is Nothing Then
    CN.Close
    Set CN=Nothing
End if

Exit SUb

ErrX:
    On Error Resume Next

    If Len(message)=0 then
       Message=Err.Description
    End if

    GF.Logger LogFile, UserID, "Sub: Test: Step: "+cstr(Step), Message
    Resume SafeExit

0
 

Author Comment

by:dsteers
ID: 6468253
Ok Guys,
Thanks for the reply's,I'll try and get back to you within the week.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:dsteers
ID: 6468257
inthedark,
I have some points that to give for some extra info on a PAQ that you gave me so please go to :
http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=visualbasic&qid=20141134

Regards
Dave Steers
0
 
LVL 9

Expert Comment

by:Valliappan AN
ID: 6470245
interested...
0
 
LVL 3

Expert Comment

by:jrspano
ID: 6501012
i wrote a whole error object a long time ago.  I implements a stack trace and error log.  What ever you decide to do make sure you wrap it nicely in a class so you can use it again in other projects.  I add the errorhanlder dll I make to my new projects.  Then make a global object in a mod of the object.  Initialize it to what I want It to do in sub main then use it like

    exit sub
ErrHandler:
    oErr.HandlerError

this way the error handling is consistant and easy to do.
0
 

Author Comment

by:dsteers
ID: 6502024
Thanks again.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now