- Debugging: Helps identify where and why a script failed
- Auditing: Keep a record of actions taken by automated jobs
- Monitoring: Send logs to IT teams or systems
-
@ECHO OFF REM Redirect stdout and stderr to log.txt MYCOMMAND > log.txt 2>&1
This captures everything the command prints (success or error).
-
Use
>>instead of>to preserve previous log content:@ECHO OFF ECHO Starting task... >> log.txt MYCOMMAND >> log.txt 2>&1 ECHO Task completed. >> log.txt
-
Wrap your entire script in a block and redirect it:
@ECHO OFF ( ECHO ===== Script Started at %DATE% %TIME% ===== DIR C:\SomeFolder XCOPY C:\Data D:\Backup /E /I ECHO ===== Script Finished at %DATE% %TIME% ===== ) >> script.log 2>&1
-
Use this format to prepend a timestamp to each log message:
@ECHO OFF SET LOGFILE=script.log CALL :Log "Script started" DIR "C:\Fake\Path" >> %LOGFILE% 2>&1 CALL :Log "Completed directory check" GOTO :EOF :Log ECHO [%DATE% %TIME%] %~1 >> %LOGFILE% EXIT /B
π You can reuse
:Logthroughout the script to make logging consistent. -
Sometimes it's useful to keep clean logs:
MYCOMMAND > output.log 2> error.log
This allows you to parse success and failure info independently.
-
Prevent log files from growing indefinitely:
@ECHO OFF SET LOGFILE=script.log IF EXIST %LOGFILE% ( REN %LOGFILE% script_%DATE:/=_%_%TIME::=_%.log ) ECHO [LOG] New log started at %DATE% %TIME% > %LOGFILE%
This renames the old log file with a timestamp.
-
@ECHO OFF SET LOGFILE=backup.log CALL :Log "Backup started" XCOPY C:\Important D:\Backup /E /I >> %LOGFILE% 2>&1 IF ERRORLEVEL 1 ( CALL :Log "ERROR: Backup failed!" ) ELSE ( CALL :Log "Backup completed successfully." ) CALL :Log "Script finished." GOTO :EOF :Log ECHO [%DATE% %TIME%] %~1 >> %LOGFILE% EXIT /B
| Technique | Example | Purpose |
|---|---|---|
| Redirect stdout + stderr | CMD > log.txt 2>&1 |
Capture all output |
| Append logs | >> log.txt |
Preserve previous logs |
| Add timestamps | [%DATE% %TIME%] in ECHO |
Time tracking |
| Use logging subroutine | CALL :Log "Message" |
Clean reusable logging |
| Log rotation | REN log.txt old_timestamp.log |
Manage large logs |
| Separate logs | > output.log 2> error.log |
Organized debugging |