sysfiles/usr/local/jilits/libverbosity.sh

63 lines
1.2 KiB
Bash
Raw Normal View History

2022-11-27 21:30:10 +01:00
#!/bin/bash
# Write to log
wrlog() {
echo "$1" >>"${LOG_FILE:?}"
}
# Write to stdout/stderr and log
echlog() {
local dt
dt="$(date +"%Y-%m-%dT%H:%M:%S")"
if [ -z "$1" ] && [ -z "$2" ]; then
echo ""
wrlog ""
elif [ -n "$1" ]; then
echo "$dt $1"
wrlog "$dt $1"
elif [ -n "$2" ]; then
echo "$dt $2" 1>&2
wrlog "$dt $2"
fi
}
# Write to stderr
errlog() {
echlog "" "$1"
}
# Rotate the log file
# TODO: Implement support for multiple rollovers and bz2 compression
rotlog() {
local filesize maxsize="${1:-10000000}"
if ! [ -f "$LOG_FILE" ]; then
echlog "File doesn't exist: '$LOG_FILE'"
return 0
fi
filesize="$(stat -c%s "$LOG_FILE")"
if ((filesize > maxsize)); then
echlog "Rotating log ($filesize > $maxsize)"
[ -f "$LOG_FILE.0" ] && rm "$LOG_FILE.0"
mv "$LOG_FILE" "$LOG_FILE.0"
fi
}
# Echo $1 and exit with code $2
echxit() {
if [ "$2" -eq 0 ]; then
echlog "$1"
exit "$2"
elif [ "$2" -gt 0 ]; then
errlog "$1"
exit "$2"
fi
errlog "$1"
errlog "Invalid exit code specified to echxit"
exit 255
}