How to manage daily growing logs using logrotate in Linux?
In Linux, the logrotate tool can be used to manage daily growing log files. Below are the basic steps for using logrotate.
- Create a logrotate configuration file. Normally, configuration files are stored in the /etc/logrotate.d/ directory so that the logrotate tool can locate and execute them. You can use any text editor to create a new configuration file, such as /etc/logrotate.d/myapp.
- Specify the log file to rotate in the configuration file. For example, to rotate the file /var/log/myapp.log, use the following content:
/var/log/myapp.log {
daily
rotate 7
compress
missingok
notifempty
}
The above configuration specifies rotating the log file daily and keeping the latest 7 rotated files. Other options include:
- Compress the rotated log files.
- missingok: Continue executing even if the log file is missing.
- notifempty: Rotation will not occur if the log file is empty.
- Save and close the configuration file.
- To manually execute log rotation using the logrotate tool: you can run the following command to rotate log files:
logrotate /etc/logrotate.d/myapp
This will rotate the specified log file according to the settings in the configuration file.
- The logrotate script located in the directory /etc/cron.daily.
#!/bin/sh
/usr/sbin/logrotate /etc/logrotate.conf
Next, change the file to have executable permissions.
chmod +x /etc/cron.daily/logrotate
This way, logrotate will automatically perform log rotation every day.
Please note that the specific configuration options and actions depend on your needs and the location of your log files. You can refer to the official logrotate documentation for more detailed information.