I have a constantly running script that I output to a log file:
script.sh >> /var/log/logfile
I'd like to add a timestamp before each line that is appended to the log. Like:
Sat Sep 10 21:33:06 UTC 2011 The server has booted up. Hmmph.
Is there any jujitsu I can use?
You can pipe the script's output through a loop that prefixes the current date and time:
If you'll be using this a lot, it's easy to make a bash function to handle the loop:
See
ts
from the Ubuntumoreutils
package:Or, if
$command
does automatic buffering (requiresexpect-dev
package):The date command will provide that information
so you can
is that what you wanted ?
Make a
config.sh
fileWhen you need to send to log file use
Log file will looks like
So it will be easy to sort by date
You can simply echo the command outputs to the logfile. ie,
It really works :)
Example:
The accepted answer https://serverfault.com/a/310104 can be a bit slow, if a lot of lines have to be processed, with the overhead of starting the
date
process allowing about 50 lines per second in Ubuntu, and only about 10-20 in Cygwin.When
bash
can be assumed a faster alternative would be theprintf
builtin with its%(...)T
format specifier. CompareRemark. On my current OpenSuse work PC (July 2021) performance is significantly up, doing 1200 lines per second with
date
and 265,000 lines per second withprintf
. Not entirely clear, how this particular performance jumped by almost two orders of magnitude compared to my laptop from 5 years ago.Try this
Call this timestamp function in every echo command:
Short answer formatted to fit the question
Explanation
awk
runs fast and is able to work as Unix pipe filter and print date by itself.Let's benchmark it:
Additional information
Sed appears to runs much faster,
However, on closer inspection, set does not seem to change time,
Because
date
(which is slower by the way) gets called only once.You mean like:
Another option is to setup a function to call each time you want to output data in your code:
Then every time in your code you want to send it to the log file call
Easy peasy....