1. Overview

In this quick tutorial, we’ll look at a few ways to clean up log files in Linux. We’ll also look briefly at ways to handle logs better.

2. Application Logging

Sometimes, applications on Linux can cause issues with large log files. In general, our applications should be handling their own log files. For example, in a Java application, we can use a rolling appender in log4j2 to periodically roll and zip logs.

But sometimes, we’ll come across an application where this is not the case, and we need some manual intervention. We could use rm but just deleting a log file can cause issues if file permissions have been set in a particular way. Also, if an application still has a handle on the file, deleting it could cause errors or not actually free up disk space.

Let’s look at a few ways to handle an application’s log files safely.

3. truncate

One way we can clear logs is to use the truncate command. Let’s make a sample log file (using fallocate) that we’ll want to clean up:

$ fallocate -l 5M app.log

This gives us a large file:

$ ls -l app.log
-rw-rw-r--. 1 alex alex 5242880 Sep 13 22:19 app.log 

Now, let’s call truncate to free up the space without deleting the file:

$ truncate --size 0 app.log

Finally, let’s recheck our file’s size to see that our command emptied the file:

$ ls -l app.log
-rw-rw-r--. 1 alex alex 0 Sep 13 22:33 app.log

4. Redirection Operator

We can clear a log file using the redirection operator (>) to replace the file’s content. First, let’s recreate our sample log file from before:

$ fallocate -l 5M app.log

Now, we’ll use the redirection operator to overwrite the file contents:

$ > app.log
$ ls -l app.log
-rw-rw-r--. 1 alex alex 0 Sep 13 22:37 app.log

The redirection operator called with nothing on the left side redirects “nothing” to the file. So, now our log file is empty.

5. logrotate

A more automated approach to log management on Linux is the logrotate tool. It allows for the automatic, cron-based rotation and compression of log files. A full example is beyond the scope of this tutorial.

6. Conclusion

In this tutorial, we presented a few ways to handle log cleanup in Linux. But, to reiterate, the ideal way to handle logs is to have an application clean up after itself.


» 下一篇: 基于TCP的Ping