Thursday 29 October 2009

Logfile rotation by CMD/BAT

The script below allows to rotate file (e.g.: logfiles). By default, the length of rotation is 5. It means that this script rotates some file no more than for 5 times.

Let's consider the permanently growing file of some application named as something.log and we'd like to keep records in this file for the long time as much as possible. But for some reason this file is cleaning up periodically or a size of the file affects on the application's performance.

The recent records are available from the file something.log and the previously saved records are available under the name something.log.1, etc until the something.log.5. After the following rotation the content of the last file will be lost and replaced by the content of the previous file (something.log.4 will be copied to the something.log.5) and the first file something.log will be copied to the something.log.1. At the same time the something.log will be truncated.

rotate something.log 10
If you'd like to increase the rotation length you can pass the additional numeric parameter to change it. The example above shows how to modify the length of the rotation until 10.
@echo off

if    "%~1" == ""   goto help
if /i "%~1" == "/h" goto help

setlocal

if not "%~2" == "" set /a rotate_n=%~2 2>nul
if not defined rotate_n set rotate_n=5
if %rotate_n% lss 5 set rotate_n=5

:: set rotate_c=copy /y
set rotate_0=copy nul
set rotate_c=move /y

set rotate_i=%rotate_n%

:loop_redo
set /a rotate_i-=1
if %rotate_i% == 0 goto loop_break

if exist "%~1.%rotate_i%" %rotate_c% "%~1.%rotate_i%" "%~1.%rotate_n%"

set /a rotate_n-=1
goto loop_redo
:loop_break

%rotate_c% "%~1" "%~1.1" && %rotate_0% "%~1"

endlocal
goto :EOF

:help
echo.Usage:
echo.    %~n0 FILENAME [NUMBER]
goto :EOF

No comments:

Post a Comment