This little recipe builds on BashScriptSyslog by adding additional (optional) debug logging to a seperate log file as specified by the $DEBUG_LOGFILE
variable.
The log_debug()
function will allow you to log messages to debug log file that do not go to the console or syslog.
#!/bin/bash
PROG="${0##*/}"
DEBUG_LOGFILE="/tmp/debug.log"
function prepend_timestamp() {
while read line ; do
echo "$(date +'%d-%m-%y %X') $line"
done
}
function log_debug() {
echo "$PROG[$$] $*" | prepend_timestamp >> "$DEBUG_LOGFILE"
}
if [[ -n "$DEBUG_LOGFILE" ]] ; then
exec > >(2>&-; \
logger -s -t "$PROG[$$]" -p user.info 2>&1 \
| prepend_timestamp | tee -a "$DEBUG_LOGFILE"
) 2> >( \
logger -s -t "$PROG[$$]" -p user.error 2>&1 \
| prepend_timestamp | tee -a "$DEBUG_LOGFILE" 1>&2
)
else
exec > >(2>&-;logger -s -t "$PROG[$$]" -p user.info 2>&1) \
2> >(logger -s -t "$PROG[$$]" -p user.error)
fi
echo "This message went to STDOUT and to syslog FACILITY_USER.LOG_INFO."
ls /tmp
log_debug "This message only went to the $DEBUG_LOGFILE log file " \
"(not to the console or to syslog)."
echo "This message went to STDERR and to syslog FACILITY_USER.LOG_ERR."
>&2
ls /path/does/not/exist
Notice that the message 14-03-15 20:05:36 bar.sh[15949] This message only went to the /tmp/debug.log log file (not to the console or to syslog).
only appears in the debug log file /tmp/debug.log
, and not the console (or syslog; not shown in this example output).
nicolaw@tyrion:~ $ ./bar.sh
14-03-15 20:05:36 bar.sh[15949]: This message went to STDOUT and to syslog FACILITY_USER.LOG_INFO.
14-03-15 20:05:36 bar.sh[15949]: apt-listchanges-tmpoR6QUz
14-03-15 20:05:36 bar.sh[15949]: ls: cannot access /path/does/not/exist: No such file or directory
14-03-15 20:05:36 bar.sh[15949]: debug.log
14-03-15 20:05:36 bar.sh[15949]: ssh-csED0GPnN1
14-03-15 20:05:36 bar.sh[15949]: ssh-rkVTz1ylScj2
14-03-15 20:05:36 bar.sh[15949]: This message went to STDERR and to syslog FACILITY_USER.LOG_ERR.
nicolaw@tyrion:~ $ cat /tmp/debug.log
14-03-15 20:05:36 bar.sh[15949]: This message went to STDOUT and to syslog FACILITY_USER.LOG_INFO.
14-03-15 20:05:36 bar.sh[15949] This message only went to the /tmp/debug.log log file (not to the console or to syslog).
14-03-15 20:05:36 bar.sh[15949]: ls: cannot access /path/does/not/exist: No such file or directory
14-03-15 20:05:36 bar.sh[15949]: debug.log
14-03-15 20:05:36 bar.sh[15949]: ssh-csED0GPnN1
14-03-15 20:05:36 bar.sh[15949]: ssh-rkVTz1ylScj2
14-03-15 20:05:36 bar.sh[15949]: This message went to STDERR and to syslog FACILITY_USER.LOG_ERR.
nicolaw@tyrion:~ $