Setup Logrotate with Laravel for worry-less logs

The problem

It's 2 in the morning, you're deep asleep enjoying dreams of squishy marshmallows, your phone chimes, you recognize the sound, it's Sentry, production is down. Shit.

You quickly read the email skimming for the issue, you realize the disk is full, ssh-rm-rf-*-dot-log and it's back online, but now customers are mad, and you're even madder; this is not the first time. "But I have a reminder to delete the logs" you think, you dismissed the notification you remember.

The Solution

Fortunately, the fix is an easy one that will take you around 39 seconds to implement on a single server setup, let's fix it before you forget again and then explain it line-by-line.

On the server, create a new file at /etc/logrotate.d/laravel and fill it with this block, and you're done, save-and-exit

/path/to/your/laravel.log
{
compress
daily
missingok
rotate 7
notifempty
copytruncate
dateext
dateformat -%Y%m%d
}

The Explanation

Log rotation is deleting/archiving logs after reaching certain criteria. Most Unix systems ship with a tool called "logrotate" by default, and we can configure it to handle rotating old log files.

Logrotate runs every day and looks for config files in /etc/logrotate.d, based on the file it will decide if it should be run or not, you can execute logrotate with --force anytime to run it immediately. This could help a lot in debugging.

Now let's see what each of the above options actually mean so that you can customize it to your app

compress: compress the file after rotation
weekly: rotate the log file once a week
missingok: if the file is missing, don't make a fuss about it
rotate: only keep the latest 7 rotations
notifempty: if the file is empty do not rotate it
copytruncate: copy the log file with the new name, then truncate the old one. this helps if the old file is opened in a long-running process and simply renaming it will not stop the process from writing to the old file
dateext: when rotating, use the date to distinguish the order of the files, the default is to append a sequential number to the file name
dateformat: this tells logrotate what is the format of the appended date, notice that dash at the beginning so that it will look like "laravel.log-2020-08-16"

Conclusion

Logrotate is one of my favorite tools when setting up a server; simple setup, stable, and keeps me worry-less of one less problem. I highly recommend checking the official docs to see how you can customize it more, it has a ton more features, like it can email you the files before rotation, in any case here's the url https://www.freebsd.org/cgi/man.cgi?query=logrotate

Did I miss something? Do you have a better default file? Let me know in the comments sections down below.