You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.7 KiB

#!/bin/bash
# Author: Nils Gerstner
pipe="$1"
err_pipe="$2"
logfile="$3"
pid=""
err_pid=""
TAB="$(printf '\t')"
trap ">&2 echo 'Logger exiting'; ps -p $pid 2>/dev/null && kill -9 $pid; ps -p $err_pid 2> /dev/null && kill -9 $err_pid; rm -f $err_pipe $pipe 2>&1 > /dev/null" EXIT
if [[ ! -p $pipe ]] || [[ ! -p $err_pipe ]]; then
mkfifo $pipe
mkfifo $err_pipe
while [[ ! -p $pipe ]] && [[ ! -p $err_pipe ]]; do
sleep 0.01
done
fi
log() {
local named_pipe="$1"
local other_pipe="$2"
local level="$3"
while true; do
in_msg="$(cat $named_pipe)"
if [ -n "$in_msg" ]; then
if [[ "$in_msg" == 'quit' ]]; then
>&2 echo "stopping $named_pipe"
echo "quit" > $other_pipe
rm -f $named_pipe
break
else
#----- L O G E X A M P L E S -----#
#
# Log to plain text
# cat >> "${logfile}_plain" <<< "${level}${TAB}${in_msg}"
# Log to json file
jq -n -c --arg msg "${in_msg}" --arg level "${level}" '{ "level": $level, "timestamp": (now | strftime("%Y-%m-%d %H:%M:%S")), "message": $msg }' |tee -a $logfile
# Log to systemd journal
# logger -t My-Logger -p ${level,,} "${msg}"
fi
fi
done
}
log_info(){
log $pipe $err_pipe INFO
}
log_err(){
log $err_pipe $pipe ERROR
}
while [[ ! -p $pipe ]] || [[ ! -p $err_pipe ]]; do
sleep 0.1
done
log_info & pid="$!"
log_err & err_pid="$!"
while [[ -p $pipe ]] && [[ -p $err_pipe ]]; do
sleep 0.01
done
ps -p $pid && kill -9 $pid
ps -p $err_pid && kill -9 $err_pid
wait
exit 0