如何将stdout重定向到Bash中的文件时添加时间戳? [英] How to add timestamp while redirecting stdout to file in Bash?

查看:170
本文介绍了如何将stdout重定向到Bash中的文件时添加时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序(服务器),我正在寻找一种方法(脚本)将所有stdout重定向(或更好地复制)到文件中,并为每个条目添加时间戳.

I have a program (server) and I am looking for a way (script) that will redirect (or better duplicate) all its stdout to file and add timestamp for each entry.

我已经进行了一些研究,而我能得到的最深入的感谢是如何为STDERR重定向添加时间戳.它重定向stdout,但是添加的时间戳记是脚本完成的时间:

I've done some research and the furthest I could get was thanks to How to add timestamp to STDERR redirection. It redirects stdout but the timestamp added is of the time when the script finishes:

#!/bin/bash
./server | ./predate.sh > log.txt

predate.sh的代码:

#!/bin/bash
while read line ; do
    echo "$(date): ${line}"
done

似乎在程序退出后刷新服务器输出.(不进行重定向也可以正常工作).另外,如果我尝试在提到的线程中的给定示例上使用predate.sh,则它可以完美运行.我知道在主程序中添加时间戳会很容易,但是我宁愿避免编辑其代码.

It seems that server output is flushed after exit of the program.(without redirecting it works fine). Also if I try using predate.sh on given example in mentioned thread, it works perfectly. I am aware it would be easy adding a timestamp to the main program but I would rather avoid editing its code.

推荐答案

我最近确实需要:在串行控制台(picocom)中接收日志消息,将它们打印到终端和文件中,并在日期前加上

I recently needed exactly that: receive log messages in a serial console (picocom), print them to a terminal and to a file AND prepend the date.

我现在使用的东西看起来是…….像这样:

What I now use looks s.th. like this:

picocom -b 115200 /dev/tty.usbserial-1a122C | awk '{ print strftime("%s: "), $0; fflush(); }' | tee serial.txt

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