How to utilize logrotate for log rotation in Linux

To use logrotate for log rotation, you can follow these steps:

  1. Install logrotate: On Linux systems, logrotate is typically pre-installed, but if it is not, you can install it using a package manager. For example, on Debian/Ubuntu, you can use the following command to install logrotate:
sudo apt-get install logrotate
  1. Create a logrotate configuration file: Create a new logrotate configuration file in the /etc/logrotate.d/ directory, you can choose any file name, such as mylog. Use an editor to open the newly created file.
sudo nano /etc/logrotate.d/mylog
  1. Write a logrotate configuration: configure the parameters of logrotate as needed. Below is an example of a sample configuration file.
/path/to/logfile {
    rotate 7  # 保留最近7个日志文件
    daily     # 每天执行一次日志切割
    compress  # 压缩旧的日志文件
    missingok # 如果日志文件不存在则继续进行
    notifempty # 如果日志文件为空则不进行切割
}

In this example, /path/to/logfile is the path of the log file that needs to be rotated. The settings rotate 7 specify to keep the latest 7 log files, daily means to rotate the log file daily, compress indicates to compress old log files, missingok allows the rotation to continue if the log file is missing, and notifempty prevents the rotation if the log file is empty.

  1. Test logrotate configuration: You can use the following command to check if the logrotate configuration file is correct:
sudo logrotate -d /etc/logrotate.d/mylog

This will simulate running logrotate and display detailed information about the process.

  1. Run logrotate: manually execute logrotate with the following command.
sudo logrotate /etc/logrotate.d/mylog

You can also set up a cron job to automatically run logrotate regularly. For example, add the following content to the /etc/cron.daily/logrotate file:

#!/bin/sh
/usr/sbin/logrotate /etc/logrotate.conf

Save the file and give it execute permission.

sudo chmod +x /etc/cron.daily/logrotate

This will enable logrotate to automatically run every day.

These are the basic steps for log rotation using logrotate. Depending on the actual requirements, logrotate’s configuration parameters can be adjusted to meet specific needs.

bannerAds