Skip to content

Latest commit

Β 

History

History
executable file
Β·
125 lines (89 loc) Β· 3.33 KB

File metadata and controls

executable file
Β·
125 lines (89 loc) Β· 3.33 KB

πŸ“˜ Logging Script Output in Batch Scripting

  • 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

πŸ”Ή Basic Logging Techniques

  1. πŸ“₯ Redirect All Output to a File

    @ECHO OFF
    REM Redirect stdout and stderr to log.txt
    MYCOMMAND > log.txt 2>&1

    This captures everything the command prints (success or error).

  2. πŸ“’ Append Instead of Overwrite

    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

  1. Logging the Entire Script

    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
  2. Add Timestamps to Each Log Entry

    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 :Log throughout the script to make logging consistent.

  3. Separate Output and Error Logs

    Sometimes it's useful to keep clean logs:

    MYCOMMAND > output.log 2> error.log

    This allows you to parse success and failure info independently.

  4. Rotating Logs (Simple Method)

    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.

  5. Example: Logging Backup Script

    @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

βœ… Summary Table

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