Search code examples
phploggingsilexmonolog

Keep a trace of the username with Monolog in a Silex app


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 ?


Solution

  • 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?