2

The time(1) command allows you to time any command, by passing it as arguments to time.

I know it's possible to redirect stderr and stdout to a file via 2>&1, and there's also tee(1) which allows one to copy its input to both the screen and a file. However, I do not know how to add timestamps to logs.

Is there a tool to redirect stderr and stdout to a file, AND append timestamps to it for logging purposes?

Satō Katsura
  • 13,368
  • 2
  • 31
  • 50
Edward
  • 21
  • 2
    I read your first sentence multiple times, but it doesn't make any sense. Did you forget 'to' between 'you' and 'time'? Any reason to fumble with adding time after the entry in a log? Why are you not using logger and get a standard entry (with timestamp before the log entry)? – Anthon Dec 17 '16 at 08:18

2 Answers2

5

You could use ts(1) from moreutils.


ts from moreutils will prepend a timestamp to every line of input you give it. You can format it using strftime too.

$ echo 'foo bar baz' | ts
Mar 21 18:07:28 foo bar baz
$ echo 'blah blah blah' | ts '%F %T'
2012-03-21 18:07:30 blah blah blah
$ 

To install it:

sudo apt-get install moreutils

Contents copied from this answer: https://stackoverflow.com/a/9813614/221689

Charley
  • 191
3

Try annotate-output from Debian's devscripts package. It shows timestamps, and writes "O" before standard output, and "E" before standard error. Example:

# run `ls` on one file that exists, and one that doesn't...
annotate-output ls /bin/bash /tmp/boosh

Output:

03:30:52 I: Started ls /bin/bash /tmp/boosh
03:30:52 O: /bin/bash
03:30:52 E: ls: cannot access '/tmp/boosh': No such file or directory
03:30:52 I: Finished with exitcode 2
agc
  • 7,223
  • Interesting. This does not have date stamp, am I right? – Edward Dec 17 '16 at 09:00
  • @Edward, it does have date stamping, just pass it a date string: annotate-output +"%D %H:%M:%S" ls /bin/bash /tmp/boosh; see man date for a list of all the date string format codes. – agc Dec 17 '16 at 17:14