Renaming log files automatically

You can organise a scheduled task (cron) to do the following:

  • Run the ImportEmailer tool, which will generate a “LogFile.txt” log
  • Run a simple script that renames the file to add the date/time

Note: This will cause the creation of a new file each time the tool is run, instead of a single file that is replaced every time. It is recommended to integrate in the script a way of removing old files, to avoid accumulation.)

The following scripts are to be executed from the directory where the log file is, and delete the files older than 7 before renaming the new file to the following format: LogFile_<YYYYMMDD>-<HHMM>.txt

Script example for Linux (bash):

#!/usr/bin/env bash

# Delete files older than 7 days

find LogFile-*.txt -mtime +7 -exec rm {} \;

# Rename the LogFile

mv LogFile.txt LogFile-"$(date +"%Y%m%d_%H%M")".txt

Script example for Windows (batch):

::Delete files older than 7 days

forfiles /m LogsFile-*.txt /D -7 /C "cmd /c del @path"

::Rename the LogFile

ren LogFile.txt LogsFile-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~0,2%%time:~3,2%.txt

ren LogFile.txt LogsFile-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~1,1%%time:~3,2%.txt

The following example shows the Linux script (renameLogFile.sh) renaming the LogFile.txt to LogFile-<date_time>.txt, as well as deleting the log files older than 7 days (LogFile dated from 1980):