Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
851 views
in Technique[技术] by (71.8m points)

logging - Bash: log stdout and stderr while preserving order and provenance

It's fairly simple to log both the stdout and the stderr of a command to a log file:

./foo.sh &> log.txt

The problem is that when inspecting the log file, one doesn't know anymore which line was coming from which stream. This could be fixed by redirecting stdout and stderr to two separate files, but then the chronology and interleaving of the output is lost.

An other solution would be to redirect to three files. One with the stdout, one with the stderr, and one with both combined. Something like:

./foo.sh 2> >(tee stderr | tee -a combined) 1> >(tee stdout | tee -a combined)

But that is not be very elegant to have so many files (and this command still dumps a copy of the output on the shell).

I found an interesting bash function that would color only stderr messages in red:

color()(set -o pipefail;"$@" 2>&1>&3|sed $'s,.*,e[31m&e[m,'>&2)3>&1

but it doesn't preserve the order of the output and the result is unreadable in a text editor. Given the following program for foo.sh:

for i in 1 2; do
   for j in 1 2; do
     printf '%s
' "out $i"
   done
   for k in 1 2; do
     printf '%s
' "err $i" >&2
   done
done

Running color ./foo.sh produces:

out 1
out 1
out 2
out 2
[31merr 1[m
[31merr 1[m
[31merr 2[m
[31merr 2[m

How could one easily end up with something such as this in a single log file ?

@| out 1
@| out 1
$| err 1
$| err 1
@| out 2
@| out 2
$| err 2
$| err 2
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

maybe you are looking for script it records both stdout, stderr and the commands...it starts a new shell in which it records everything (or use -c _cmd_)

 $ script tx1

your color() function breaks order because sed is buffering...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...