I'm trying to write some functions I can utilize in my scripts to essentially tag all output as Error vs Standard output, throw date/time stamps on it, and also include the name of the function that the output came from. I have this all working except for buffering issues. My output essentially isn't in chronological order.
I've tried combinations of unbuffer, sync, stdbuf, etc, but I can't get it to work. Any help or explanation about why specifically this is failing for me would be appreciated. Also, any tips on a simpler execution of this would be great. So far, in order to get my function name I have to reconfigure my redirection on every single function call.
#!/bin/bash
function stdOutput
{
typeset strLogFile=$1; shift
typeset strLogID=$1; shift
while IFS='' read -r strInput
do
echo "$(eval echo ${strLogID})${strInput}" && echo "$(eval echo ${strLogID})${strInput}" >> ${strLogFile}
done
}
function errOutput
{
typeset strLogFile=$1; shift
typeset strLogID=$1; shift
while IFS='' read -r strInput
do
>&2 echo "$(eval echo ${strLogID})${strInput}" && echo "$(eval echo ${strLogID})${strInput}" >> ${strLogFile}
done
}
function main
{
stdLogID="\<STD\>!"'$'"(date +\"%Y-%m-%d!%H:%M:%S\")!"
errLogID="\<ERR\>!"'$'"(date +\"%Y-%m-%d!%H:%M:%S\")!"
logFile=/tmp/out.log
> $logFile
exec 3>&1 1> >(stdOutput ${logFile} "${stdLogID}${FUNCNAME[0]}!")
exec 4>&2 2> >(errOutput ${logFile} "${errLogID}${FUNCNAME[0]}!")
>&2 echo "Line1"
echo "Line2"
>&2 echo "Line3"
echo "Line4"
>&2 echo "Line5"
echo "Line6"
>&2 echo "Line7"
echo "Line8"
>&2 echo "Line9"
echo "Line10"
exec 1>&3 3>&-
exec 2>&4 4>&-
}
main
sync
exit
What I would hope to get as output from this script. Every other line being ERR then STD tagged and the line numbers in order 1-10.
<ERR>!2016-08-01!14:06:15!main!Line1
<STD>!2016-08-01!14:06:15!main!Line2
<ERR>!2016-08-01!14:06:15!main!Line3
<STD>!2016-08-01!14:06:15!main!Line4
<ERR>!2016-08-01!14:06:15!main!Line5
<STD>!2016-08-01!14:06:15!main!Line6
<ERR>!2016-08-01!14:06:15!main!Line7
<STD>!2016-08-01!14:06:15!main!Line8
<ERR>!2016-08-01!14:06:15!main!Line9
<STD>!2016-08-01!14:06:15!main!Line10
Example of the type of output I usually get. Line numbers out of order due to buffering.
<ERR>!2016-08-01!14:06:15!main!Line1
<STD>!2016-08-01!14:06:15!main!Line2
<STD>!2016-08-01!14:06:15!main!Line4
<ERR>!2016-08-01!14:06:15!main!Line3
<STD>!2016-08-01!14:06:15!main!Line6
<ERR>!2016-08-01!14:06:15!main!Line5
<STD>!2016-08-01!14:06:15!main!Line8
<ERR>!2016-08-01!14:06:15!main!Line7
<STD>!2016-08-01!14:06:15!main!Line10
<ERR>!2016-08-01!14:06:15!main!Line9
stdout
.