I added Monolog v.1.24.0 to my project.
Create a logger:
$logger = new Logger('db');
$logger->setTimezone(DateTime::getTimezone());
$logger->pushHandler(new StreamHandler(ROOT.'/log/db.log', Logger::DEBUG, 600));
Now at some point later in the code I construct a message and send it to browser:
// $result contains my array
$tmp = \json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_SLASHES);
echo $tmp;
$logger->notice($tmp);
My problem is that I want to extract the time info contained in the log stored at db.log
and include to that echoed to the user.
How is that possible?
PS: I can construct the time by myself but then it's better to delete the whole Monolog project and use my own!
You are trying to use monolog and generally a PSR-3 logger for something that it is not meant to be used in this way...
What happens internally in monolog or more specifically in this case to a PSR-3 client is out of scope of what you are trying to achieve. Most probably your business domain says that you need to store a record for an action that the user did.. Then do so.. It does not say that you want to log it or if it does say that you need to log it these two should not be mixed.
Moreover you shouldn't be mixing what monolog internally does with what you need to display to the user.
So in the end the solution would be:
// $result contains my array
$tmp = \json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_SLASHES);
echo $tmp;
//
// write here custom code that saves my $msg where ever I need to and that it contains also the timestamp
//
// Then come here and log that my record is saved..
$logger->notice('Record is saved');
You have to understand that logger is an abstract layer for LOGGING
.. You are violating the Liskov Principle of SOLID... What will happen if in the future you remove the DB/Stream Handler from your monolog? And replace it with something else that does not have timestamp.
Your code will fail.