将 PHP 异常和错误记录到数据库 table PHP Slim 3

Log PHP exceptions and Errors to Database table PHP Slim 3

所以我试图找到让 PHP SLIM 3 将 PHP 异常和错误记录到数据库 table 而不是日志的最佳方法。什么是最好的方法来完成这个?到目前为止在文档中推荐这个。

依赖关系:

$app = new \Slim\App();
$c = $app->getContainer();
$c['errorHandler'] = function ($c) {
    return function ($request, $response, $exception) use ($c) {
        return $response->withStatus(500)
            ->withHeader('Content-Type', 'text/html')
            ->write('Something went wrong!');
    };
};

我无法理解的是在哪里调用它以及如何连接它以将其登录到我创建的数据库 table 中。有任何想法吗?

你在 Slim 3 上试过这个吗?


$config = [
    'settings' => [
        'displayErrorDetails' => true,

        'db' => [
            'driver' => 'mysql',
            'host' => 'localhost',
            'username' => 'root',
            'database' => 'test',
            'password' => '',
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
           'flags' => [
               PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
           ],
        ]
    ],
];

$app = new \Slim\App($config);

$container = $app->getContainer();

$container[PDO::class] = function ($container) {
    $settings = $container['settings']['db'];

    $host = $settings['host'];
    $dbname = $settings['database'];
    $username = $settings['username'];
    $password = $settings['password'];
    $charset = $settings['charset'];
    $flags = $settings['flags'];
    $dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";

    return new PDO($dsn, $username, $password, $flags);
}

$container[PDO::class] = function ($container) {
    $settings = $container['settings']['db'];

    $host = $settings['host'];
    $dbname = $settings['database'];
    $username = $settings['username'];
    $password = $settings['password'];
    $charset = $settings['charset'];
    $flags = $settings['flags'];
    $dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";

    return new PDO($dsn, $username, $password, $flags);
};

$container ['errorHandler'] = function ($container ) {
    $connection = container[PDO::class];

    return function ($request, $response, $exception) use ($connection) {

        $row = [
            'message' => $exception->getMessage(),
        ];

        $sql = "INSERT INTO error_logs SET message=:message";

        $connection->prepare($sql)->execute($row);

        return $response->withStatus(500)
            ->withHeader('Content-Type', 'text/html')
            ->write('Something went wrong!');
    };
};