This Python script searches a specified directory and truncates all files with the .log
extension that exceed a certain size.
- Python 3.6 or higher
Run the script with the following arguments:
--directory
: The directory to search for large.log
files.--max-size
: The maximum file size in GB..log
files that exceed this size will be truncated. The default value is 5 GB.
Example:
python app.py --directory /var/lib/docker/containers/ --max-size 10
This example searches the directory /var/lib/docker/containers/
and truncates all .log
files that are larger than 10 GB.
The script logs its activities in the file /var/log/truncate_files.log
. It logs both successful truncations and errors.
Please be careful when using this script. It truncates .log
files irreversibly to free up storage space. Make sure you don't lose any important data.
You can also run this script in a Docker container. Use the provided Dockerfile and build a container.
# docker build -t truncate_logs:latest .
Run the container with the required arguments:
# docker run -it --rm -v /var/lib/docker/containers/:/containers:rw -v /var/log:/app/log:rw truncate_logs:latest ./app.py --directory /containers/ --max-size 10
You can also set up a cron job to run the Docker container regularly. To do this, edit the crontab file:
# crontab -e
Add the following line to run the container every 6 hours:
0 */6 * * * docker run -it --rm -v /var/lib/docker/containers/:/containers:rw -v /var/log:/app/log:rw truncate_logs:latest ./app.py --directory /containers/ --max-size 10
MIT License
Copyright (c) 2024 Günter Bailey
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
direct translation from github Copilot.
Dockerfile to run this script on server < Python3.6
On first time, docker build:
docker build -t truncate_logs:latest .
command to run in cronjob:
45 */6 * * * root docker run -it --rm -v /var/lib/docker/containers/:/containers:rw -v /var/log:/app/log:rw truncate_logs:latest ./app.py --directory /containers/ --max-size 10