10

I have logs in the following format: YYYYMMDD

I want to compress old logs (older then current day) and maybe move them to a different directory afterwards.

Can I do this in logrotate, or do I have to use a custom script in cron?

4

Here's a quickie script which will do what you need:

#!/bin/bash
LOGDIR=/var/log/somedir
OLDLOGS=/var/log/keep-old-logs-here
PATH=/bin:$PATH
TODAY=$(date +'%Y%m%d')

[ -d $OLDLOGS ] || mkdir -p $OLDLOGS

cd $LOGDIR

for LOG in $(ls | egrep '^[[:digit:]]{8}$'); do
    [ $LOG -lt $TODAY ] && gzip $LOG && mv $LOG.gz 
done

Make the script executable:

$ chmod +x /where/you/put/this/script

The crontab entry will look like:

30 0 * * * /where/you/put/this/script

Just adjust LOGDIR and OLDLOGDIR. At 12:30am it will move all logs in the format of YYYYMMDD for the previous (and earlier, if any) days.

2
  • 5
    Yes, but it doesn't really answer my question. My question was whether I can use logrotate for this. Jun 24 '11 at 11:04
  • @Let_Me_Be - I thought it was implicit in my answer. No, logrotate won't do exactly what you want. That is, you can't only match YYYYMMDD files. Otherwise you can come close by using nodateext, olddir, compress, and daily options.
    – unpythonic
    Jun 24 '11 at 11:26
3

logrotate can do it with olddir if your log file name is the same every time it runs and you can add dates. If your log file name changes i.e. YYYYMMDD then logrotate won't do it for you.

# sample logrotate conf file
copytruncate
compress
dateformat %Y%m%d.
dateext
extension log
olddir ./logarchive

/logs/sys.log {
    rotate 7
    daily
}

Copies and gzips /logs/sys.log to /logs/logarchive/sys.20120101.log.gz, keeps one week worth of logs.

1
  • 2
    This is not the answer. The logs already have datestamps, and are effectively rotated Let_Me_Be just wants to compress them. I believe @jmtd is right. Apr 7 '17 at 1:22
2

logrotate itself does not do this. I'd recommend writing a supplementary script and invoking it from logrotate using the postrotate option in the configuration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.