Logger does not log Exceptions thrown in application

101 Views Asked by At

I use the configuration below to create a logger:

'log' => [
    'logger' => [
        'writers' => [
            'stream' => [
                'name' => 'stream',
                'priority' => \Zend\Log\Logger::INFO,
                'options' => [
                    'stream' => __DIR__ . '/../../data/log/name_' . date("Ym") . '.log',
                    'formatter' => [
                        'name' => \Zend\Log\Formatter\Simple::class,
                        'options' => [
                            'format' => '%timestamp% %priorityName% : %message% %extra%',
                            'dateTimeFormat' => 'c',
                        ],
                    ],

                ],
            ],
        ],
        'processors' => [
            'requestid' => [
                'name' => \Zend\Log\Processor\RequestId::class,
            ],
            'backtrace' => [
                'name' => \Zend\Log\Processor\Backtrace::class,
            ],
        ],
    ],
],

Log works fine but php error not logged nowhere.

Why?

I use this code to generate a simple error

$d1 = new DateTime();
$d2 = new DateTime();
$a = array($d1,$d2);
$a->format("Y-m-d");

in my controller class.

This error is not logged

2

There are 2 best solutions below

0
On

In PHP 7 ther's Error class to catch Fatal error

}catch(\Error $err){
    $this->log->err($err->getMessage());

Error class

0
On

zend-log is not exception or error handler by default. You have to set it to do that. You can use exceptionhandler, errorhandler and fatal_error_shutdownfunction options to set it. All config keys accepts boolean value. Here's an example. I didn't test it but should be like that.

'log' => [
    'logger' => [
        'writers' => [
            'stream' => [
                'name' => 'stream',
                'priority' => \Zend\Log\Logger::INFO,
                'options' => [
                    'exceptionhandler' => true,
                    'errorhandler' => true,
                    'stream' => __DIR__ . '/../../data/log/name_' . date("Ym") . '.log',
                    'formatter' => [
                        'name' => \Zend\Log\Formatter\Simple::class,
                        'options' => [
                            'format' => '%timestamp% %priorityName% : %message% %extra%',
                            'dateTimeFormat' => 'c',
                        ],
                    ],
                ],
            ],
        ],
        'processors' => [
            'requestid' => [
                'name' => \Zend\Log\Processor\RequestId::class,
            ],
            'backtrace' => [
                'name' => \Zend\Log\Processor\Backtrace::class,
            ],
        ],
    ],
],