How to Rotate a Log in Ubuntu


In our last guide, we demonstrated different approaches for checking logs on Ubuntu. The topic of today’s guide will be rotating a log on Ubuntu. Let’s get into it.

Rotating a log on Ubuntu refers to the process of managing log files by compressing or archiving, removing older entries, and creating new ones. It helps in maintaining the size of log files, preventing them from growing too large and filling up the available disk space.

How to Rotate a Log on Ubuntu?

To rotate logs on Ubuntu, you can use the logrotate utility. Logrotate allows you to manage and rotate log files automatically based on specified criteria. We have demonstrated the procedure for setting up a log rotation on Ubuntu below.

Step 1: Navigate to the logrotate Configuration Directory

As the first step, open up the Ubuntu terminal. Then, execute the mentioned command:

cd /etc/logrotate.d/

Step 2: Create a New Configuration File

Next, create a new configuration file for your log file. For example, if you want to rotate the Apache access log, create a file named “apache2”:

sudo nano apache2

Step 3: Add the Configuration Directives

Adjust the configuration according to your log file path and rotation preferences:

/var/log/apache2/*.log {

rotate 7

daily

missingok

compress

delaycompress

notifempty

create 640 root adm

sharedscripts

postrotate

/etc/init.d/apache2 reload > /dev/null

endscript

}

Press “Ctrl+X” then “Y”.

Step 4: Test the log rotation

Test the log rotation to see if there are any errors or issues with the configuration. To do so, run the mentioned command:

sudo logrotate -d /etc/logrotate.d/apache2

Step 5: Manually Initiate the log Rotation

If there are no errors, you can manually initiate the log rotation by running the command below:

sudo logrotate -f /etc/logrotate.d/apache2


That was all about rotating a log on Ubuntu.

Conclusion

To rotate a log on Ubuntu, you need to open the terminal first. After that, navigate to the logrotate configuration directory. Next, create a new configuration file for your log file. Then, add the configuration directives. As the next step, test the log rotation. If there are no errors, then, start the log rotation manually by executing the “sudo logrotate -f /etc/logrotate.d/apache2” command. That’s how you can rotate a log on Ubuntu.

Print Friendly, PDF & Email
Categories