Photo Gallery Member List Search Calendars FAQ Ticket List Log Out


Logger Class

 
Logged in as: Guest
arrSession:exec spGetSession 2,16,24797
 Active Users: There are 0 members and 0 guests.
 Users viewing this topic: none
 

 

 
  
  Printable Version
All Forums >> [Scripting] >> Post a VBScript >> Logger Class
  Do you like VisualBasicScript.com? Link to us and help spread the word about our forum. Thanks!
Page: [1]
Login
Message << Older Topic   Newer Topic >>
 Logger Class - 8/12/2005 12:59:13 AM   
  ebgreen


Posts: 4595
Score: 29
Joined: 7/12/2005
Status: offline
If anyone has ever used any of the Log4N loggers, that is loosely what I bassed this class on. It will let you instantiate a logger object that will hopefully safely handle things like file opening and closing in a smart error free fashion. It let's you select one of 5 log levels: SEVERE, WARN, INFO, DEBUG, NOLOG. For the selscted level, any logline that is called with that level or higher importance will be logged. NOLOG is a special case in that if you set the log level to NOLOG, then nothing will ever be written to the log file. You can also set the indentation level and the character that is used for indentation. This allows for rudimentary formatting of the log. In our environment, we implement this as a wsc file and register it as a com object. Please provide any feedback that you feel is appropriate.

