forked from Ecotrust-Canada/youngagrarians
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker-logs-trim.sh
90 lines (68 loc) · 1.93 KB
/
docker-logs-trim.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/bin/bash
# NOTES:
# Requires jq (https://github.com/stedolan/jq)
# Does NOT delete logfile (BAD IDEA) - simply trims file with redirect.
# Handles single/all-running/all-existing containers - see end of script for usage.
# Enjoy :-)
_get_container_logfile() {
case $1 in
running) _trim_container_logfile "$(docker ps -q)" $2
;;
all) _trim_container_logfile "$(docker ps -aq)" $2
;;
*) _trim_container_logfile "$(docker ps -a | awk -v ID=$1 '$1 ~ ID || $NF ~ ID {print $1}')" $2
;;
esac
}
_trim_container_logfile() {
TEMP=$(mktemp)
case $2 in
*[!0-9]*) echo "[lines] must be a number - \"$2\" is not a number."
exit -1
;;
''|*) MAX=${2:-1000}
;;
esac
if [ -z $1 ]
then
echo "Container name/id unknown!"
exit -1
else
for container in $1
do
logfile="$logfile $(docker inspect $container | jq -r '.[].LogPath')"
echo "Keeping $MAX lines: $logfile"
tail -n ${MAX} $logfile > $TEMP
# Uncomment the next line when you trust the script!
# cat $TEMP > $logfile
done
fi
rm $TEMP
}
if [ -a "$(which jq)" ]
then
case $1 in
--trim) if [ -z $2 ]
then
echo "Container name/id missing!"
exit -1
else
_get_container_logfile $2 $3
fi
;;
--trim-running) _get_container_logfile running $2
;;
--trim-all) _get_container_logfile all $2
;;
*) echo "Usage:"
echo " --trim {container} [lines] Keep [lines] of logfile for a single container"
echo " --trim-running [lines] Keep [lines] of logfile for all running containers"
echo " --trim-all [lines] Keep [lines] of logfile for all containers"
echo "Default: lines=1000"
exit -1
;;
esac
else
echo "Requires \"jq\""
exit -1
fi