Class LogFile
VBScript Library: io\LogFile.vbs

Provides log file functionality to scripts including configurable verbosity and log file rotation.

Log Levels

Log levels are used to determine what messages should be output to the log file. Every message that is logged is logged with a level that indicates it's severity. A log level can be applied to the LogFile instance, only log messages that are equal to or more severe than the set level will be output to the log files. The default level is LOG_WARN.

The output log level can be set with setLogLevel() and may be one of:

  1. LOG_ERROR: only success and error messages will be logged
  2. LOG_WARN: same as above, including warning messages
  3. LOG_INFO: same as above, including informative messages
  4. LOG_VERBOSE: same as above, including verbose messages
  5. LOG_DEBUG: same as above, including debug messages

When using log levels with log() you can also pass LOG_SUCCESS. LOG_SUCCESS messages are always logged.

Log File Rotation

The class supports in-built log file rotation which is disabled by default. Without rotation, log files will grow until the disk is full or the maximum file size is reached. You can enable log file rotation by passing True to enableAutoRotation().

It should be noted that if you are logging a lot, rotation will hinder performance. Fewer larger files are preferable to many small files, this will help reduce the number of rotations.

Since VBScript seems reluctant to acknowledge UTC without messing with time biases from the registry, files are rotated numerically by inserting .00 between the filename and extension. The higher the number the older the file. The current log file will not have a number and be the filename supplied to openFile().

The log file size is checked when opening and is tracked internally as it is written to. Once it exceeds the size set with setMaxLogFileSize(), it will be rotated. The default is 5MB (5,120KB).

When rotation has been enabled, the default files is limited to 11, that's 10 historic and the current log. You can change the number of log files with setMaxLogFiles(). The total space used by the logs will then be approximately the number of files multiplied by the log file maximum size.

Reducing the number of log files will cause any excess log files to be cleaned up on the next rotation. If the logs are important to you, consider some kind of backup routine, especially if users are configuring your script.

Reference

Method Detail

Return Type Method and Description
- close()
Closes the open log file and frees resources.

A blank line is written before closing to help readability.

- checkAndRotateLogs()
Checks the size of the current log file and rotates if necessary.

Calling this method will rotate the log file even if isAutoRotationEnabled() returns false.

See Log File Rotation above for more information.

- enableAutoRotation(byVal enabled)
Enables or disables auto-rotation.

Use setMaxLogFileSize() to set the maximum size log files should grow to before rotating. To limit the number of log files, use setMaxLogFiles().

See Log File Rotation above for more information.

Parameters:

  • enabled (Bool): True to enable log file rotation
- enableAutoRotationLogMessages(byVal enabled)
Enables or disables auto-rotation log messages.

By default, log file rotation will output status and error messages to the log. These messages can be disabled by passing False.

See Log File Rotation above for more information.

Parameters:

  • enabled (Bool): True to enable rotation log messages
String getErrorMessage()
Returns the last error message that occurred while opening a log file.

When openFile() returns 2, a system error has occurred. The error code and message can be retrieved using getErrorMessage() and getErrorNumber().

Returns: the error message raised by openTextFile()

Int getErrorNumber()
Returns the last error code that occurred while opening a log file.

When openFile() returns 2, a system error has occurred. The error code and message can be retrieved using getErrorMessage() and getErrorNumber().

Returns: the error code raised by openTextFile()

Int getMaxLogFiles()
Returns the number of log files that will be kept if auto-rotation is enabled.

See Log File Rotation above for more information.

Returns: the number of log files that will be kept if auto-rotation is enabled

Long getMaxLogFileSize()
Returns the maximum size a log file can grow to if auto-rotation is enabled.

See Log File Rotation above for more information.

Returns: the maximum size a log file can grow to if auto-rotation is enabled

Bool isAutoRotationEnabled()
Returns True if auto-rotation is enabled.

See Log File Rotation above for more information.

Returns: True if auto-rotation is enabled

Bool isOpen()
Returns True if the log file is open and ready for writing.

Returns: True if the log file is open and ready for writing

- log(byVal logLevel, byVal message)
Writes a message to the current log file.

The message will only be written if logLevel is =< the value set with setLogLevel() or the value of DEFAULT_LOG_LEVEL.

Parameters:

  • logLevel (Int): one of LOG_DEBUG, LOG_ERROR, LOG_INFO, LOG_SUCCESS, LOG_VERBOSE or LOG_WARN
  • message (String): the message to write to the log
Int openFile(byVal filePath)
Opens a log file for writing.

If a non-zero value is returned, the LogFile is not ready for use. A value of 1 means the filename is invalid and cannot be broken into it's directory and filename parts. A value of 2 means a system error occurred opening the file. You should check the value of getErrorNumber() and getErrorMessage() for details.

Parameters:

  • filePath (String): the absolute or relative path to the log file to open

