A Perl script to print Nagios log records in a human readable date format

By Alvin J. Alexander, devdaily.com

In this blog I'll share the source code for a Perl program that takes nagios.log records as input, then outputs the records with a human-readable date format. More specifically, the input records look like this:

[1225306053] SERVICE ALERT: FTPSERVER;FTP SERVICE;OK;SOFT;2;FTP OK - 0.029 second response time on port 21 [220 ProFTPD 1.3.1 Server ready.]
[1225307073] SERVICE ALERT: FTPSERVER;FTP SERVICE;OK;SOFT;3;FTP OK - 0.046 second response time on port 21 [220 ProFTPD 1.3.1 Server ready.]

and the output records look like this:

[2008/10/29 14:47:33] SERVICE ALERT: FTPSERVER;FTP SERVICE;OK;SOFT;2;FTP OK - 0.029 second response time on port 21 [220 ProFTPD 1.3.1 Server ready.]
[2008/10/29 15:04:33] SERVICE ALERT: FTPSERVER;FTP SERVICE;OK;SOFT;3;FTP OK - 0.046 second response time on port 21 [220 ProFTPD 1.3.1 Server ready.]

The Perl script

Here's the source code for my Perl script that converts these records:

#!/usr/bin/perl

# ------------------------------------------------------------
# fixnag.pl
# ------------------------------------------------------------
# a script to take nagios.log records as input, and then
# output them with the date field converted to something
# human-readable
# ------------------------------------------------------------

sub epochtime
{
  my $epoch_time = shift;
  ($sec,$min,$hour,$day,$month,$year) = localtime($epoch_time);

  # correct the date and month for humans
  $year = 1900 + $year;
  $month++;

  return sprintf("%02d/%02d/%02d %02d:%02d:%02d", $year, $month, $day, $hour, $min, $sec);
}

while (<>)
{
  my $epoch = substr $_, 1, 10;
  my $remainder = substr $_, 13;
  my $human_date = &epochtime($epoch);
  printf("[%s] %s", $human_date, $remainder);
}

exit;

All you have to do to run this script is something like this:

cat nagios.log | fixnag.pl

search

devdaily logo