Skip to main content

nagios.log with readable timestamps

Usually, the nagios.log is logged with Unix timestamps. This is neat and all, but I too like to be able to read these timestamps once in a while. And because I always forget about this, here's how:

$ tail -1 nagios.log 
[1299847717] Auto-save of retention data completed successfully.

$ tail -1 nagios.log | perl -pe 's/(\d+)/localtime($1)/e'
[Fri Mar 11 13:48:37 2011] Auto-save of retention data completed successfully.
Or, the long & ugly version of this:
$ sed 's/\[//;s/\]//' nagios.log | awk '{printf strftime("%c ", $1); print }' | \
  sed 's/CET [0-9]* /CET /' | tail -1
Fri 11 Mar 2011 01:48:37 PM CET Auto-save of retention data completed successfully.
MacOS 10.6 doesn't even support the latter and barfs with:
  awk: calling undefined function strftime
  input record number 1, file 
  source line number 1
So yeah, Perl is clearly the winner here :-)

As a bonus, here's how to convert epoch timestamps into YYYY-MM-DD (ISO 8601):
$ alias e2i='perl -MPOSIX -pe "s/(\d+)/strftime(\"%Y-%m-%d %H:%M:%S\", localtime(\$1))/e"'
$ tail -3 nagios.log | e2i
[2011-07-05 09:18:00] SERVICE NOTIFICATION ...
[2011-07-05 09:18:10] SERVICE EVENT HANDLER ...
[2011-07-05 09:20:20] EXTERNAL COMMAND ...