Last active
October 17, 2018 15:18
-
-
Save jberger/8d458f4e49412c819173de8f43aa85c0 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; | |
use Mojo::JSON 'to_json'; | |
use Scalar::Util 'weaken'; | |
{ | |
package Mojo::Log::WithContext; | |
use Mojo::Base 'Mojo::Log'; | |
has context => sub { {} }; | |
} | |
helper 'log' => sub ($c) { | |
return $c->stash->{'log.logger'} if $c->stash->{'log.logger'}; | |
my $log = Mojo::Log::WithContext->new; | |
$log->context->{request_id} = $c->tx->req->request_id; | |
$log->unsubscribe('message'); | |
$log->format(sub ($log, $level, @lines) { | |
return join '|', @lines, to_json($log->context); | |
}); | |
weaken $c; | |
$log->on(message => sub ($log, $level, @lines) { | |
return unless $c; | |
# pass up to app's logger after formatting | |
$c->app->log->$level($log->format->($log, $level, @lines)); | |
}); | |
return $c->stash->{'log.logger'} = $log; | |
}; | |
get '/' => sub ($c) { | |
$c->log->context->{user} = 'Joel'; # add some context | |
$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