1
votes

I have a Silex application within I have set up a Monolog logger service. In debug mode, the logs are like (INFO level):

[2018-02-21 09:08:26] appName.INFO: > GET /customers [] []
[2018-02-21 09:08:27] appName.INFO: < 200 [] []

I would like to keep a trace of the user who generate those requests, by writing the username in the log, next to the date for instance.

Is there a way to customize the Monolog template to achieve that ?

2
As a reminder, Silex has its EOL set on June 2018. You should migrate to SF4 if you want to keep the code up to date (which you really should). Also, there seems to be some movement on handing over the Silex management, but for now its all good intentions (I hope they really succeed)mTorres
As I've moved to this SIlex project recently, I wasn't well-informed about this SensioLabs' decision. Thanks.Clément Canuto

2 Answers

1
votes

Simply do this when user consumes the request:

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$logger = new Logger('name');
$logger->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

//Add following lines
$username = 'foobar'; //Ofcourse your user's username
$logger->info($username);

What else do you expecting?

0
votes

You are after a log processor & formatter. With a custom log processor add the username to the log record, then with the formatter, include that value in the log string row.

Or you can simply add the username to the log's context if you will:

$logger->log('User logged in', ['username' => $username]);