How to delete logs automatically after a certain time and restart the process that fills up the log file?

Server is Ubuntu 16.04. I have a process running with nohup that logs into a local file. This file gets big enough to consume 100% disk space. To resolve this I have to kill the process first and then remove the log file. Then I restart the process. How can I resolve this with a script or some other tool?

3 Answers

With logrotate you can configure how big a log file may get or after how much time:

  • the log files are rotated (log.n becoming log.n+1, and the last log file being deleted)

  • the current log file is truncated without disturbing the writing process.

Take a look at man 8 logrotate.

3

I guess that you start the script/program with nohup like

nohup scriptname 1>logfile.log 2>& &

I would recommend instead of deleting the log file just to clear it with

echo -n >logfile.log

If you delete/move an open file it will be written until the process will close the file or the process will end.

9

To delete all logs automatically, edit the .bashrc file using your favorite text editor. Here I'm using nano. In your terminal run:

nano ~/.bashrc - 

Add the following to the bottom of the file:

rm -r /var/log # Deletes logs directory
clear # Clear the terminal

Press Ctrl+O to save and Ctrl+X to exit edit mode.

The .bashrc file is executed every time you log in or launch a terminal instance, thus your logs will always be deleted.

You can also delete them based on time. E.g. delete all logs created 3 days ago using:

find /yourlog/path -mindepth 1 -mtime +3 -delete
  • -mindepth 1 means process all files except the command line arguments.
  • -mtime +3 will check for the files that were modified 3 days ago.
  • -delete will delete them.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like