Magento 2 log rotation with logrotate

Why?

Log rotation is an automated process to remove or archive old and big log files. More information here.

Magento 2 log files get bigger every day, it may take too much space and slow down your server. In fact, you can backup and delete Magento log files, but it’s better if there’s an automated process that helps you to clean it up, you can still check the log if needed and you don’t have to care about them at all.

Install logrotate

logrotate is recommended by Magento. It’s a very powerful software on Linux and installed by default on many Linux distributions. You can check it by:

which logrotate
---------- OR ----------
sudo service logrotate status

To install logrotate:

---------- On Debian and Ubuntu ---------- 
sudo apt-get update && sudo apt-get install logrotate 

---------- On CentOS, RHEL and Fedora ---------- 
sudo yum update && sudo yum install logrotate

Logrotate configuration for Magento 2

Below is the content of logrotate.conf that I’m using on my production environments. Replace /var/www/html/magento2/ with your site’s root-absolute path.

/var/www/html/magento2/var/log/*.log /var/www/html/magento2/var/log/*/*.log{
    # Rotate daily
    daily
    # Compress old log files
    compress
    # Keep the most recent log uncompressed
    delaycompress

    # Skip missing files
    missingok
    # Skip empty files
    notifempty

    # Rotate when the size is bigger than 50MB
    size 50M
    # Always keep 4 weeks of log files
    rotate 4
    # Create a new log file with mode 0644
    create 0644

    # Add a date extension to rotated files
    dateext
    # Sets the dateformat of the dateext
    dateformat -%Y-%m-%d-%s
}

Ways to run logrotate

Method 1: Using logrotate service

Create a new file in /etc/logrotate.d/ without extension, m2logrotate for example.

Add the above content and save.

Method 2: Using crontab 

Add the following line to crontab using crontab -e command. The user that runs cronjob must own log files, so if log files belong to www-data, the crontab command should be crontab -u www-data -e.

---------- Replace /path/to/ with corresponding absolute path ---------- 
30 * * * * /usr/sbin/logrotate /path/to/logrotate.conf --state /path/to/var/log/.logrot_state

If you run cronjob as root with sudo crontab -e:

---------- Replace /path/to/ with corresponding absolute path ----------
30 * * * * /usr/bin/su www-data -c "/usr/sbin/logrotate /path/to/logrotate.conf --state /path/to/var/log/.logrot_state"

If you run cronjob by adding a file into /etc/cron.d or modifying /etc/crontab:

---------- Replace /path/to/ with corresponding absolute path ----------
30 * * * * www-data /usr/sbin/logrotate /path/to/logrotate.conf --state /path/to/var/log/.logrot_state

That’s it!

5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x