How to limit log file size in Linux?
Published on Aug. 22, 2023, 12:17 p.m.
To limit log file size in Linux, you can use log rotation. Log rotation is a process that renames or moves a log file and creates a new one when it reaches a certain size or age.
The logrotate
command is a built-in tool in most Linux distributions, and it can be used to configure log rotation for specific files or directories. Here’s an example of how to configure log rotation for a specific file:
- Create a configuration file in the
/etc/logrotate.d/
directory:
sudo nano /etc/logrotate.d/example
- Add the following content to the configuration file:
/var/log/example.log {
rotate 4
maxsize 10M
compress
delaycompress
missingok
notifempty
}
Here, /var/log/example.log
is the path to the log file that you want to rotate. The rotate 4
option means to keep up to 4 rotated log files. The maxsize 10M
option means to rotate the log file when it reaches 10 MB. The compress
option will compress the rotated log files using gzip. The delaycompress
option means to compress the rotated log files the next time the log file is rotated. The missingok
option means to not raise an error if the log file is missing. The notifempty
option means to not rotate the log file if it is empty.
- Save and close the file.
- Check the configuration file:
sudo logrotate -d /etc/logrotate.d/example
This will show you what logrotate
would do, but it won’t actually rotate the log file.
- Test the configuration file:
sudo logrotate -f /etc/logrotate.d/example
This will force the logrotate
to rotate the log file.
By default, log rotation is usually set up to run daily via a cron job, but you can customize the rotation cycle as well.