len8200
len8200

Reputation: 85

How to display information about the current user in Mojo :: Log

The logs display information by default. Using the _default function in Mojo::Log.

sub _default {
  my ($time, $level) = (shift, shift);
  my ($s, $m, $h, $day, $month, $year) = localtime $time;
  $time = sprintf '%04d-%02d-%02d %02d:%02d:%08.5f', $year + 1900, $month + 1, $day, $h, $m,
    "$s." . ((split /\./, $time)[1] // 0);
  return "[$time] [$$] [$level] " . join "\n", @_, '';
}

It is necessary to add information about the current user (for example, his ID). An App :: Controller object is required to retrieve user information. Is it possible to override the resulting $app->log using the before_dispatch function?

$app->hook(before_dispatch => sub($c){...});

Upvotes: 2

Views: 237

Answers (1)

simbabque
simbabque

Reputation: 54333

In general, you can change the format of the logger by setting the format property. That part is fairly trivial.

use Mojolicious::Lite -signatures;

helper user => sub ($c) {
    return "bob";
};

get '/' => sub ($c) {
    app->log->warn('hello');
    $c->render(text => "Hello");
};

app->log->format( sub { app->user . ": " . join "\n", @_, '' } );
app->start;

This will work. The trick here is to use something that isn't part of the arguments the format code reference gets passed in, and to close over that. It works well with app.

You are saying your user information comes from a different controller. That is a bit strange. Shouldn't the context contain the information about the current user?

Upvotes: 4

Related Questions