-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibrary.sh
More file actions
executable file
·91 lines (79 loc) · 2.13 KB
/
library.sh
File metadata and controls
executable file
·91 lines (79 loc) · 2.13 KB
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
#!/usr/bin/env bash
function log() {
local show_timestamp=false
local level
local message
local timestamp=""
local prefix=""
# Colors
local RED="\033[0;31m"
local YELLOW="\033[0;33m"
local GREEN="\033[0;32m"
local BLUE="\033[0;34m"
local NC="\033[0m"
# Function to map log level to a rank (lower means more verbose)
function get_level_rank() {
case "$1" in
DEBUG) echo 10 ;;
INFO) echo 20 ;;
WARN) echo 30 ;;
ERROR) echo 40 ;;
*) echo 50 ;;
esac
}
# Check if first arg is -t or --with-timestamps
if [[ "$1" == "-t" || "$1" == "--with-timestamps" ]]; then
show_timestamp=true
shift
fi
level="$1"
shift
message="$*"
# If DRY_RUN is set, add a prefix
if [[ "$DRY_RUN" == "true" ]]; then
prefix="[${BLUE}DRY_RUN${NC}] "
fi
# If timestamps requested, build the timestamp string
if [[ "$show_timestamp" == "true" ]]; then
prefix="$prefix[$(date +"%Y-%m-%d %H:%M:%S")] "
fi
# Determine threshold rank from LOG_THRESHOLD or default to INFO
local threshold_level="${LOG_THRESHOLD:-INFO}"
local threshold_rank=$(get_level_rank "$threshold_level")
local current_rank=$(get_level_rank "$level")
# Only log if current level is greater or equal to the threshold
if [ "$current_rank" -lt "$threshold_rank" ]; then
return
fi
# Prepare the log entry (with color applied only to the text inside brackets)
local log_entry=""
case "$level" in
DEBUG)
log_entry="${prefix}[${BLUE}DEBUG${NC}] $message"
;;
INFO)
log_entry="${prefix}[${GREEN}INFO${NC}] $message"
;;
WARN)
log_entry="${prefix}[${YELLOW}WARN${NC}] $message"
;;
ERROR)
log_entry="${prefix}[${RED}ERROR${NC}] $message"
;;
*)
log_entry="${prefix}[UNKNOWN] $message"
;;
esac
# Decide where to send output (LOG_FILE or stdout/stderr)
if [[ -n "$LOG_FILE" ]]; then
# Always append to file
echo -e "$log_entry" >> "$LOG_FILE"
else
# No LOG_FILE, emit to stdout (or stderr for ERROR)
if [[ "$level" == "ERROR" ]]; then
echo -e "$log_entry" 1>&2
else
echo -e "$log_entry"
fi
fi
}