|
|
Title | Build a simple logging class |
Description | This example shows how to build a simple logging class in Visual Basic 6. The Log class provides methods to open a log file, write to the file, and close the file. |
Keywords | log, logging, log file |
Categories | Software Engineering, Files and Directories |
|
|
Thanks to Stefan De Prins.
The Log class lets an application easily write logs entries to a file.
Subroutine CreateFile creates a file in a given directory. It uses the fsCreateFileName function to get a file name that contains the current date. CreateFile creates this file or opens it for appending.
|
|
Public Sub CreateFile(ByVal Path As String, ByVal vsTitle _
As String)
Dim lsFile As String
Path = Trim(Path)
If Right(Path, 1) <> "\" Then
Path = Path & "\"
End If
miFileNumber = FreeFile
lsFile = Path & fsCreateFileName
If Dir(lsFile) = "" Then
Open lsFile For Output As #miFileNumber
Else
Open lsFile For Append As #miFileNumber
End If
If Dir(lsFile) <> "" Then
mbFileHasBeenAssigned = True
Else
coError.SetError 1001, "File Creation failed"
End If
mvarTitle = vsTitle
End Sub
Private Function fsCreateFileName() As String
fsCreateFileName = Format(CDate(Now()), "YYYY-MM-DD") & _
".txt"
End Function
|
|
Subroutines WriteHeader, WriteLine, and WriteFooter add text to the file.
|
|
Public Sub WriteHeader()
WriteLine _
"***********************************************"
WriteLine "START " & mvarTitle & " ON " & _
Format(CDate(Now()), "YYYY-MM-DD hh:nn:ss")
WriteLine _
"***********************************************"
WriteLine " "
WriteLine " "
End Sub
Public Sub WriteLine(ByVal vsLine As String)
If mbFileHasBeenAssigned Then
Print #miFileNumber, vsLine
Else
coError.SetError 1000, "No file has been assigned"
End If
End Sub
Public Sub WriteFooter()
WriteLine " "
WriteLine " "
WriteLine _
"***********************************************"
WriteLine "END " & mvarTitle & " ON " & _
Format(CDate(Now()), "YYYY-MM-DD hh:nn:ss")
WriteLine _
"***********************************************"
End Sub
|
|
Subroutine CloseFile closes the log file.
|
|
Public Sub CloseFile()
If mbFileHasBeenAssigned Then
Close #miFileNumber
mbFileHasBeenAssigned = False
Else
coError.SetError 1000, "No file has been assigned"
End If
End Sub
|
|
Note: If you open the log file when the program starts and close it when it ends, you may lose some logging if the application crashes without closing the file. If you want to catch everything, you can open the file, write into it, and close the file each time you want to save some information.
|
|
|
|
|
|