Skip to main content

Command Palette

Search for a command to run...

Automating Log Cleanup Using Shell Script

Updated
โ€ข2 min read

Before automating log cleanup by deleting or archiving logs, let's first understand why log automation is important and what problems we may face if logs are not maintained properly.

Why Do We Need to Delete Old Logs?

Applications continuously generate log files to record events, errors, and other important information. Since applications run every day, log files keep growing over time. If these logs are not managed properly, they can consume a significant amount of disk space and eventually lead to storage-related issues.

To avoid such problems, many real-world projects follow a log clean-up or log retention policy.

Common approaches include:

  • deleting old log files,

  • archiving them, or

  • moving them to backup storage.

In real-world projects, these log cleanup activities are often automated using Shell Scripting.

Automation helps reduce manual effort and ensures that old logs are cleaned up regularly without human intervention.

Now, let's look at the actual process and the steps involved in implementing log cleanup automation.

Steps Involved

  1. Identify the directory containing log files.

  2. Verify whether the directory exists.

  3. Find log files older than 14 days.

  4. Delete the old log files.

  5. Log the script execution for auditing and troubleshooting purposes.

Script (delete-old-logs.sh)

By automating log cleanup, we can efficiently manage disk space and ensure that servers continue to run smoothly.

I am also logging the details of the deleted files. This helps us keep track of which files were removed and when they were deleted. In the future, if we need to audit, troubleshoot, or verify the cleanup activity, we can refer to the log file.

As shown in the image below, I stored the details of the deleted log files in a separate log file for tracking and future reference.

What's Next?

You can schedule this script to run periodically using Cron, which allows the cleanup process to happen automatically without any manual intervention.

More from this blog

Special Variables in Shell Scripting: Small Symbols, Powerful Impact

๐—จ๐—ป๐—ฑ๐—ฒ๐—ฟ๐˜€๐˜๐—ฎ๐—ป๐—ฑ๐—ถ๐—ป๐—ด ๐—ฆ๐—ฝ๐—ฒ๐—ฐ๐—ถ๐—ฎ๐—น ๐—ฉ๐—ฎ๐—ฟ๐—ถ๐—ฎ๐—ฏ๐—น๐—ฒ๐˜€ ๐—ถ๐—ป ๐—ฆ๐—ต๐—ฒ๐—น๐—น ๐—ฆ๐—ฐ๐—ฟ๐—ถ๐—ฝ๐˜๐—ถ๐—ป๐—ด While learning Shell Scripting, I came across something very useful: ๐—ฆ๐—ฝ๐—ฒ๐—ฐ๐—ถ๐—ฎ๐—น ๐—ฉ๐—ฎ๐—ฟ๐—ถ๐—ฎ๐—ฏ๐—น๐—ฒ๐˜€.

Jun 19, 20264 min read17
D

DevOps With Pavan

5 posts

Sharing beginner-friendly tutorials and practical insights on DevOps, AWS, Linux, Docker, Kubernetes, CI/CD, and Cloud technologies in a simple and easy-to-understand way.