Returns: 0 if the log file was opened succesfully, 1 if the file name cannot be parsed and 2 if a system error occurs during opening

- rotateLog()
Manually rotates the log file, regardless of size.

If getMaxLogFiles() returns > 0, this will also delete any log files that exceed this value. Calling this method will rotate the log file even if isAutoRotationEnabled() returns False.

See Log File Rotation above for more information.

- setLogLevel(byVal level)
Sets the log level. Only log messages this or more severe will be outputted to the log file.

level must be between LOG_ERROR (1) and LOG_DEBUG (5).

Parameters:

  • level (Int): the log level
- setMaxLogFiles(byVal maxFiles)
Sets the maximum number of log files when auto-rotation is enabled.

When rotating logs, the maxFiles newest files are kept, any older files are deleted. Value must be between 2 and 100. If you want just one log file, disable auto-rotation.

See Log File Rotation above for more information.

Parameters:

  • maxFiles (Int): the maximum number of files
- setMaxLogFileSize(byVal size)
Sets the maximum size a log file can grow to.

The log file size is tracked, once it exceeds this size the log file is rotated. Minimum log file size is 1MB (1024KB).

Use enableAutoRotation() to enable or disable auto-rotation of log files. See Log File Rotation above for more information.

Parameters:

  • size (Int): the maximum log file size in KB

Script Constants

Name Type Value Description
DEFAULT_LOG_LEVEL Int 2 Log level that new instances will use.
DEFAULT_LOG_SIZE Int 5120 Default maximum log file size before rotation (in KB).
LOG_DEBUG Int 5 Log level to pass to log() to write a debug message to the log.
LOG_ERROR Int 1 Log level to pass to log() to write an error message to the log.
LOG_INFO Int 3 Log level to pass to log() to write an informative message to the log.
LOG_SUCCESS Int 0 Log level to pass to log() to write a success message to the log.
LOG_VERBOSE Int 4 Log level to pass to log() to write a verbose message to the log.
LOG_WARN Int 2 Log level to pass to log() to write a warning message to the log.

Sample Usage

The example code below opens a log file, enables auto-rotation with 4 x 10MB log files and writes test data to the log. It will then open the log in Notepad to demonstrate the output. You should have 4 log files in the folder once the script has finished. Running the script again will rotate those 4 files.

Option Explicit

const MY_LOG_FILE = "h:\temp\mylog.log"

Dim log: Set log = new LogFile
log.openFile(MY_LOG_FILE)

WScript.echo "openFile() return code: " & openResult
Select Case openResult
    Case 0: WScript.Echo "Log file opened."
    Case 1: WScript.Echo "Couldn't parse file name '" & MY_LOG_FILE & "'."
    Case 2: WScript.Echo "Script Error " & log.getErrorNumber() & _
            ": " & log.getErrorMessage()
End Select

If openResult <> 0 Then
    WScript.Echo "Exiting script, couldn't open log file."
    WScript.Quit openResult
End If

' Set the LogFile properties, the higher the log level, the less is logged, '
' we will have at most 4 x 10MB log files, so our logs should never use more '
' than ~40MB of disk space. '
log.setLogLevel LOG_DEBUG
log.enableAutoRotation True
log.setMaxLogFiles 4
log.setMaxLogFileSize 10240 ' KB '

WScript.Echo "Logging lots of junk to demonstrate log file rotation."
Dim p: p = 0
Do While p < 117370
    p = CLng(p + 1)
    log.log LOG_SUCCESS, "This is a success message."
    log.log LOG_ERROR, "This is an error message."
    log.log LOG_WARN, "This is a warning message."
    log.log LOG_INFO, "This is an informative message."
    log.log LOG_VERBOSE, "This is a verbose message."
    log.log LOG_DEBUG, "This is a debug message."
Loop

WScript.Echo "Written some stuff to the log."
log.close
WScript.Echo "Log file closed, opening in Notepad."

Dim shell: Set shell = CreateObject("WScript.Shell")
shell.exec "notepad.exe """ & MY_LOG_FILE & """"

WScript.Echo "Script exiting."
WScript.Quit 0

Example Output

[S] 2014-11-12 13:12:05 - LogAutoRotation - Log file rotation triggered, maximum file size exceeded.
[S] 2014-11-16 13:12:05 - This is a success message.
[E] 2014-11-16 13:12:05 - This is an error message.
[W] 2014-11-16 13:12:05 - This is a warning message.
[I] 2014-11-16 13:12:05 - This is an informative message.
[V] 2014-11-16 13:12:05 - This is a verbose message.
[D] 2014-11-16 13:12:05 - This is a debug message.

Directory of H:\temp

16/11/2014  13:12        10,485,788 mylog.01.log
16/11/2014  13:12        10,485,781 mylog.00.log
16/11/2014  13:12         2,087,045 mylog.log
16/11/2014  13:11        10,485,785 mylog.02.log
               4 File(s)     33,544,399 bytes