Dan*_* W. 19 command-line colors tail
我正在查看不同的日志
tail -q -f /var/log/syslog -f /var/log/fail2ban.log -f /var/log/nginx/error.log
Run Code Online (Sandbox Code Playgroud)
我怎样才能让每个日志的输出颜色不同?
Sté*_*las 21
使用 GNUgrep
进行着色:
color() { GREP_COLOR=$1 grep --color '.*'; }
(tail -qf /var/log/syslog | color 31 &
tail -qf /var/log/fail2ban.log | color 32 &
tail -qf /var/log/nginx/error.log | color 33)
Run Code Online (Sandbox Code Playgroud)
请注意,前两个是在后台启动的。这意味着如果您按下它们不会被杀死Ctrl-C(shell 明确忽略异步作业的 SIGINT)。
为了防止这种情况,您可以改为:
color() { GREP_COLOR=$1 grep --line-buffered --color=always '.*'; }
(tail -qf /var/log/syslog | color 31 &
tail -qf /var/log/fail2ban.log | color 32 &
tail -qf /var/log/nginx/error.log | color 33) | cat
Run Code Online (Sandbox Code Playgroud)
这样, on Ctrl-C, last tail+grep
and cat
die (SIGINT)和其他两个 grep+tails 将在下次写东西时死于 SIGPIPE。
或者恢复 SIGINT 处理程序(不适用于所有 shell):
color() { GREP_COLOR=$1 grep --color '.*'; }
((trap - INT; tail -qf /var/log/syslog | color 31) &
(trap - INT; tail -qf /var/log/fail2ban.log | color 32) &
tail -qf /var/log/nginx/error.log | color 33)
Run Code Online (Sandbox Code Playgroud)
您也可以在color
函数中进行。这不适用于tail
,但tail
会在下次写入时grep
因SIGPIPE而死亡,如果死亡。
color() (trap - INT; GREP_COLOR=$1 exec grep --color '.*')
(tail -qf /var/log/syslog | color 31 &
tail -qf /var/log/fail2ban.log | color 32 &
tail -qf /var/log/nginx/error.log | color 33)
Run Code Online (Sandbox Code Playgroud)
或者让整个 tail+grep 成为一个函数:
tailc() (trap - INT; export GREP_COLOR="$1"; shift; tail -qf -- "$@" |
grep --color '.*')
tailc 31 /var/log/syslog &
tailc 32 /var/log/syslog &
tailc 33 /var/log/nginx/error.log
Run Code Online (Sandbox Code Playgroud)
或者整件事:
tailc() (
while [ "$#" -ge 2 ]; do
(trap - INT; tail -f -- "$2" | GREP_COLOR=$1 grep --color '.*') &
shift 2
done
wait
)
tailc 31 /var/log/syslog 32 /var/log/syslog 33 /var/log/nginx/error.log
Run Code Online (Sandbox Code Playgroud)