-
Notifications
You must be signed in to change notification settings - Fork 3
/
pipe-logger.sh
executable file
·72 lines (63 loc) · 1.26 KB
/
pipe-logger.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
#!/bin/bash
SIZE=$(( 10 * 1024 * 1024 ))
FILES=10
TIME_PREFIX=0
usage() {
echo "$BASH_SOURCE [-s SIZE[k|m|g]] [-n #FILES] [-t] FILENAME"
}
while getopts "s:n:th" opt; do
case $opt in
s )
SIZE=$(echo $OPTARG | tr '[:upper:]' '[:lower:]')
if [ ${SIZE%k} != $SIZE ]; then
SIZE=$(( ${SIZE%k} * 1024 ))
elif [ ${SIZE%m} != $SIZE ]; then
SIZE=$(( ${SIZE%m} * 1024 * 1024 ))
elif [ ${SIZE%g} != $SIZE ]; then
SIZE=$(( ${SIZE%g} * 1024 * 1024 * 1024 ))
fi
;;
n )
FILES=$OPTARG
;;
t )
TIME_PREFIX=1
;;
h )
usage
exit 0
esac
done
shift $(($OPTIND -1))
if [ $# -ne 1 ]; then
usage
exit 1
fi
FILE=$1
if [ -f "$FILE" ]; then
if [ `uname` = 'Darwin' ]; then
bytes=`stat -f%z "$FILE"`
else
bytes=`stat -c%s "$FILE"`
fi
else
bytes=0
fi
while read line; do
# Log formatting
if [ $TIME_PREFIX -eq 1 ]; then
line="$(date '+[%Y/%m/%d %H:%M:%S]') $line"
fi
line="$line\n"
# Rotate if required
bytes=$((bytes + ${#line}))
if [ $bytes -gt $SIZE ]; then
for i in `seq $((FILES - 1)) -1 1`; do
[ -f "$FILE.$i" ] && mv -f "$FILE.$i" "$FILE.$((i + 1))"
done
mv -f "$FILE" "$FILE.1"
bytes=0
fi
# Log
echo -en $line >> "$FILE"
done