To achieve the described functionality, you can utilize a combination of tee for duplicating the output to both the console and a log file, and some additional processing to prefix each line with the required information. The following Bash script demonstrates how to accomplish this.
First, let's create a function that will handle the logging. This function will read from its standard input, prefix each line with the required information ($CURRENT_STEP and a timestamp), and then write it to a log file while also passing it through to stdout.
#!/bin/bash
# Set the log file name
LOG_FILE="script_log.log"
# Function to log output
log_output() {
while IFS= read -r line; do
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
echo "${CURRENT_STEP} ${TIMESTAMP} ${line}"
done | tee -a "${LOG_FILE}" /dev/stdout
}
# Function to handle stderr logging
log_error() {
while IFS= read -r line; do
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
echo "${CURRENT_STEP} ${TIMESTAMP} ${line}" >&2
done | tee -a "${LOG_FILE}" /dev/stderr
}
# Main script execution is wrapped to capture stdout and stderr
{
# Example commands
echo "This is an info message"
CURRENT_STEP="STEP1"
echo "Running step $CURRENT_STEP"
ls -l /dev/null
# Simulating an error
echo "Something went wrong" >&2
CURRENT_STEP="STEP2"
echo "Running step $CURRENT_STEP"
ls -l /nonexistent
} 2> >(log_error) | log_output
However, the above script has a flaw: it doesn't correctly maintain the unbuffered output to the console for both stdout and stderr due to the buffering nature of tee and the pipe. For most cases, this should be sufficient, but if you need strict unbuffered output, consider using stdbuf or unbuffer (from the expect package) to disable buffering.
Here's an enhanced version that attempts to address buffering:
#!/bin/bash
LOG_FILE="script_log.log"
log_output() {
stdbuf -oL sed -u "s/^/${CURRENT_STEP} $(date -u +\"%Y-%m-%dT%H:%M:%SZ\") /" | tee -a "${LOG_FILE}"
}
log_error() {
stdbuf -oL sed -u "s/^/${CURRENT_STEP} $(date -u +\"%Y-%m-%dT%H:%M:%SZ\") /" >&2 | tee -a "${LOG_FILE}" >&2
}
{
echo "This is an info message"
CURRENT_STEP="STEP1"
echo "Running step $CURRENT_STEP"
ls -l /dev/null
echo "Something went wrong" >&2
CURRENT_STEP="STEP2"
echo "Running step $CURRENT_STEP"
ls -l /nonexistent
} 2> >(log_error) | log_output
This version uses stdbuf -oL to make sed line-buffered, which helps in maintaining unbuffered output to the console. However, the effectiveness can depend on the specific commands and their buffering behavior.
To further ensure unbuffered output, you can run your script with unbuffer (from expect package):
unbuffer ./your_script.sh
This will make the entire script behave as if it's running interactively, thus typically disabling buffering.