How To Logrotate In Linux

Logging on a Linux server is a significant aspect of system administration. Over time, log files can grow in size and consume your storage, which could potentially crash your system. This issue brings us to an essential tool in Linux known as logrotate. This post will provide a guide on how to use logrotate to manage your log files in Linux.

What is Logrotate?

Logrotate is an utility designed for administrators who manage servers producing a high volume of log files. Logrotate allows the automatic rotation, compression, removal, and mailing of log files. This tool can be set to handle log files daily, weekly, monthly, or when it grows too large.

How to Install Logrotate in Linux

In most Linux distributions, logrotate comes pre-installed. To check if it is installed on your system, you can use the command:

logrotate –version

If the system prompts a message that command ‘logrotate’ not found, you can install it using the following commands:

For Ubuntu/Debian:
sudo apt-get install logrotate

For CentOS/RHEL:
yum install logrotate

Configuring Logrotate

Logrotate works based on the configuration files. The main configuration file is /etc/logrotate.conf, and the directory /etc/logrotate.d/ contains configuration files for specific services.

Let’s look at an example configuration file:

/etc/logrotate.d/apache2
/var/log/apache2/*.log {
    weekly
    missingok
    rotate 52
    compress
    delaycompress
    notifempty
    create 640 root adm
    sharedscripts
    postrotate
        /etc/init.d/apache2 reload > /dev/null
    endscript
    prerotate
        if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
            run-parts /etc/logrotate.d/httpd-prerotate; \
        fi; \
    endscript
}

Here is a brief overview of what each directive means:

  • weekly: Log files are rotated once each week.
  • missingok: If the log file doesn’t exist, go on to the next one without issuing an error message.
  • rotate 52: Keep 52 weeks worth of backlogs.
  • compress: Old versions of log files are compressed with gzip by default.
  • delaycompress: Postpone compression of the previous log file until the next rotation cycle.
  • notifempty: Do not rotate the log if it’s empty.
  • create 640 root adm: Immediately after rotation, a new log file is created with the specified permissions, owner, and group.
  • sharedscripts: Run postrotate script only once, not once for each log that gets rotated.

Conclusion

Logrotate is a powerful tool that can help administrators manage log files effectively. The key to successful log management lies in understanding how to configure and use logrotate to suit your specific needs. We hope this guide helps you get started with logrotate on Linux.