I have this common problem where my servers generates about 5-6 megs of log file every day filling up the disk, and following dos script to delete old logs have been quite handy
:: Iterate files alphabetically at specified folder and keep a maximum of N to :: avoid filling disk space. Called by run.bat :: This script takes 3 arguments off setlocal ENABLEDELAYEDEXPANSION set FOLDER=%1 set FILEPREFIX=%2 set LIMIT=%3 echo Accessing %FOLDER% cd %FOLDER% set /a COUNT=0 for /f "tokens=*" %%f in ('dir /b /a-d-h-s /o-n %FILEPREFIX%*') do ( set /a COUNT=COUNT+1 if !COUNT! GTR %LIMIT% ( echo deleting %%f del /f /q %%f ) ) endlocal
I place the script above in C:filecleanerdeletefiles.bat. This script iterates a folder alphabetically and keep only specified amount of files. I then created a second script to be called by task scheduler
:: Called by task scheduler. This script calls deletefiles.bat over each file path prefix :: :: Example: :: deletefiles.bat c:logrotate-test access.log 3 :: means keep maximum 3 files (sorted alphabetically) starting with access.log off deletefiles.bat "C:apache-tomcat-6.0.35" catalina 7 deletefiles.bat "C:apache-tomcat-6.0.35" commons-daemon 7 deletefiles.bat "C:apache-tomcat-6.0.35" host-manager 7 deletefiles.bat "C:apache-tomcat-6.0.35" localhost 7 deletefiles.bat "C:apache-tomcat-6.0.35" manager 7 deletefiles.bat "C:apache-tomcat-6.0.35" tomcat6-stderr 7 deletefiles.bat "C:apache-tomcat-6.0.35" tomcat6-stdout 7
I put this script in C:filecleanerrun.bat. As you can see it calls deletefiles.bat several times to clean my tomcat log files. The script uses following arguments:
- The folder where the log files exist
- The prefix of the log files
- How many latest files should be kept
It’s important to note this will only work if the files alphabetical ordering implies their age. This typically works best if the files pattern has a yyyy-MM-dd format (or similar at the end):
stdout.2013-12-04.log stdout.2013-12-05.log stdout.2013-12-06.log stdout.2013-12-07.log
Finally to run this automatically every 3.30am in the morning I created a task scheduler with following action: