记录PHP通知

时间:2018-09-16 15:41:45

标签: php logging slim syslog

使用Slim并正确记录了我的所有错误,但是直到脚本结束,才显示诸如<b>Notice</b>: Undefined offset: 747 in <b>/var/www/App.php</b> on line <b>54</b><br />之类的通知。发生时如何将它们记录到syslog?

<?php
error_reporting(E_ALL);
ini_set('display_startup_errors', 1);
ini_set("log_errors", 1);
ini_set('display_errors', 1);
openlog('PublicAPI', LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER | LOG_PERROR);

require '../vendor/autoload.php';

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app = new \Slim\App([
    'displayErrorDetails'=>true,
    'settings' => parse_ini_file(__DIR__.'/../config.ini', true, INI_SCANNER_TYPED)
]);

$c = $app->getContainer();

$c['errorHandler'] = function ($c) {
    return function ($request, $response, $e) use ($c) {
        syslog(LOG_ERR, "Slim errorHandler: {$e->getFile()} ({$e->getline()}): {$e->getMessage()} ({$e->getCode()})");
        return $c['response']->withJson(['message'=>'Server Error'],500);
    };
};
$c['notFoundHandler'] = function ($c) {
    return function ($request, $response) use ($c) {
        syslog(LOG_ERR, 'Slim notFoundHandler error handler');
        return $c['response']->withJson(['message'=>'Page not found'],404);
    };
};
$c['notAllowedHandler'] = function ($c) {
    return function ($request, $response, $methods) use ($c) {
        $uri=$request->getUri();
        $path=$uri->getPath();
        syslog(LOG_ERR, "Slim notAllowedHandler error handler.  $uri $path Method must be one of: " . implode(', ', $methods));
        return $c['response']
        ->withHeader('Allow', implode(', ', $methods))
        ->withJson(['message'=>'Method must be one of: ' . implode(', ', $methods)],405);
    };
};
$c['phpErrorHandler'] = function ($c) {
    return function ($request, $response, $e) use ($c) {
        $msg="Slim phpErrorHandler: {$e->getFile()} ({$e->getline()}): {$e->getMessage()} ({$e->getCode()})";
        syslog(LOG_ERR, $msg);
        return $c['response']->withJson(['message'=>$msg],500);
    };
};

1 个答案:

答案 0 :(得分:0)

类似的事情会起作用:

set_error_handler(function ($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting, so ignore it
        return false;
    }
    syslog(LOG_ERR, "PHP error: $file ($line}): {$message} ({$severity})");
    return true;
});