Logging Whole Batch File Execution

Thanks to http://makemsi-manual.dennisbareis.com/logging_whole_batch_file_execution.htm

This is a simple approach which can can log the complete execution of a batch file. The batch file can use the “echo” command (I’d recommend outputting a prefix of “[%date% %time%]”) to display progress information.

Some care and testing is required if long running programs are spawned (to ensure you can access the file. The batch below demonstrates a number of approaches to building a suitable log filename.

As written its assumed that no parameters are passed, but you could easily alter this to use an environment variable or any other flag. What it does is detect that its started and then restarts itself while redirecting the output making it a relatively trivial process to add good logging to any existing batch files while also being very handy for schedules etc.

The following demonstrates the process (just add to the front of the batch file):

@echo off
setlocal

@REM *** START: Turns logging on ***
if "%~1" == "NOWLOGGING" goto NowLogging
    set SchedulesLogFile=%TEMP%\%~n0 - %date:/=-% %time::=_%.txt
    set SchedulesLogFile=%TEMP%\%~n0 - %RANDOM%.txt
    set SchedulesLogFile=%TEMP%\%~n0.txt
    %0 "NOWLOGGING" > "%SchedulesLogFile%" 2>&1
    goto :EOF
:NowLogging
@REM *** END: Turns logging on ***

@rem Guts of batch file...
echo [%date% %time%] starting...
echo *** start of actual batch file...
...
echo *** end of actual batch file...
echo [%date% %time%] ending...