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:
- Use $userId variable inside the message string:
<?php
$userId = 123456;
$logger->info("User $userId logged in.")
?>
- Use sprintf to construct the message:
<?php
$userId = 123456;
$logger->info(sprintf("User %s logged in.", $userId))
?>
- Configure Monolog to use the PsrLogMessageProcessor so that you can use the PSR-3 compatible placeholder replacement. This is the most elegant way in my opinion. It combines a descriptive message with a structured context which can be very helpful especially when sending logs to backend like Graylog.
<?php
$userId = 123456;
$logger->info("User {userId} logged in.", ['userId' => $userId])
?>