Skip to content

Commit

Permalink
Try to protect against using undef as a label value
Browse files Browse the repository at this point in the history
This is surprisingly easy to do when generating metrics.
  • Loading branch information
robn committed Sep 7, 2023
1 parent f134ab5 commit 8de6ba1
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
1 change: 1 addition & 0 deletions Changes
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
Revision history for {{$dist->name}}

{{$NEXT}}
- Warn and handle attempts to set label values to undef

0.010 2022-02-01 08:25:56+11:00 Australia/Melbourne
- Warn and handle attempts to set or add non-numbers
Expand Down
11 changes: 8 additions & 3 deletions lib/Prometheus/Tiny.pm
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,14 @@ sub _format_labels {

join ',', map {
my $lv = $to_format->{$_};
$lv =~ s/(["\\])/\\$1/sg;
$lv =~ s/\n/\\n/sg;
qq{$_="$lv"}
if (defined $lv) {
$lv =~ s/(["\\])/\\$1/sg;
$lv =~ s/\n/\\n/sg;
qq{$_="$lv"}
} else {
carp "label '$_' has an undefined value, dropping it";
()
}
} sort keys %$to_format;
}

Expand Down
12 changes: 12 additions & 0 deletions t/50-warn-undef.t
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,16 @@ some_metric 10
EOF
}

{
my $p = Prometheus::Tiny->new;
$p->set('some_metric', 10);
warning_like
{ $p->add('some_metric', 10, { foo => undef }) }
qr/label '.+' has an undefined value, dropping it/,
'undef label value emits a warning';
is $p->format, <<EOF, 'add metric undef label formatted correctly';
some_metric 20
EOF
}

done_testing;

0 comments on commit 8de6ba1

Please sign in to comment.