How to Create a Log Rotation Script in Batch Script
Applications and services often write to log files continuously. If left unmanaged, these files can grow to an enormous size, consuming disk space and becoming difficult to open and analyze. Log rotation is the essential process of archiving the current log file, creating a new empty one, and deleting very old archives to keep the process manageable.
This guide will teach you how to create a complete, robust log rotation script using standard, built-in Windows commands. You will learn how to combine file operations (REN), date variables (%DATE%), and the powerful FORFILES utility to create a fully automated solution that can be run from the Windows Task Scheduler.
The Goal: The Three Steps of Log Rotation
A complete log rotation process consists of three main tasks:
- Archive: The current, active log file (e.g.,
app.log) is renamed to include a timestamp (e.g.,app_2023-10-27.log). This takes it "out of rotation." - Recreate: A new, empty file with the original name (
app.log) is created so the application can immediately start writing to it again without interruption. - Purge: Very old archive files (e.g., older than 30 days) are deleted to reclaim disk space.
The Core Commands Used in This Script
REN(Rename): Used to perform the "Archive" step.%DATE%Variable: Used to create the timestamp for the archived log's filename.TYPE NUL > ...: A standard trick to create a new, empty file for the "Recreate" step.FORFILES: The perfect tool for the "Purge" step. It can select files based on their age and execute a command on them.
The Full Log Rotation Script
This is a complete, reusable, and configurable script. You can change the variables at the top to match your environment.
@ECHO OFF
SETLOCAL
REM --- Configuration ---
SET "LogFile=C:\MyApp\Logs\app.log"
SET "ArchiveFolder=C:\MyApp\Logs\Archive"
SET "RetentionDays=30"
ECHO --- Log Rotation Script ---
ECHO.
ECHO Log File: "%LogFile%"
ECHO Archive To: "%ArchiveFolder%"
ECHO Retention: %RetentionDays% days
ECHO.
REM --- Step 0: Pre-flight checks ---
IF NOT EXIST "%LogFile%" (
ECHO [INFO] The primary log file does not exist. Nothing to rotate.
GOTO :PurgeOldLogs
)
MKDIR "%ArchiveFolder%" 2>NUL
REM --- Step 1: Archive the current log file ---
ECHO Archiving the current log file...
REM Create a timestamp in YYYY-MM-DD format (for US locale)
SET "Timestamp=%DATE:~10,4%-%DATE:~4,2%-%DATE:~7,2%"
SET "ArchiveName=%Timestamp%_app.log"
REN "%LogFile%" "%ArchiveName%"
MOVE "%ArchiveFolder%\%ArchiveName%" "%ArchiveFolder%" > NUL 2> NUL
move "%ArchiveName%" "%ArchiveFolder%"
ECHO Archived to: "%ArchiveFolder%\%ArchiveName%"
ECHO.
REM --- Step 2: Recreate the empty log file ---
ECHO Recreating the primary log file for the application...
TYPE NUL > "%LogFile%"
ECHO.
:PurgeOldLogs
REM --- Step 3: Purge old archive files ---
ECHO Purging archive files older than %RetentionDays% days...
REM /P: Path, /M: Mask, /D: Date, /C: Command
FORFILES /P "%ArchiveFolder%" /M "*.log" /D -%RetentionDays% /C "cmd /c del @path"
ECHO.
ECHO --- Log rotation complete ---
ENDLOCAL
How the script works:
- Configuration: The variables at the top make the script easy to adapt.
- Pre-flight Checks: The script first checks if the log file even exists. If not, there's nothing to rotate, but it will still try to purge old logs. It also ensures the archive folder exists with
MKDIR. - Timestamp Creation:
SET "Timestamp=%DATE:~10,4%-%DATE:~4,2%-%DATE:~7,2%"is a string substitution trick that slices up the%DATE%variable (e.g.,Fri 10/27/2023) to reformat it into the sort-friendly2023-10-27. - Archive (
RENandMOVE): The script renamesapp.logto2023-10-27_app.logand then moves it into the archive folder. - Recreate (
TYPE NUL >): It instantly creates a new, emptyapp.logso the application has a file to write to. - Purge (
FORFILES): This is the cleanup command./P "%ArchiveFolder%": Sets the path to search./M "*.log": Sets the file mask to only look at log files./D -%RetentionDays%": This is the date filter.-30means "30 days ago or older."/C "cmd /c del @path": This is the command to run on every file that matches the criteria.@pathis a variable that represents the full path to the found file.
CRITICAL: Handling the "File In Use" Problem
This is the number one reason a log rotation script will fail. If the application is still running, it will have a lock on app.log, and the REN command will fail with an "Access is denied" or "The process cannot access the file because it is being used by another process" error.
The ONLY reliable solution is to stop the application or service before running the rotation script, and then restart it immediately after.
The Correct Workflow
ECHO Stopping the application service...
NET STOP MyAwesomeAppService
ECHO Running the log rotation script...
CALL C:\Scripts\log_rotation.bat
ECHO Starting the application service again...
NET START MyAwesomeAppService
This entire sequence should be what you put into your scheduled task.
Common Pitfalls and How to Solve Them
- Permissions: The script may require administrator rights to stop/start services or to write to certain directories like
C:\ProgramData. Solution: Run the script as an administrator or as the service account user. - Date Format (
%DATE%): The date parsing (%DATE:~10,4%...) is dependent on the system's regional settings. The example is for a US format. For an internationally-safe method, it's better to useWMICor PowerShell to get the date components.
Practical Application: Running the Script with Task Scheduler
The ideal way to use this script is to run it automatically.
- Open Task Scheduler.
- Create a new basic task.
- Set the Trigger to run daily, typically at a time of low activity (e.g., midnight).
- Set the Action to "Start a program" and point it to a "launcher" batch script that implements the "Stop-Rotate-Start" logic.
- Configure the task to run with the highest privileges.
Conclusion
A log rotation script is an essential tool for system maintenance. By combining a few powerful, built-in commands, you can create a fully automated solution.
Key takeaways for a robust script:
- Follow the Archive, Recreate, Purge logic.
- Use
RENfor archiving,TYPE NUL >for recreating, andFORFILESfor purging. - CRITICAL: You must stop the service or application that is writing to the log file before you attempt to rotate it to avoid "file in use" errors.
- Use Windows Task Scheduler to run your script on a regular basis.