重击:在保留顺序和出处的同时记录stdout和stderr [英] Bash: log stdout and stderr while preserving order and provenance

查看:106
本文介绍了重击:在保留顺序和出处的同时记录stdout和stderr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将命令的stdout和stderr都记录到日志文件中是非常简单的:

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

./foo.sh &> log.txt

问题是,当检查日志文件时,人们不再知道哪一行来自哪一个流.可以通过将stdout和stderr重定向到两个单独的文件来解决此问题,但是输出的年代和交织会丢失.

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.

另一种解决方案是重定向到三个文件.一个带有stdout,一个带有stderr,另一个带有两者的组合.像这样:

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)

但是拥有这么多文件并不是一件很优雅的事情(并且此命令仍然将输出的副本转储到Shell上).

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).

我发现了一个有趣的bash函数,该函数只会将stderr消息着色为红色:

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

,但是它不保留输出顺序,并且结果在文本编辑器中不可读.给定foo.sh的以下程序:

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\n' "out $i"
   done
   for k in 1 2; do
     printf '%s\n' "err $i" >&2
   done
done

运行color ./foo.sh会产生:

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

推荐答案

也许您正在寻找script 它同时记录了stdout,stderr和命令...它启动了一个新的shell,其中记录了所有内容(或使用-c _cmd_)

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

您的color()函数中断了顺序,因为sed正在缓冲...

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

这篇关于重击:在保留顺序和出处的同时记录stdout和stderr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