在执行单独的重定向的同时保持完美的顺序,如果没有一些丑陋的骇客,理论上是不可能的。 顺序只保留在直接写入同一文件(在 O_APPEND 模式下);只要您将tee 之类的内容放在一个进程中而不是另一个进程中,排序保证就会消失,并且如果不保留有关以何种顺序调用哪些系统调用的信息,就无法检索。
那么,那个黑客会是什么样子?它可能看起来像这样:
# eat our initialization time *before* we start the background process
sudo sysdig-probe-loader
# now, start monitoring syscalls made by children of this shell that write to fd 1 or 2
# ...funnel content into our logs.log file
sudo sysdig -s 32768 -b -p '%evt.buffer' \
"proc.apid=$$ and evt.type=write and (fd.num=1 or fd.num=2)" \
> >(base64 -i -d >logs.log) \
& sysdig_pid=$!
# Run your-program, with stderr going both to console and to errors.log
./your-program >/dev/null 2> >(tee errors.log)
也就是说,这仍然是丑陋的骇客:它只捕获直接对 FD 1 和 2 的写入,而不会跟踪可能发生的任何进一步的重定向。 (这可以通过执行对 FIFO 的写入并使用 sysdig 跟踪对这些 FIFO 的写入来改进;这样fdup() 和类似的操作将按预期工作;但以上足以证明这个概念。
单独处理显式
在这里,我们演示了如何使用它来仅对 stderr 进行着色,而无需理会 stdout —— 通过告诉 sysdig 生成 JSON 流作为输出,然后对其进行迭代:
exec {colorizer_fd}> >(
jq --unbuffered --arg startColor "$(tput setaf 1)" --arg endColor "$(tput sgr0)" -r '
if .["fd.filename"] == "stdout" then
("STDOUT: " + .["evt.buffer"])
else
("STDERR: " + $startColor + .["evt.buffer"] + $endColor)
end
'
)
sudo sysdig -s 32768 -j -p '%fd.filename %evt.buffer' \
"proc.apid=$$ and evt.type=write and proc.name != jq and (fd.num=1 or fd.num=2)" \
>&$colorizer_fd \
& sysdig_pid=$!
# Run your-program, with stdout and stderr going to two separately-named destinations
./your-program >stdout 2>stderr
因为我们要关闭输出文件名(stdout 和 stderr),所以这些文件名需要保持不变,以上代码才能正常工作——任何需要的临时目录都可以使用。
显然,您实际上不应该这样做。更新您的程序以支持任何可用其本地语言(Java 中的 Log4j、Python 日志记录模块等)的日志记录基础设施,以允许它的日志记录要明确配置。