Skip to content

Instantly share code, notes, and snippets.

@bandaangosta
Last active March 1, 2019 13:35
Show Gist options
  • Save bandaangosta/2b574abdf0f4dbe50f1c899933eefee0 to your computer and use it in GitHub Desktop.
Save bandaangosta/2b574abdf0f4dbe50f1c899933eefee0 to your computer and use it in GitHub Desktop.
Print Docker containers log size
#! /usr/bin/env python3
# Print Docker containers log size
# Needs to 'pip install docker' first
#
# $ sudo ./docker_logs_size.py
# 658675d834 reverse-proxy_1: 10.31 KB
# 85f65ece1d webroot_1: 13.1 KB
# 34c6cc54ab redis_1: 18.81 KB
# 05a3c8b895 mysql_8.0_1: 48.69 KB
# ...
import os
import sys
from pathlib import Path
# Following is considering you are using a virtualenv where docker library was installed.
# Comment out if docker is installed globally
activate_this = os.path.join(Path(__file__).resolve().parent, 'venv', 'bin', 'activate_this.py')
exec(open(activate_this).read(), {'__file__': activate_this})
import docker
# From https://stackoverflow.com/a/14996816/2824942
def humansize(nbytes):
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
i = 0
while nbytes >= 1024 and i < len(suffixes)-1:
nbytes /= 1024.
i += 1
f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
return '%s %s' % (f, suffixes[i])
def main():
client = docker.from_env()
containers = client.containers.list()
for container in containers:
log = client.api.inspect_container(container.short_id)['LogPath']
print('{} {}: {}'.format(container.short_id, container.name, humansize(os.path.getsize(log))))
client.close()
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment