[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 383
  • Last Modified:

Error Logging for VB6 App

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
dsteers
Asked:
dsteers
1 Solution
 
appariCommented:
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
 
dsteersAuthor Commented:
Thanks,
I'll check it out and get back to you in a few days.

Dave
0
 
inthedarkCommented:
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
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
dsteersAuthor Commented:
Ok Guys,
Thanks for the reply's,I'll try and get back to you within the week.
0
 
dsteersAuthor Commented:
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
 
Valliappan ANSenior Tech ConsultantCommented:
interested...
0
 
jrspanoCommented:
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
 
dsteersAuthor Commented:
Thanks again.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now