Search notes:

VBA class for hierarchical logging: dbgFileWriter

dbgFileWriter is a class that implements dbgWriter and writes debug text to files.
An instance of this class is initialized with the method init which takes as parameter the filename to which the debug-output should be written to.
An optional second argument specifies if the debugged output should be flused immediately to the file when dbgWriter_out is called.

Source code

'
'  vim: ft=vb
'
'  History
'    0.02   2020-07-30   In dbgWriter_out(): call flush() if flushImmediately_ is true
'    0.03   2021-07-20   Fix mess with flushImmediately_
'
option explicit

implements dbgWriter

private debugFile         as integer
private fileName_         as string
private flushImmediately_ as boolean
'
public sub class_terminate() ' {
   if not flushImmediately_ then
      closeFile
   end if
end sub ' }

public sub init(fileName as string, optional flushImmediately as boolean = false)
  '
  ' When using dbgFileWriter, it's probably advisable to explicitely
  ' use the VBA `end` statement when done.
  '

    fileName_         = fileName
    flushImmediately_ = flushImmediately

    if not flushImmediately_ then
       openFile
    end if

end sub

public sub dbgWriter_out(txt as string) ' {

    if flushImmediately_ then
       openFile
    end if

    print #debugFile, txt

    if flushImmediately_ then
       closeFile
    end if

end sub ' }

public sub flush() ' {
    closeFile
    openFile
end sub ' }

private sub openFile() ' {

    debugFile = freeFile()
    open fileName_ for append as #debugFile

end sub ' }
'
private sub closeFile() ' {

    if debugFile <> 0 then
       close #debugFile
    end if

    debugFile = 0

end sub ' }
Github repository VBAModules, path: /dbg/dbgFileWriter.cls

Test case for flushImmediately

option explicit

dim dbg_ as dbg

sub main(currentDir as variant) ' {

    set dbg_ = new dbg 
     
    dim fileWriter as new dbgFileWriter
    fileWriter.init currentDir & "dbg-out_" & format(now, "yyyy-mm-dd_hhnn") & ".txt", flushImmediately := true
    dbg_.init fileWriter

    dbg_.text "started"

    A

end sub ' }

sub A() ' {
    dbg_.indent "A"
    dbg_.text "in A"
    B
    dbg_.dedent
end sub ' }

sub B() ' {
    dbg_.indent "B"
    dbg_.text "in B"
    dbg_.dedent
end sub ' }
Github repository VBAModules, path: /_test/dbg/flushImmediately.vb

History

V0.2 2020-07-30
V0.3 Fix flushImmediately mess (2021-07-20)

TODO

dbgFileWriter should probably use the file class.

See also

The dbgFileWriter class might be tested with this test script.
VBA classes for hierarchical logging

Index