问题
I have written a small sub to create log file
sub WriteLogFileLine(sLogFileNameFull, sLogFileLine)
logfolder = "C:\Users\TEMPPAHIR\LearnVB\Logfolder\"
ScriptName1 = Replace(Wscript.ScriptName, ".vbs", "")
sLogFileName = ScriptName1 & "_" & date & "_" & hour(now) & "-" & minute(now) & "-" & second(now) & "_log.txt"
sLogFileNameFull = logfolder & sLogFileName
dateStamp = Now()
Set MyLog = objFSO.OpenTextFile(sLogFileNameFull, 8, True)
MyLog.WriteLine(cstr(dateStamp) + vbTab + "-" + vbTab + sLogFileLine)
MyLog.Close
Set MyLog = Nothing
end sub
I am calling this sub multiple times in my main vb script function to write messages to the log file this way,
'******************************************************************************
'* Main Script Body
'******************************************************************************
Function DoAllWork
On Error Resume Next
Dim sFile, FromDate, ToDate, FromLocation, MyFile, objFolder, Filename, objArgs, FilenameReq, line, inFile, outFile, outputLines
Dim FromdateFile, FromdateFileReq, lineDt, CFileDt, CopyFiles, line1, CFile, resultX, stringY, resultY, resultfinal, outputLine
Dim FromFolderList, ToLocationArg, outputLines1, Arch, ToLocationArg1, writeOutput
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
Set MyLog = objFSO.OpenTextFile(sLogFileNameFull, 8, True)
If WScript.Arguments.Count = 4 Then
Call WriteLogFileLine(sLogFileNameFull, "Total number of arguments passed are " & WScript.Arguments.Count & " and they are as follows : ")
'Parameter1, begin with index0
FromDate = WScript.Arguments(0)
'Parameter2
ToDate = WScript.Arguments(1)
'Parameter3
FromLocationArg = WScript.Arguments(2)
'Parameter4
ToLocation = WScript.Arguments(3)
Else
Call WriteLogFileLine(sLogFileNameFull, "Error, Must pass 4 arguments to the script !" & vbcrlf)
Wscript.quit
End if
Call WriteLogFileLine(sLogFileNameFull, "First Argument, the date folder FROM where files needs to be copied is : " & FromDate & vbcrlf)
Call WriteLogFileLine(sLogFileNameFull, "Second Argument, the date folder TILL where files needs to be copied is : " & ToDate & vbcrlf)
MyLog.Close
Set MyLog = Nothing
DoAllWork = Err.Number
Call WriteLogFileLine(sLogFileNameFull, "End of the script !" & vbcrlf)
End Function
'******************************************************************************
'* End of the script.
'******************************************************************************
But while executing the script sometimes there are multiple log files getting generated, I guess everytime the timestamp is changing it is creating a new log file and writting log in that file.
QUE : I want all the log to be written to one single log file whose timestamp is picked up at the beginning of my script. Please help !!
回答1:
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).
回答2:
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
'=============================================================
来源:https://stackoverflow.com/questions/34132848/write-to-a-single-log-file-in-vbscript