Logs are taking up too much space on your server. How to fix it?
Most log files are stored in the /var/log
directory, but they are not limited to it. The principles described in this section apply to all *.log files in any directory on your server.
Logs are files that store information about server events: application and operating system activity, various errors, user requests to websites, and more. Over time, logs can take up a significant amount of disk space, especially under heavy load or if there are software errors.
One critical aspect of log files is that, in most cases, deleting them can cause issues for the program generating them — whether it’s a web server or even the operating system itself.
Additionally, logs often contain valuable diagnostic information that can help identify software issues on your server and prevent larger problems. Therefore, it’s important to handle them properly and carefully.
How to identify logs that can be cleaned
Use ncdu to locate large logs on the server. If a log file is unusually large, check its latest entries:
sudo tail /path/to/log
If there are no anomalies, check the beginning of the file to determine whether the log grew large simply due to age (pay attention to the date of the earliest entries):
sudo head /path/to/log
After this, you can proceed with cleaning the file.
If you’re unsure why the log file has grown so large, it’s better to save it and contact your hosting provider’s support team for clarification.
How to safely clean logs
The truncate
command clears the contents of a file without deleting it:
sudo truncate -s 0 /var/log/nginx/error.log
Separately note the files that are logs, despite the lack of *.log extension:
/var/log/btmp
/var/log/syslog
/var/log/messeges
/var/log/secure
/var/log/maillog
These files can also be safely cleaned using the truncate
command.
A special case is the log located in the /var/log/journal
directory. You can find more details about working with it in separate article.
How to prevent logs from growing too large
While analyzing logs, you may notice some of them have names like:
syslog.1
yoursite.access.log.1
These appear when log rotation is applied, for example, using the logrotate program. Old files can be deleted or compressed during rotation, saving disk space.
You can read more about configuring this mechanism in a separate article.