Hello everyone, today I am going to share one problem I faced when I was developing my first project with Zend Framework 2. The issue was with defining and managing error, exceptions. In the front-end, it was displaying errors/exceptions to the user, rather filing it into any file. It was too awkward for a user to see the error message as kind of paragraph in the front-end :D.
So, that time, I thought of logging those errors/exceptions in a log file, for further check and fix for the issue, as we always do with any other framework/normal PHP projects. I searched for the native solution, it is present or not in the same Framework. I found the manual (though now-a-days we can find a lot of blogs/tutorials for solving error logging issue), where some logging code has been written, and which I thought would definitely help me to reach my goal.
So, what I did was – I just went through the manual for error logging once, and believe me, I didn’t understand even 50% of the concept :). That’s why I decided be patient and go through the same manual once again or twice.
Hmmm… after reading 3 more times, I got some points and I thought of using it in the code. Then, I checked and analyzed what should be the best position to use the logger code, so that it would help me as extent and I should not have to write the same code again and again.
So, here I am going to explain what attempt I had taken that time and it was successful also. Let’s check the step by step process of adding the logger for errors/exception.
First Step
First, attach to the dispatch error event inside Module.php (say in Application folder).
public function onBootstrap(MvcEvent $e)
{
$sm = $e->getApplication()->getServiceManager();
$sharedManager = $e->getApplication()->getEventManager()->getSharedManager();
$sharedManager->attach('Zend\Mvc\Application', 'dispatch.error',
function($e) use ($sm) {
if ($e->getParam('exception')) {
$sm->get('\Zend\Log\Logger')->crit($e->getParam('exception'));
return false;
}
}
);
}
Second Step
Create service.config.php file (say Application/config/service.config.php).
return array(
'factories' => array(
'\Zend\Log\Logger' => function($sm){
$logger = new Zend\Log\Logger;
$writer = new Zend\Log\Writer\Stream('./data/logs/' . date('Y-m-d') . '-error.log');
$logger->addWriter($writer);
return $logger;
},
),
);
Now, it’s done. The call anyway will go through bootstrap
method and will log the error if any into one file. The path we used above for creating the log is inside ‘data/logs/’ directory. Do you really find it useful? :) If yes, then please like and add some comments, if you want.
Thanks :) and I will be happy to hear from you :).
CodeProject
