..

Convert Nagios perfdata string to JSON

Posted September 30, 2014

I find Nagios’s performance data painful to parse. Hopefully, with Nagios’s perl module, creating a little script that converts Nagios’s performance data string into JSON is easy.

Requirements

We need perl, libjson-perl and libnagios-plugin-perl packages.

sudo apt-get install perl libjson-perl libnagios-plugin-perl

Performance Data to JSON script

#!/usr/bin/env perl
use Nagios::Plugin::Performance use_die => 1;
use JSON;

my $perfstring = $ARGV[0];

if (not defined $perfstring) {
  die "perfstring is required";
}

@perf = Nagios::Plugin::Performance->parse_perfstring(
    $perfstring
) 
or die "Failed to parse perfstring";

@metrics = ();

for $p (@perf) {
  # Special accessor returning a threshold obj containing warning/critical
  $threshold = $p->threshold;
  # not supported yet

  my %metric_hash = (
    'label'    => $p->label,
    'value'    => $p->value,
    'uom'      => $p->uom,
    'warning'  => $p->warning,
    'critical' => $p->critical,
    'min'      => $p->min,
    'max'      => $p->max
  );
  push(@metrics, \%metric_hash);
}

print encode_json \@metrics;

Example usage

Example #1 : Parsing check_http’s perfdata to json.

perl perfdatatojson.pl "time=0.002231s;;;0.000000 size=454B;;;0"
[
  {
    "value": 0.002231,
    "min": "0.000000",
    "label": "time",
    "uom": "s",
    "warning": null,
    "max": null,
    "critical": null
  },
  {
    "warning": null,
    "critical": null,
    "max": null,
    "label": "size",
    "min": "0",
    "value": 454,
    "uom": "B"
  }
]

Example #2 : Parsing check_ping’s perfdata to json.

perl perfdatatojson.pl "rta=0.038000ms;5000.000000;5000.000000;0.000000 pl=0%;100;100;0"
[
  {
    "uom": "ms",
    "warning": "5000.000000",
    "critical": "5000.000000",
    "min": "0.000000",
    "label": "rta",
    "max": null,
    "value": 0.038
  },
  {
    "critical": "100",
    "min": "0",
    "warning": "100",
    "uom": "%",
    "value": 0,
    "label": "pl",
    "max": null
  }
]

author Philippe LewinWritten by Philippe Lewin, French Software Engineer. twitter