Write to a single log file in vbscript

拈花ヽ惹草 提交于 2019-12-06 11:27:24

Your logging function has an argument for the full path to the log file, so you should define the filename once at the beginning of your code and use that name throughout the entire script (I'd recommend doing the same for the FileSystemObject instance). Remove all code defining the filename from the logging function.

Set objFSO = CreateObject("Scripting.FileSystemObject")

logfolder    = "C:\Users\TEMPPAHIR\LearnVB\Logfolder"
ScriptName1  = Replace(Wscript.ScriptName, ".vbs", "")
sLogFileName = ScriptName1 & "_" & Date & "_" & Hour(Now) & "-" & _
               Minute(Now) & "-" & Second(Now) & "_log.txt"
logfile = objFSO.BuildPath(logfolder, sLogFileName)

Sub WriteLogFileLine(sLogFileNameFull, sLogFileLine)
    Set MyLog = objFSO.OpenTextFile(sLogFileNameFull, 8, True)
    MyLog.WriteLine Now & vbTab & "-" & vbTab & sLogFileLine
    MyLog.Close
End Sub

...
WriteLogFileLine logfile, "some log line"
...

You may want to take a look at the logger class I wrote a couple years ago (if you'll forgive the shameless plug). It might help simplify your log handling. Copy the class code into your script and you can do logging like this:

logfolder = "C:\Users\TEMPPAHIR\LearnVB\Logfolder"
logname   = Replace(Wscript.ScriptName, ".vbs", "") & "_" & Date & "_" & _
            Hour(Now) & "-" & Minute(Now) & "-" & Second(Now) & "_log.txt"
logfile   = objFSO.BuildPath(logfolder, logname)

Set clog = New CLogger
clog.LogToConsole = False
clog.LogFile = logfile      'open log
clog.IncludeTimestamp = True

...
clog.LogInfo "some message"
clog.LogError "other message"
...

clog.LogFile = ""           'close log

The log file is closed automatically when the script terminates (if it wasn't already closed in the code before).

Jake

I created this to do what you have asked. I use it to keep logs as the scripts run via a scheduled task.

Dim FSO, OutPutFile
Dim DateTimeString
Dim LogDirectory, LogFileName, MaxLogFileSize

Set FSO = CreateObject("Scripting.FileSystemObject")

'The Log File Directory
LogDirectory = "E:\LogFiles"

'The name of the log file for this script
LogFileName = "archive.log"

'The maximun Log file Size in Megabytes
MaxLogFileSize = 5

SetUpLogFile()

DateTimeString = GetCurrentDateTimeString
OutPutFile.WriteLine(DateTimeString + " " + "----------------------------------")
DateTimeString = GetCurrentDateTimeString
OutPutFile.WriteLine(DateTimeString + " " + "Writing to the log file.")

'=============================================================
Function SetUpLogFile()

'First Thing: Check if log file exists, and if it exceeds max Size
If (FSO.FileExists(LogDirectory + "\" + LogFileName)) Then

    Dim CurrentLogFile, CurrentLogFileSize
    Set CurrentLogFile = FSO.GetFile(LogDirectory + "\" + LogFileName)
    CurrentLogFileSize = CurrentLogFile.Size

    'Convert Size to MB
    CurrentLogFileSize = ((CurrentLogFileSize \ 1024) \ 1024)

    'Check if log file exceeds maximum size
    If (CurrentLogFileSize >= MaxLogFileSize) Then

        'Get a unique string to re-name backup log with
        Dim LogDateTimeString
        LogDateTimeString = cstr(Year(date)) + "_" + _
        + cstr(Month(date)) + "_" _
        + cstr(Day(date)) + "__" _
        + cstr(Hour(time)) + "_" _
        + cstr(Minute(time)) + "_" _
        + cstr(Second(time))

        'rename old log file
        CurrentLogFile.Name = LogDateTimeString + "_" + CurrentLogFile.Name
        'create new log file
        Set OutPutFile = FSO.OpenTextFile(LogDirectory + "\" + LogFileName ,8 , True)

    Else
        'Just append to the log file if it is not over the max size
        Set OutPutFile = FSO.OpenTextFile(LogDirectory + "\" + LogFileName ,8 , True)

    End If

Else
    'Create Log File if it does not yet exist
    Set OutPutFile = FSO.OpenTextFile(LogDirectory + "\" + LogFileName ,8 , True)

End If

'Output to a window if the log file cannot be used
'All errors for any other condition will get logged to the
'log file
If Err.Number <> 0 Then

   wscript.echo "ERROR: Error creating or writing to log file: " + _
      LogDirectory + "\" + LogFileName + vbcrlf + _
      "Please fix the problem as the script will now quit and cannot continue." +  _
      vbcrlf + vbcrlf + _
      "Error information:" + vbcrlf + _
      "Error Number: " + cstr(Err.Number) + vbcrlf + _
      "Source: " +  Err.Source + vbcrlf + _
      "Description: " +  Err.Description

    wscript.quit

End If

End Function

'=============================================================

Function GetCurrentDateTimeString()

'Build Date Time String For Logging
Dim tmp, ReturnDateString

tmp = Right("00" & Month(Now()), 2)
ReturnDateString = ReturnDateString + tmp + "/"

tmp = Right("00" & Day(Now()), 2)
ReturnDateString = ReturnDateString + tmp + "/" + cstr(Year(date)) + " "

tmp = Right("00" & Hour(Now()), 2)
ReturnDateString = ReturnDateString + tmp + ":"

tmp = Right("00" & Minute(Now()), 2)
ReturnDateString = ReturnDateString + tmp + ":"

tmp = Right("00" & Second(Now()), 2)
ReturnDateString = ReturnDateString + tmp + " -"

GetCurrentDateTimeString = ReturnDateString

End Function
'=============================================================
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!