Class Logger
    '=====================================================================================
    '
    '    Class:        Logger
    '    Author:        ###
    '
    '    Public Properties:
    '        LogLoc - Log file path and file name - Default:c:\temp\<ScriptName>.Log
    '        AppendMode - Whether or not to append to an existing log file. This defaults
    '                     to True. If you want it to be False, it must be set before
    '                     LogLoc is set.
    '        FilterLevel - There are currently three valid filter levels. They are
    '                     "NOLOG", "SEVERE", "WARNING", "INFO", and "DEBUG". If a logline is sent to
    '                     the logger it will only be logged if its level is greater than or
    '                     equal to FilterLevel. Thus if FilterLevel is set to WARNING, only
    '                     lines with "WARNING" or "SEVERE" level will actually be logged.
    '
    '    Public Methods:
    '        LogLine(strLvl, strMsg) - Logs strMsg to the log file at LogLoc if strLvl is
    '                     greater than FilterLevel.
    '        LogBlankLine - Places a blank line in the log file.
    '        LogNoStamp(strLvl, strMsg) - Logs to the file according to the same level rules as
    '                     LogLine.
    '
    '    To Do:
    '        - Allow AppendMode to be set anytime before the first LogLine call
    '        - Allow the use of an xml based config file
    '        - Allow for adding STDOUT in addition to logging
    '
    '    Revision History:
    '        7/21/04 - RMD - Initial creation
    '        7/22/04 - RMD - Changed the default location to use the script name
    '        7/22/04 - RMD - Added SmartFileOpen to allow the construction of the path
    '                        to the log file dynamically.
    '        1/19/05 - RMD - Added the VerboseMode property to cause output to got to STDOUT as it is
    '                        looged if VerboseMode is set to True.
    '        3/11/05 - RMD - Added the NOLOG filter to give a means for turning off logging
    '        7/29/05 - RMD - Changed the date/time stamp format to YYYY-MM-DD-hh:mm:ss
    '        7/29/05 - RMD - Added the IndentLevel property to control the level of indentation
    '        7/29/05 - RMD - Added the IndentChar property to set the character used to indent
    '                        default is vbTab
    '
    '======================================================================================   
    Private strLogFile              'This is the internal var for the path and name of the Log
    Private bAppend                    'Internal bool to control whether the log appends or Not
    Private nFilterLevel            'Controls what level of messages are shown
    Private dAllowableFilters        'Dictionary to hold the allowable logging levels
    Private nAppendMode                'Integer to set the append mode when the file is actually opened
    Private bFirstWrite                'Used to track the first time a message is logged for append
    Private bVerbose                'Determines if info is output to STDOUT as it is logged default is False
    Private nIndentLevel            'Set the indentation level
    Private strIndentChar            'Character used for Indentation defaults to vbTab
        
     '======================================================================================
     '
     '    Class constructor
     '    Notes:
     '        Sets default values for log file name, append mode, and log level. Also builds
     '        the dictionary of allowable logging levels.
     '
     '======================================================================================
     Private Sub Class_Initialize
         strLogFile = Replace(WScript.ScriptFullName, WScript.ScriptName, "") _
                      & Split(WScript.ScriptName, ".")(0) & ".log"
         bAppend = True
         nAppendMode = 8
         Set dAllowableFilters = CreateObject("Scripting.Dictionary")
         dAllowableFilters.Add "NOLOG", 4
         dAllowableFilters.Add "SEVERE", 3
         dAllowableFilters.Add "WARNING", 2
         dAllowableFilters.Add "INFO", 1
         dAllowableFilters.Add "DEBUG", 0
        nFilterLevel = dAllowableFilters("DEBUG")
        bFirstWrite = False
        bVerbose = False
        nIndentLevel = 0
        strIndentChar = vbTab
     End Sub
     '======================================================================================
     '
     '    IndentLevel Getter and Setter
     '    Notes:
     '        Set the level of indentation
     '
     '======================================================================================
     Public Property Let IndentLevel(nLvl)
         nIndentLevel = nlvl
     End Property
     Public Property Get IndentLevel
         IndentLevel = nIndentLevel
     End Property
     '======================================================================================
     '
     '    IndentChar Getter and Setter
     '    Notes:
     '        Set the character used for indentation default is vbTab
     '
     '======================================================================================
     Public Property Let IndentChar(strChar)
         strIndentChar = strChar
     End Property
     Public Property Get IndentChar
         IndentChar = strIndentChar
     End Property
     '======================================================================================
     '
     '    VerboseMode Getter and Setter
     '    Notes:
     '        Control the log path and filename
     '
     '======================================================================================
    Public Property Let VerboseMode(bMode)
        If UCase(CStr(bMode)) = "TRUE" Or UCase(CStr(bMode)) = "FALSE" Then bVerbose = bMode
    End Property
    Public Property Get VerboseMode
        VerboseMode = bVerbose
    End Property
     '======================================================================================
     '
     '    LogLoc Getter and Setter
     '    Notes:
     '        Control the log path and filename
     '
     '======================================================================================
    Public Property Let LogLoc(strName)
        Dim oFSO, oFile
        ' Open the log file create it if it does not exist
        strLogFile = strName
    End Property
    Public Property Get LogLoc
        LogLoc = strLogFile
    End Property
    '======================================================================================
    '
    '    AppendMode Getter and Setter
    '    Notes:
    '        Control the append behavior for the log
    '
    '======================================================================================
    Public Property Let AppendMode(bMode)
        bAppend = bMode
        If bAppend Then
            nAppendMode = 8
        Else
            nAppendMode = 2
        End If
    End Property
    Public Property Get AppendMode
        AppendMode = bAppend
    End Property
    '======================================================================================
    '
    '    FilterLevel
    '    Notes:
    '        Controls the level of logging to write to the log
    '
    '======================================================================================
    Public Property Let FilterLevel(strLvl)
         nFilterLevel = dAllowableFilters("DEBUG")
        If dAllowableFilters.Exists(UCase(strLvl)) Then
            nFilterLevel = dAllowableFilters(UCase(strLvl))
        End If
    End Property
    Public Property Get FilterLevel
        Dim strLevel
        For Each strLevel In dAllowableFilters.Keys()
            If nFilterLevel = dAllowableFilters(strLevel) Then
                FilterLevel = strLevel
                Exit Property
            End If
        Next
        FilterLevel = "UNKNOWN"
    End Property
    '======================================================================================
    '
    '    RotateLog
    '    Notes:
    '        Rotates the log file based on file size. The size in MB is passed to the
    '        function. If the log file is bigger than this, the log file will be renamed
    '        to the current name prepended with BU-. If this file already exists, the
    '        existing one will be deleted.
    '
    '======================================================================================
    Public Sub RotateLog(dblMB)
        Dim oFSO
        Dim oFile
        Dim strBUFile
       
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        Set oFile = oFSO.GetFile(strLogFile)
        'Check for an existing bu file and delete if there
        'See if the current logfile is over the limit
        If (oFile.Size/(2^20)) < dblMB Then
            'WScript.Echo "File Size = " & oFile.Size/(2^20) & " which is smaller than " & dblMB
            Set oFile = Nothing
            Set oFSO = Nothing
            Exit Sub
        End If
        LogLine INF, "Rotating the logfile. The cureent log is greater than " & dblMB & "Mb"
        strBUFile = oFile.ParentFolder & "\BU-" & oFile.Name
        'WScript.Echo strBUFile
        If oFSO.FileExists(strBUFile) Then
            LogLine INF, "There is an existing backup log named " & strBUFile & ". It will be deleted"
            oFSO.DeleteFile strBUFile, True
        End If
        'Rename the existing log
        LogLine INF, "Renaming the current log to " & strBUFile
        oFSO.MoveFile oFile.Path, strBUFile
        Set oFile = Nothing
        Set oFSO = Nothing
        'Log to the new Log
        LogLine INF, "Starting new logfile after log rotation. The backup log is named " & strBUFile       
    End Sub

    '======================================================================================
    '
    '    LogBlankLine
    '    Notes:
    '        Logs a blank line with no timestamp. This is really redundant because it Is
    '        the same as .LogNoStamp ""
    '
    '======================================================================================
    Public Sub LogBlankLine
        Dim oFSO, oFile
        If Not nFilterLevel = 4 THen
            If strLogFile = "" Then
                strLogFile = "C:\Temp\" & Split(WScript.ScriptName, ".")(0) & ".log"
            End If
            Set oFSO = CreateObject("Scripting.FileSystemObject")
            Set oFile = SmartOpenFile(strLogFile, nAppendMode, True)
            If bVerbose Then WScript.Echo ""
            oFile.WriteLine ""
            Set oFSO = Nothing
            oFile.Close
            Set oFile = Nothing
            If bFirstWrite = False Then
                'bAppend = True
                nAppendMode = 8
            End If
        End If
    End Sub
    '======================================================================================
    '
    '    LogNoStamp
    '    Notes:
    '        Logs a line without prepending a date time stamp. Useful for multiline output
    '        of a single chunk of information.
    '
    '======================================================================================
    Public Sub LogNoStamp(strLvl, strMsg)
        Dim oFSO, oFile   
        If strLogFile = "" Then
            strLogFile = "C:\Temp\" & Split(WScript.ScriptName, ".")(0) & ".log"
        End If
        If Not dAllowableFilters.Exists(UCase(strLvl)) Then
            strLvl = "DEBUG"
        End If
        If dAllowableFilters(UCase(strLvl)) >= nFilterLevel Then
            Set oFSO = CreateObject("Scripting.FileSystemObject")
            Set oFile = SmartOpenFile(strLogFile, nAppendMode, True)
            strMsg = String(nIndentLevel, strIndentChar) & strMsg
            If bVerbose Then WScript.Echo strMsg
            oFile.WriteLine strMsg
            Set oFSO = Nothing
            oFile.Close
            Set oFile = Nothing
            If bFirstWrite = False Then
            'bAppend = True
            nAppendMode = 8
        End If
        End If
    End Sub   
    '======================================================================================
    '   
    '    LogLine
    '    Notes:
    '        Logs a line of text prepending a date/time stamp and the severity level of the
    '        message.
    '
    '======================================================================================
    Public Sub LogLine (strLvl, strMsg)
        Dim oFSO, oFile   
        If strLogFile = "" Then
            strLogFile = "C:\Temp\" & Split(WScript.ScriptName, ".")(0) & ".log"
        End If
        If Not dAllowableFilters.Exists(UCase(strLvl)) Then
            strLvl = "DEBUG"
        End If
        If dAllowableFilters(UCase(strLvl)) >= nFilterLevel Then
            Set oFSO = CreateObject("Scripting.FileSystemObject")
            Set oFile = SmartOpenFile(strLogFile, nAppendMode, True)
            strMsg = GetLogTime & "[" & UCase(strLvl) & "] - " _
                    & String(nIndentLevel, strIndentChar) & strMsg
            If bVerbose Then WScript.Echo strMsg
            oFile.WriteLine strMsg
            Set oFSO = Nothing
            oFile.Close
            Set oFile = Nothing
            If bFirstWrite = False Then
            'bAppend = True
            nAppendMode = 8
        End If
        End If
    End Sub
    '======================================================================================
    '
    '    GetLogTime
    '    Notes:
    '        Returns a date/time stamp in the format YYYYMMddmmss
    '
    '======================================================================================
    Private Function GetLogTime()
        Dim strNow
        strNow = Now()
        GetLogTime = Year(strNow) & "-" & Pad(Month(strNow), 2, "0", True) & "-"  _
                   & Pad(Day(strNow), 2, "0", True) & "-" & Pad(Hour(strNow), 2, "0", True) _
                   & ":" & Pad(Minute(strNow), 2, "0", True) _
                   & ":" & Pad(Second(strNow), 2, "0", True)
    End Function 'GetLogTime()
    '======================================================================================
    '
    '    Pad
    '    Notes:
    '        Pads a string to a specified length using the specified character by appending
    '        or prepending.
    '
    '======================================================================================
    Private Function Pad(strText, nLen, strChar, bFront)
            Dim nStartLen
            If strChar = "" Then
                strChar = "0"
            End If
            nStartLen = Len(strText)
            If Len(strText) >= nLen Then
                Pad = strText
            Else
                If bFront Then
                    Pad = String(nLen - Len(strText), strChar) & strText
                Else
                    Pad = strText & String(nLen - Len(strText), strChar)
                End If
            End If
    End Function
    '======================================================================================
    '
    '    SmartOpenFile
    '    Notes:
    '        Opens a file building any directory structure that is required.
    '
    '======================================================================================
    Private Function SmartOpenFile(strPath, nMode, bCreate)
        'Creates the path to the file if bCreate = True
        Dim arrPath, i, oFSO, nErr, strErr
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        arrPath = Split(strPath, "\")
        If UBound(arrPath) < 1 Then
            'Invalid path
            Set SmartOpenFile = Null
            Exit Function
        End If
        If bCreate Then
            strPath = arrPath(0)
            For i = 1 To UBound(arrPath) - 1
                strPath = strPath & "\" & arrPath(i)
                On Error Resume Next
                    oFSO.CreateFolder(strPath)
                    nErr = Err.Number : strErr = Err.Description
                    LogLine "DEBUG", "In SmartOpenFile creating " & strPath & " " & nErr _
                            & ") - " & strErr
                On Error Goto 0
            Next
        End If
        strPath = Join(arrPath, "\")
        On Error Resume Next
            Set SmartOpenFile = oFSO.OpenTextFile(strPath, nMode, bCreate)
        On Error Goto 0
    End Function       
End Class

< Message edited by ebgreen -- 8/15/2005 6:47:28 AM >
 
 
Post #: 1
 
 RE: Logger Class - 3/19/2007 6:38:17 AM   
  jeffbrownjr

 

Posts: 3
Score: 0
Joined: 3/19/2007
Status: offline
I tried using the logger class and I am not having much luck.

Below is how I am using. DO you have any exmples. The log file is not getting created. I tried passing in bad arguements into a public function to see if would throw an error and it did.

<?xml version="1.0" encoding="utf-8" ?>
<package>
<job id="testLogger">
 <?job error="false" debug="false" ?>
 <description>
 </description>
 <script language="VBScript" src="C:\MyScripts\Scripts\Helpers\Logger.vbs"/>
 <script language="VBScript">
<![CDATA[
Dim Source
Source=Split(WScript.ScriptName, ".")(0)
Main() 'goto Main

Sub Main() 'Start here
'*********************************************************
' Name: Main
' Purpose: Start of program
' Inputs: N/A
' Returns: N/A
'*********************************************************
Set oLogger = New Logger
oLogger.LogBlankLine
oLogger.LogLine Warning, "Test Message"
oLogger.LogLine 2, "Test Message"
'oLogger.LogLine 2 'Purposely pass in wrong # of arguments to see if the class is even working. Throws error as expected.
End Sub
]]>
 </script>
</job>
</package>

(in reply to ebgreen)
 
 
Post #: 2
 
 RE: Logger Class - 3/19/2007 6:42:11 AM   
  ebgreen


Posts: 4595
Score: 29
Joined: 7/12/2005
Status: offline
I have to say that I do not use this in an ASP environment so there may be a permissions issue going on here.

_____________________________

"... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
http://www.visualbasicscript.com/m_47117/tm.htm

(in reply to jeffbrownjr)
 
 
Post #: 3
 
 RE: Logger Class - 3/19/2007 6:47:15 AM   
  jeffbrownjr

 

Posts: 3
Score: 0
Joined: 3/19/2007
Status: offline
Not an ASP environment. This is a vbscript but with the extension of a WSF WHICH allows me to include the Logger class(I copied the code and put in a vbs file named Logger.vbs) I know you mentioned using as a WSC but when I copied the code it did not register. It threw errors. I figured since I am use to the WSF file to just include the file. Do you have any examples of how to use?

Thanks again!
JB

(in reply to ebgreen)
 
 
Post #: 4
 
 RE: Logger Class - 3/19/2007 6:50:49 AM   
  ebgreen


Posts: 4595
Score: 29
Joined: 7/12/2005
Status: offline
Well, I use it just about exactly the way you are using it. Unless you have defined Warning somewhere else, this is not valid:

oLogger.LogLine Warning, "Test Message"

_____________________________

"... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
http://www.visualbasicscript.com/m_47117/tm.htm

(in reply to jeffbrownjr)
 
 
Post #: 5
 
 RE: Logger Class - 3/19/2007 6:51:51 AM   
  ebgreen


Posts: 4595
Score: 29
Joined: 7/12/2005
Status: offline
Here is an example of it's use:

Set oLog = New Logger

oLog.LogLine "WARN", "This is a warning"

_____________________________

"... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
http://www.visualbasicscript.com/m_47117/tm.htm

(in reply to ebgreen)
 
 
Post #: 6
 
 RE: Logger Class - 3/19/2007 8:02:40 AM   
  jeffbrownjr

 

Posts: 3
Score: 0
Joined: 3/19/2007
Status: offline
So I tried what you recommened and actually did that before...so it must be a WSF setup issue or the way I use it. So I took the exact code verbatim from post and copied to another script file with a WSC extension and tried to register. It throws errors. SO mayb there are some setup issues with my WSC or something that needs to be included other than the code you posted.

Again any help is appreciated...sorry for bugging you on this. Thanks again!

(in reply to ebgreen)
 
 
Post #: 7
 
 RE: Logger Class - 3/19/2007 8:12:48 AM   
  ebgreen


Posts: 4595
Score: 29
Joined: 7/12/2005
Status: offline
Well there is a lot more to registering a COM object than just saving a script with a .wsc extension. I would suggest some research on that.

_____________________________

"... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
http://www.visualbasicscript.com/m_47117/tm.htm

(in reply to jeffbrownjr)
 
 
Post #: 8
 
 RE: Logger Class - 3/21/2007 4:23:00 AM   
  benbrazis

 

Posts: 2
Score: 0
Joined: 3/21/2007
Status: offline
This is a great logger class and I implemented. Works great...I have a question or two.

Is this the latest logger class? I noticed you commented using xml as a config file for some of the properties. If you have not done so then I will look at doing one for myself. I see a need for a config file especially with the logging levels. It woul dbe nice to change config file versus the script.

Also, not sure if you have also done or can provide guidance but I do not always log to the same log file for every script. I noticed when strLogFile is Null it uses default of where script is run.

If you do the following:

Set myLog = New Log
myLog.LogLoc=test

Since the value is not null it will create the log file in the c:\TEMP. My question is how would I go about specifying the name of a log file in a script that tells the logger class to log to a specific file.

For example,
Set myLog = New Log
myLog.LogLoc=DBExtracter.log

Override the default and set a name for a log of where the messages are written
Great logger class and please let me know if you have updated or have any ideas with overriding the default log file and setting a name for a file.

Thank You.

(in reply to ebgreen)
 
 
Post #: 9
 
 RE: Logger Class - 3/21/2007 4:34:11 AM   
  ebgreen


Posts: 4595
Score: 29
Joined: 7/12/2005
Status: offline
I have not had time to update the class. To specify a file to log to you simply set the logloc property.

_____________________________

"... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
http://www.visualbasicscript.com/m_47117/tm.htm

(in reply to benbrazis)
 
 
Post #: 10
 
 RE: Logger Class - 3/21/2007 5:42:27 AM   
  benbrazis

 

Posts: 2
Score: 0
Joined: 3/21/2007
Status: offline
hmm..I will take a look.

Because when I the following two commands:

Set myLog = New Log
myLog.LogLoc=DBExtracter.log

From the class file....Based on the code no matter what I put in the LogLoc property the below statement ends up not being NULL and and creates a logfile in c:\temp\ScriptName.log. IN this case when I set DBExtracter.log it will always create a log in the c:\temp\ScriptName.log and not DBExtractor.log. Am I missing something.

If strLogFile = "" Then
           strLogFile = "C:\Temp\" & Split(WScript.ScriptName, ".")(0) & ".log"
End If


(in reply to ebgreen)
 
 
Post #: 11
 
 RE: Logger Class - 3/21/2007 7:10:12 AM   
  ebgreen


Posts: 4595
Score: 29
Joined: 7/12/2005
Status: offline
This :

myLog.LogLoc=DBExtracter.log


Is not valid

This is:

myLog.LogLoc="DBExtracter.log"

_____________________________

"... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
http://www.visualbasicscript.com/m_47117/tm.htm

(in reply to benbrazis)
 
 
Post #: 12
 
 
 
  

If you found our site useful please link to us <a href="http://www.visualbasicscript.com">VisualBasicScript.com</a>.
All Forums >> [Scripting] >> Post a VBScript >> Logger Class Page: [1]
Jump to:





New Messages No New Messages
Hot Topic w/ New Messages Hot Topic w/o New Messages
Locked w/ New Messages Locked w/o New Messages
 Post New Thread
 Reply to Message
 Post New Poll
 Submit Vote
 Delete My Own Post
 Delete My Own Thread
 Rate Posts