We have a process that creates a log file, and we want to archive the log files every day. The easiest way to rotate these logs is to create a batch file that copies the log file to a filename that includes the date of the file as the file name. Now, we can’t really rely on Perl or Cygwin being on this box, so we need to use (gasp!) a batch file. We are going to use For with %~t to expand the date/time of the file. For more info on FOR in Windows batch files, type for /?. Note that the options we are using will not work on NT. Our batch file:
FOR %%V IN (%1) DO FOR /F "tokens=1-3 delims=/ " %%A IN ("%%~tV") DO copy "%%V" %%A%%B%%C%%~xV |
A little explanation. %1 is our file passed from the command line. We only want three tokens, the year, month, and day. We want to delimit on / or space. This is because the date is in the format 00/00/00. Our three tokens, then, will be the individual pieces of the date returned from %%~tV. We then copy these to the new archived file. To use this, put the above text in a batch file, say logrotate.bat. Then, just run logrotate filename, where filename is the name of the log file you want to archive. For instance:
C:\lg>dir Volume in drive C has no label. Volume Serial Number is F484-97B4 Directory of C:\lg 03/12/2003 05:06a <DIR> . 03/12/2003 05:06a <DIR> .. 03/12/2003 04:37a 96 logrotate.bat 1 File(s) 96 bytes 2 Dir(s) 749,436,928 bytes free C:\lg>type logrotate.bat FOR %%V IN (%1) DO FOR /F "tokens=1-3 delims=/ " %%A IN ("%%~tV") DO copy "%%V" %%B%%B%%C%%~xV C:\lg>copy con log.log ^Z 1 file(s) copied. C:\lg>logrotate log.log C:\lg>FOR %V IN (log.log) DO FOR /F "tokens=1-3 delims=/ " %A IN ("%~tV") DO cop y "%V" %B%B%C%~xV C:\lg>FOR /F "tokens=1-3 delims=/ " %A IN ("03/12/03 05:07a") DO copy "log.log" %B%B%C.log C:\lg>copy "log.log" 031203.log 1 file(s) copied. C:\lg>dir Volume in drive C has no label. Volume Serial Number is F484-97B4 Directory of C:\lg 03/12/2003 05:07a <DIR> . 03/12/2003 05:07a <DIR> .. 03/12/2003 05:07a 2 031203.log 03/12/2003 05:07a 2 log.log 03/12/2003 04:37a 96 logrotate.bat 3 File(s) 100 bytes 2 Dir(s) 749,436,928 bytes free C:\lg> |
For a related article that will create an HTML calendar you can access the log files from, see this article.