This document explains how to set up and use a log truncation utility on a Linux system using systemd
-
Create the Script (
truncate_logs.sh
):Copy the following script into a new file named
truncate_logs.sh
. This script searches for log files larger than a specified size and truncates them if they were modified in the last 30 minutes. Add the file in /usr/local/sbin/.#!/bin/bash # Define the directory containing the logs and the size threshold LOG_DIR="/var/log" MAX_SIZE=100M # Max size in MB, modify as needed # Find and truncate to 100M the files larger than the specified size. find $LOG_DIR -type f -size +$MAX_SIZE -exec truncate -s 100M {} \;
-
Make the Script Executable:
Run the following command to make the script executable:
sudo chmod +x /usr/local/sbin/truncate_logs.sh
-
Create the Service File (
truncate_logs.service
):Create a new file named
truncate_logs.service
in/etc/systemd/system/
with the following content:[Unit] Description=Log Truncation Service [Service] Type=oneshot ExecStart=/usr/local/sbin/truncate_logs.sh [Install] WantedBy=multi-user.target
-
Reload
systemd
and Enable the Service:Run the following commands to reload
systemd
and enable the service:sudo systemctl daemon-reload sudo systemctl enable truncate_logs.service
-
Create the Timer File (
truncate_logs.timer
):If you want the script to run automatically at regular intervals (e.g., every half hour), create a file named
truncate_logs.timer
in/etc/systemd/system/
with the following content:[Unit] Description=Run log truncation every half hour [Timer] # execute log_truncate service each 30 minutes OnCalendar=*:0/30 Persistent=true [Install] WantedBy=timers.target
-
Enable and Start the Timer:
Run these commands to enable and start the timer:
sudo systemctl enable truncate_logs.timer sudo systemctl start truncate_logs.timer
Once set up, the script will run according to the schedule defined in the truncate_logs.timer
file (every 30 minutes in this case). You can also manually trigger the script by starting the truncate_logs.service
:
sudo systemctl start truncate_logs.service
- Log Directory and Size Threshold: Modify the
LOG_DIR
andMAX_SIZE
variables in thetruncate_logs.sh
script to suit your requirements. - Schedule: Adjust the
OnCalendar
setting in thetruncate_logs.timer
file to change the script's execution schedule.