Created
August 30, 2019 17:28
-
-
Save jberger/3948bef00526465bda7174d7be992ed4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Mojolicious::Lite -signatures; | |
sub _generate_id { ... } | |
{ | |
package Mojo::Log::WithContext; | |
use Mojo::Base 'Mojo::Log', -signatures; | |
has context => sub { {} }; | |
has id => sub { _generate_id() }; | |
has format => sub { sub ($id, $first, @lines) { ("[$id] $first", @lines) } }; | |
has parent => sub { Mojo::Log->new }; | |
sub new { | |
my $self = shift->SUPER::new(@_); | |
$self->unsubscribe('message'); | |
$self->on(message => sub ($self, $level, @lines) { | |
$self->parent->$level($self->format->($self->id, @lines)); | |
}); | |
return $self; | |
} | |
} | |
# this would be an attribute on the controller really | |
helper log => sub ($c) { | |
$c->stash->{logger} ||= Mojo::Log::WithContext->new( | |
id => $c->req->request_id, | |
parent => $c->app->log, | |
); | |
}; | |
get '/' => sub ($c) { | |
$c->log->info('Requested /'); # log some message | |
$c->render(text => 'done'); | |
}; | |
app->start; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment