Using Monolog Context Effectively

2015/10/04

Any Monolog entry is constructed by 2 elements, the Log message and the optional Log Context which is an array of data related to the log message.

Most of the times you will need to use data from the context inside the message.

Let’s assume that you need to add a log entry whenever a user logs into your website. You can do this in 3 different ways:

<?php
    $userId = 123456;
    $logger->info("User $userId logged in.") 
?>
<?php
    $userId = 123456;
    $logger->info(sprintf("User %s logged in.", $userId))  
?>  
<?php
    $userId = 123456;
    $logger->info("User {userId} logged in.", ['userId' => $userId]) 
?>

Categories: posts Tags: php monolog