forked from CSCfi/hpc-container-wrapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common_functions.sh
107 lines (93 loc) · 2.39 KB
/
common_functions.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/bin/bash
if [[ ! ${USE_COLOR+defined} ]];then
export USE_COLOR="yes"
fi
if [[ ! ${CW_LOG_LEVEL+defined} ]];then
export CW_LOG_LEVEL="2"
fi
if [[ -t 1 && "$USE_COLOR" = "yes" ]];then
export _RED='\033[0;31m'
export _GREEN='\033[0;32m'
export _YELLOW='\033[1;33m'
export _BLUE="\e[1;34m"
export _PURPLE='\033[0;35m'
export _NC='\033[0m' # No Color
else
export _RED=""
export _GREEN=""
export _YELLOW=""
export _BLUE=""
export _PURPLE=""
export _NC=""
fi
time_stamp(){
if [[ $CW_LOG_LEVEL -gt 2 ]];then
echo " $(date +"%H:%M:%S")"
fi
}
# _print_info <log level threshold>
print_info(){
if [[ $CW_LOG_LEVEL -gt $2 ]];then
if [[ "$2" == 1 ]]; then
>&1 echo -e "[ ${_BLUE}INFO${_NC}$(time_stamp) ] $1 " | sed '2,$s/^/ /g'
else
>&1 echo -e "[ ${_PURPLE}DEBUG${_NC}$(time_stamp) ] $1 " | sed '2,$s/^/ /g'
fi
fi
}
print_warn(){
if [[ $CW_LOG_LEVEL -gt 0 ]];then
>&1 echo -e "[ ${_YELLOW}WARNING${_NC}$(time_stamp) ] $1 " | sed '2,$s/^/ /g'
fi
}
# Errors are always printed
print_err(){
>&1 echo -e "[ ${_RED}ERROR${_NC}$(time_stamp) ] $1 " | sed '2,$s/^/ /g'
}
## Fancy info
export UPLINE=$(tput cuu1)
export ERASELINE=$(tput el)
erase_lines(){
for i in $(eval echo "{1..$1}");do
echo -e "$ERASELINE$UPLINE$ERASELINE\c"
done
}
export -f erase_lines
counter=1
follow_log(){
set -e
p_pid=$1
log_file=$2
output_length=$3
trap "kill $p_pid 2> /dev/null" EXIT
trap "kill $p_pid 2> /dev/null" INT
trap "kill $p_pid 2> /dev/null" ERR
echo "========================="
while kill -0 $p_pid 2> /dev/null; do
if [[ ! -f $log_file ]];then
continue
fi
res="$(tail -n $output_length $log_file)"
res_lines="$(echo -e "$res" | wc -l )"
echo -e "$res"
echo "========================="
counter=$(($counter +1))
sleep 1
if [[ "$output_length" -gt "$res_lines" ]];then
erase_lines $res_lines
else
erase_lines $output_length
fi
erase_lines 1
done
trap - EXIT
trap - INT
trap - ERR
res="$(tail -n $output_length $log_file)"
echo -e "$res"
echo "========================="
}
export -f follow_log
export -f print_info
export -f print_warn
export -f print_err