Setup logrotate on Linux
Tired of having tons of log files, and wasting storage space on your server/host? In this guide I will show you how to setup logrotate on a Linux host to get rid of this problem!
Starting off
First we need to see if we have the software installed. On most Linux distros logrotate should already be installed. Check by running logrotate -v
If the above command does not return a version you will need to install logrotate on your system:
Setup
First we need to find the path to the directory where the log file is. In this example I will use /home/ubuntu/.pm2/logs
We then need to create a config file wich logrotate will run once a day. The file can be called whatever you want, but it needs to be placed in /etc/logrotate.d/
. I will call mine “pm2Logrotate”. Open up /etc/logrotate.d/pm2Logrotate
:
/home/ubuntu/.pm2/logs/*.log {
daily
rotate 7
compress
missingok
notifempty
copytruncate
create 0644 ubuntu ubuntu
}
The first line tells logrotate to look for every .log file inside the .pm2/logs/ directory. Inside the curly brackets we can add or remove tons of variables to fit our needs. This is just one example wich will do the job.
Variable | Description |
---|---|
daily | Will do the logrotate daily |
rotate 7 | Will keep 7 copies. If daily is set this means “keep 7 days of logs”, if weekly it will mean “keep 7 weeks of logs” |
compress | Will compress the file to save space |
missingok | If no .log file is present it will just carry on without stopping bacause of the error |
notifempty | Skips logrotate on a file that is empty |
copytruncate | This will copy the log file to another file and compress the copy. It will then remove all text from the original log file. This to prevent programs to stop because the file no longer exists etc. |
create 0644 ubuntu ubuntu | Sets the file permission to a desired user/group |
To read more about logrotate and it’s functions/variables see the manpages
logrotate -f /etc/logrotate.d/pm2Logrotate
. Just swap the last part with your own config