How can I write a cron job to archive my log files every night?

5,262

You'll want to check out logrotate which is installed by default (or easily though a package manager) on nearly every major Linux distribution. It's quite easy to put together a simple configuration entry to rotate your log file -- everything you need to know about configuration options is on that man page.

Some distributions use a special /etc/logrorate.d/ directory to specify individual logrotate files for each log file (or a related group of log files). If your distribution uses this method, it's as simple as creating an appropriately-named file in that directory with a configuration block as described in the man page.

Otherwise you can simply just append your new configuration block to the end of the existing /etc/logrotate.conf file.

Share:
5,262

Related videos on Youtube

Reuben Sanders
Author by

Reuben Sanders

Updated on September 18, 2022

Comments

  • Reuben Sanders
    Reuben Sanders almost 2 years

    I assume this is relatively easy but my shell scripting isn't that great so I'm hoping to get some help.

    I have a task which runs every hour and appends its output to a log file. I'd like to move that log file every night so that the script has an empty one to work with and the logs are easier to look at when I need to check them.

    So I'd like a script which moves

    /var/log/my.log

    to

    /var/log/my.log.2 or my.log.yyyy.mm.dd or something.

    How can I do that pretty easily?

  • Reuben Sanders
    Reuben Sanders over 12 years
    after I create the file in /etc/logrotate.d, will it run by default or do I need to set anything else up?
  • Garrett
    Garrett over 12 years
    Logrotate runs in a daily cron and re-reads configuration files for each run, so there's no need to take additional steps.