Skip to content
Advertisement

How can I add a timestamp to every line in a piped log output?

I have to run some rather lengthy and legacy PHP scripts using cron. I want to capture the pid, output (both std and err) and log it to a file, but I would also like every line of this output to be timestamped. These scripts are quite fragile and it is not viable to properly instrument them with logging.

I came up with a bit of bash + gawk script that accomplishes this like so:

JavaScript

This works OK, however, it’s a rather convoluted and obscure solution to an otherwise simple problem.

Is there a simpler, better solution or tool to accomplish this?

Advertisement

Answer

an actual alternative –

Let awk handle the wait.

JavaScript

I don’t like that this spawns a whole subshell for a tenth-second sleep, but it avoids loading another extension and having to be concerned whether this local system is above or below version 5.1… (c.f. the manual entry for details)

just a rewrite

On closer inspection, this solution is riddled with problems and I don’t recommend you use it.

First, it fails if the input has more than one string.

JavaScript

I can fix that by putting the whole line into the date format:

JavaScript

but that will corrupt any data it sees as a valid formatting directive.

JavaScript

This method is really much kludgier than what you already had, as it’s spawning a date process for every line…

Adding in the PID is the only reason it becomes problematic, and your solution for that, while visually painful, really isn’t bad at all.

Taking another look… is the PID file really taking long enough to write that spawning the gawk reads an empty? This works fine for me:

JavaScript

If you just want a slightly less confusing, more maintainable way to write basically the same logic –

JavaScript

Switched to curly enclosure, works fine for this.

Or, using your values,

JavaScript

original

Pipe it through sed with a expression substitution.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement