I would like a shell script to have all it's output for stdout
and stderr
logged to an external file with timestamps prepended to each line (plus a few extra items), without changing how the script is called. The output redirection should happen within the script itself. I also should not have to change any existing code in the script or pipe commands individually. Ideally I would only have to add a few lines to the script.
Using these two answers:
- Log entirety of bash script and prepend timestamp to each line
- Prepending a timestamp to each line of output from a command
I got to a point where it's working on Bash
#! /usr/bin/env bash
CUSTOM_PREFIX1="FancyScript"
CUSTOM_PREFIX2="SomeRunID_12-3-4.5"
LOG_FILE="/var/log/script.log"
touch $LOG_FILE
exec 1>> >(while IFS= read -r line; do printf '[%s] %s %s: %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "${CUSTOM_PREFIX1}" "${CUSTOM_PREFIX2}" "${line}"; done >> "${LOG_FILE}")
exec 2>&1
Script continues...
d
echo "Hello"
Running the script above produces no output and the following log file:
# cat /var/log/script.log
[2022-02-23 03:11:45] FancyScript SomeRunID_12-3-4.5: Development/shell_log.sh: line 12: d: command not found
[2022-02-23 03:11:45] FancyScript SomeRunID_12-3-4.5: Hello
So far so good, but I want to change two things.
- Make it work in POSIX shell (
sh
) and not depend on Bash. Regularsh
doesn't likeexec 1>> >(...)
- Instead of that long sub process
(while IFS= read ....)
I want to pipe it to a function within the script itself. Something likepipe_log() {...}
logger
) does the job perfectly. As a nice bonus I can use the OS'ssyslog
to further manage it. – Tuaris Apr 08 '22 at 07:09