Friday, December 15, 2006

Reusable Logging in VBScript - LogToFile.vbs

*Updated 10-18-07*

Frequently I have had the need to log certain information or messages to a log file as script is running. Since this is such a frequent requirement, and adding logging to a script can be a messy affair since it's often an after thought. I decided to write a sub routine that you could easily call and it would do the work for you.

When using the following script, you simply prepend the configuration section to the beginning of the script, decide how you'd like the script to behave by changing the various options, and then append the sub portion to the end of the script.

Anywhere you'd like to log a message within the script you'd simply add LogToFile "Your Message" to log the relevant information.

With this script you can log the date and time you began the script, the date and time of any particular events, and generate unique filenames if you want to schedule script run times. It's also simple to turn off logging without editing the entire logging section out.

'---------LogToFile Configuration---------
'NOTE: Copy the configuration section To
'the beginning of an existing script. The
'values specified here must be set before
'calling the LogToFile sub.

'You can disable logging globally by
'setting the bEnableLogging option to false.
bEnableLogging = True

'Setting this to true will time stamp Each
'message that is logged to the log file
'with the current date and time.
bIncludeDateStamp = True

'This will set the log file name to the
'current date and time. You can use this
'option to create incremental log files.
bPrependDateStampInLogFileName = False

'Specify the log file location here. Path
'must contain a trailing backslash. If you
'would like to log to the same location as
'the currently running script, set this
'value to "relative" or uncomment out the
'line below.
'sLogFileLocation = "C:\LogFiles\"
sLogFileLocation = "relative"

'Specify the log file name here.
sLogFileName = "logtofiletest.txt"

'You can set whether or not you would like
'the script to append to an existing file,
'or if you would like it to overwrite
'existing copies. To overwrite set the
'sOverWriteORAppend variable to "overwrite"
sOverWriteORAppend = "append"

'Here you can set the maximum number of
'lines you like to record. If the maximum
'is reached the beginning of the log file
'will be pruned. Setting this to a value
'of 0 will disable this function.
vLogMaximumLines = 0

'This is just like limiting the log file
'to a number of lines but limits by the
'total size of the log file. This value
'is in bytes. Setting this to 0 will
'disable this function.
vLogMaximumSize = 0
'-------END LogToFile Configuration-------

Sub LogToFile(Message)
    'LogToFile.vbs 10-18-07
    'This script is provided under the Creative Commons license located
    'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
    'be used for commercial purposes with out the expressed written consent
    'of NateRice.com

    If bEnableLogging = False Then Exit Sub

    Const ForReading = 1
    Const ForWriting = 2
    Const ForAppending = 8

    Set oLogFSO = CreateObject("Scripting.FileSystemObject")
   
    If sLogFileLocation = "relative" Then
        Set oLogShell = CreateObject("Wscript.Shell")
        sLogFileLocation = oLogShell.CurrentDirectory & "\"
        Set oLogShell = Nothing
    End If
   
    If bPrependDateStampInLogFileName Then
        sNow = Replace(Replace(Now(),"/","-"),":",".")
        sLogFileName = sNow & " - " & sLogFileName
        bPrependDateStampInLogFileName = False       
    End If
   
    sLogFile = sLogFileLocation & sLogFileName
   
    If sOverWriteORAppend = "overwrite" Then
        Set oLogFile = oLogFSO.OpenTextFile(sLogFile, ForWriting, True)
        sOverWriteORAppend = "append"
    Else
        Set oLogFile = oLogFSO.OpenTextFile(sLogFile, ForAppending, True)
    End If

    If bIncludeDateStamp Then
        Message = Now & "   " & Message
    End If

    oLogFile.WriteLine(Message)
    oLogFile.Close
   
    If vLogMaximumLines > 0 Then
      Set oReadLogFile = oLogFSO.OpenTextFile(sLogFile, ForReading, True)   
      sFileContents = oReadLogFile.ReadAll
      aFileContents = Split(sFileContents, vbCRLF)
      If Ubound(aFileContents) > vLogMaximumLines Then
        sFileContents = Replace(sFileContents, aFileContents(0) & _
        vbCRLF, "", 1, Len(aFileContents(0) & vbCRLF))
        Set oLogFile = oLogFSO.OpenTextFile(sLogFile, ForWriting, True)
        oLogFile.Write(sFileContents)
        oLogFile.Close
      End If
      oReadLogFile.Close
    End If
    
    If vLogMaximumSize > 0 Then
      Set oReadLogFile = oLogFSO.OpenTextFile(sLogFile, ForReading, True)  
      sFileContents = oReadLogFile.ReadAll
      oReadLogFile.Close
      sFileContents = RightB(sFileContents, (vLogMaximumSize*2))
      Set oLogFile = oLogFSO.OpenTextFile(sLogFile, ForWriting, True)
      oLogFile.Write(sFileContents)
      oLogFIle.Close
    End If
    
    oLogFSO = Null
End Sub
Send this to:                          

Comments

Vijay Saraff said...

Thanks for the tip. I had written a similar routine in VB but couldn't find it. I used it in a script of mine, i'll put the link here when it's done

5/25/2007 4:15:52 AM

Vijay Saraff said...

As promised here is the link to the script i've written

http://vijay.saraff.com/blog/2007/05/29/copy-target-instead-of-shortcuts/


I see you've changed the domain name/hosting provider!

5/30/2007 3:31:02 AM

Chris Maze said...

Hey Nate, can I use your vbs logger for some quick little internal projects at work. Nothing thats prifitable or nothing and I'll keep you license in the code. Its really just for me. Its a nice little piece of code. Please let me know. I could find an email for you. PEace.

6/25/2007 3:29:38 PM

Big Dave G said...

Het Nate, nice bit of code for learning purposes. Helped me heaps on some small projects.

12/13/2007 2:24:37 PM

said...

great script with elaborate comments ...
thanks a lot...

4/18/2009 5:42:32 AM

said...

Thank you. Works nicely.

1/29/2010 6:34:39 AM

said...

I don''t like this line

Message = Now & " " & Message

When I try to log any variable, this line changes that variable by adding time.

2/2/2010 4:39:54 AM

Name
URL
Email
Email address is not published
Remember Me
Comments

CAPTCHA
Write the characters in the image above