Sunday, January 6, 2008

Writing trace messages in VB (script) programs.

Writing trace messages in VB (script) programs
Download source files - 10 Kb

' first, create the com object
' you can use one or more such objects within a single process
dim objTrace
set objTrace = CreateObject("XYTraceObj.1")
dim myInt = -2

' then set the trace file prefix
' this method needs only to be called once within a process
' the trace file will be created in directory "c:\temp" with name prefix "VBLog"
objTrace.SetTraceFilePrefix "c:\temp\VBLog"

' set the current trace level to 10
' this method affect the whole process
objTrace.SetTraceLevel 10

' write trace messages to the trace file
' the first parameter of WriteTrace is the intended trace level
' the second parameter of WriteTrace is a format string as in the C function printf
' only the first message will be written because the current trace level is 10
objTrace.WriteTrace 10, "The string: %s", "Hello, world"
objTrace.WriteTrace 20, "The int: %d", 300
objTrace.WriteTrace 30, "Something else: %d, %s, %04d", 200, "Hey", myInt

' set the current trace level to 20
objTrace.SetTraceLevel 20

' write trace messages to the trace file
' only the first two messages will be written because the current trace level is 20
objTrace.WriteTrace 10, "The string: %s", "Hello, world"
objTrace.WriteTrace 20, "The int: %d", 300
objTrace.WriteTrace 30, "Something else: %d, %s, %04d", 200, "Hey", myInt

' set the current trace level to 30
objTrace.SetTraceLevel 30

' write trace messages to the trace file
' all three messages will be written because the current trace level is 30
objTrace.WriteTrace 10, "The string: %s", "Hello, world"
objTrace.WriteTrace 20, "The int: %d", 300
objTrace.WriteTrace 30, "Something else: %d, %s, %04d", 200, "Hey", myInt

' disable tracing by setting the trace level to 0
objTrace.SetTraceLevel 0

' this message will not be written
objTrace.WriteTrace 10, "Why am I not written? Because tracing is disabled!"

' set objTrace to nothing
set objTrace = nothing



Here is the trace file for the above program. The string 06:57:30_843_1EB in the trace message is the timestamp (down to milliseconds) and the hex thread id.

06:57:30_843_1EB: The string: Hello, world
06:57:30_843_1EB: The string: Hello, world
06:57:30_843_1EB: The int: 300
06:57:30_843_1EB: The string: Hello, world
06:57:30_843_1EB: The int: 300
06:57:30_843_1EB: Something else: 200, Hey, -002