问题
I make use of simple logging in mojolicious application. I want to extend logging by some information. This could be ip address or transaction id or session id. What I do before is writing for each log level one helper like this:
$self->helper( 'info' => sub {
my $self=shift;
my $msg=shift;
my $ip=$self->tx->remote_address;
$self->app->log->info("[$ip] $msg");
});
...
$self->info("Login failed of user $user.");
I would like to modify format of logging output so I can make use of generic log function which will add any additionally values I need and without lot of helpers for each log level. Basic call of:
$self->app->log->info("Login failed of user $user.");
should also give log entries like
[Sun Jun 8 11:09:12 2014] [info] [127.0.0.1] Login failed of user Tim.
I try do do it by change log format but anything I do is ignored.
$self->app->log->format(sub {
my ($time, $level, @lines) = @_;
return "[$time] [$level] [$self->tx->remote_address] @lines.\n";
});
I know there is Log4Perl in combination with Mojolicious. But I want to keep it simple as possible.
回答1:
I got this going pretty quick with using Mojolicious::Lite;
To start off, shift a log to someplace you can find quickly.
use Mojo::Log;
my $log = Mojo::Log->new(path => '~/log/mojo.log');
Then try this, set the remote address variable outside of the sub first.
# $r_ip = remote ip address
my $r_ip = $self->tx->remote_address;
$self->app->log->format(sub {
my ($time, $level, @lines) = @_;
return "[" . localtime(time) . "] [$level] [$r_ip] . join("\n", @lines) . "\n";
});
The format can been seen at: http://mojolicio.us/perldoc/Mojo/Log
回答2:
There is a possible to log a unique id per request/response? thread on the Mojolicious mailing list, where Sebastian/sri - the author of Mojolicious - answers:
Simple answer: You can't, Mojolicious is async by design and there may be thousands of concurrent requests active at any given time.
Complex answer: If you limit your application (through the server) to handling only one request at a time and don't use any real-time web features (not that it would make much sense if you can't handle concurrent requests), you could subclass Mojo::Log to customize the message format and store a global unique id for every new request.
The other (currently accepted) answer does exactly that: It removes all concurrency and uses a global variable. That'll start breaking down when you start using the real-time Mojolicious features.
来源:https://stackoverflow.com/questions/24104937/logging-of-ip-address-transaction-id-or-session-id-in-mojolog