In my VBScript work I often create log files, either for debugging or as a main component of the script. I’m fond of a format like this:
6/15/2000 8:49:29 AM – Administrator Administrator from LISBON
6/15/2000 8:49:29 AM – Account Change Aborted.
In a batch file I could never figure out how to get this same type of result. You can use commands like date /t and time /t to get a date stamp or time stamp but combining the two on one line was practically impossible. Until now. The hack I came up with was to use the FOR command to pass the result of the date /t and time /t commands. Take a look at this expression:
for /f “tokens=*” %i in (‘date /t’) do @for /f “tokens=*” %j in (‘time /t’) do @echo %i%j “Logging has begun”
Normally you think of using FOR /f to process a list but there’s no rule saying the list can’t consist of only one item. That’s what is happening here. The first FOR command produces the same result as simply running date /t. The advantage here is that I can save the output as %i and also call another FOR command to do the same thing. I can then use the DO portion of the second FOR command to create my log file entry. Here’s the result you get from this command:
Mon 11/20/2006 08:51 AM “Logging has begun”
I can’t get the seconds component like I can in VBScript, but I can live with that.
The next step is to put this is a function of sorts that I can use in my batch files. Here is a sample script that uses this routine:
@echo off
::LogEntryDemo.bat
REM Jeffery Hicks jhicks@sapien.com
REM This script doesn’t really do much other than demonstrate
REM how to use the LogEntry routine to create a
REM log file with a timestamped entry for each line.
REM define path to log file
set myLog=e:\temp\log.txt
REM Delete the logfile if it already exists.
if exist %myLog% del %myLog% >NUL
Echo Working…
REM When sending something to the log routine, enclose the
REM message in quotes.
Call :LogEntry “Starting %0”
Call :LogEntry “Running DIR”
DIR %windir%\*.* /s >NUL
Call :LogEntry “Finished DIR”
Call :LogEntry “Sleeping for 30 seconds”
Sleep 30
Call :logEntry “Getting NETSTAT information”
REM Sending results of a NETSTAT command to the log. Notice
REM I’m enclosing the output in quotes. Otherwise, only the
REM first part of the output would be recorded.
for /f “tokens=*” %%t in (‘netstat ^|find /i “TCP”‘) do @Call :LogEntry “%%t”
Call :LogEntry “Finishing logging and opening %myLog%”
REM Display the log
start Notepad %MyLog%
GOTO :EOF
:LogEntry
REM Output will be like: Wed 11/15/2006 05:27 PM “Starting LogEntryDemo.bat”
for /f “tokens=*” %%i in (‘date /t’) do @for /f “tokens=*” %%j in (‘time /t’) do @echo %%i%%j %1 >>%myLog%
GOTO :EOF
:EOF
Whenever I want to log something I call :LogEntry and pass a parameter for whatever message I want logged. The value must be enclosed in quotes so it can be treated as a single entry. Again, a compromise that I can live with.
Let me know what you think of this solution.