Logger: Accept an arrayref of contexts for ctx parameter

This commit is contained in:
Richard Hansen 2024-08-02 15:37:41 -04:00
parent f36c2f45aa
commit 15db76f739
2 changed files with 26 additions and 6 deletions

View file

@ -2352,13 +2352,13 @@ sub ynu {
sub new {
my ($class, $ctx, $parent) = @_;
$ctx = [$ctx // ()] if ref($ctx) eq '';
return bless({ctx => $ctx, parent => $parent, _in_logger => 0}, $class);
}
sub _ctxs {
my ($self) = @_;
return ($self->{parent} ? $self->{parent}->_ctxs() : (),
defined($self->{ctx}) ? ($self->{ctx}) : ());
return ($self->{parent} ? $self->{parent}->_ctxs() : (), @{$self->{ctx}});
}
# Takes the following keyword arguments:
@ -2366,8 +2366,8 @@ sub ynu {
# * `label` (string): Severity ('DEBUG', 'WARNING', etc.) to prefix each line with.
# * `email` (boolean): Whether to include the message in the next email.
# * `raw` (boolean): Whether to omit `label` and the contexts (output `msg` as-is).
# * `ctx` (optional string): If defined, this is temporarily pushed onto the context stack
# (for this call only).
# * `ctx` (optional string or arrayref of strings): Context or contexts to temporarily push
# onto the context stack (for this call only).
#
# The keyword arguments may optionally be followed by a single positional argument, which
# becomes the value for the `msg` keyword argument if the `msg` keyword argument is not
@ -2380,11 +2380,12 @@ sub ynu {
(@_ % 2) ? (msg => pop) : (),
@_,
);
$args{ctx} = [$args{ctx} // ()] if ref($args{ctx}) eq '';
my $buffer = $args{msg};
chomp($buffer);
if (!$args{raw}) {
my $prefix = $args{label} ? sprintf("%-8s ", $args{label} . ':') : '';
$prefix .= join('', map("[$_]", $self->_ctxs(), $args{ctx} // ()));
$prefix .= "[$_]" for $self->_ctxs(), @{$args{ctx}};
$prefix .= '> ' if $prefix;
$buffer = "$prefix$buffer";
$prefix =~ s/> $/ /;

View file

@ -83,12 +83,31 @@ my @test_cases = (
"LBL: [context one][context two] bar\n"),
},
{
desc => 'ctx arg',
desc => 'string ctx arg',
args => [label => 'LBL', ctx => 'three', "foo\nbar"],
ctxs => ['one', 'two'],
want => ("LBL: [one][two][three]> foo\n" .
"LBL: [one][two][three] bar\n"),
},
{
desc => 'arrayref ctx arg',
args => [label => 'LBL', ctx => ['three', 'four'], "foo\nbar"],
ctxs => ['one', 'two'],
want => ("LBL: [one][two][three][four]> foo\n" .
"LBL: [one][two][three][four] bar\n"),
},
{
desc => 'undef ctx',
args => [label => 'LBL', "foo"],
ctxs => ['one', undef],
want => "LBL: [one]> foo\n",
},
{
desc => 'arrayref ctx',
args => [label => 'LBL', "foo"],
ctxs => ['one', ['two', 'three']],
want => "LBL: [one][two][three]> foo\n",
},
);
for my $tc (@test_cases) {