首页 > 解决方案 > Cakephp:错误处理问题(错误未插入 error_log 表)

问题描述

在我们的应用程序中,我们处理所有错误并插入到 tbl_error_log 表中。但由于某种原因,它已经停止工作,现在除了初始化函数错误之外,没有错误插入到 error_log 表中。如果初始化函数出错,那么它正在工作。我们使用下面的代码插入错误。

文件路径 :Vendor/Cakephp/Cakephp/src/Error/BaseErrorhandler.php

protected function _logError($level, $data) {
    $ErrorLogTable = TableRegistry::get('tbl_error_log');
    $errorlog      = $ErrorLogTable->newEntity();

    $errorlog->in_user_id       = $User['member_id'];
    $errorlog->st_email_address = $User['email'];
    $errorlog->in_error_no      = $data['code'];
    $errorlog->st_error_type    = $data['error'];
    $errorlog->st_error_string  = $data['description'];
    $errorlog->st_error_file    = $data['file'];
    $errorlog->in_error_line_no = $data['line'];
    $errorlog->dt_error_time    = new \DateTime('now');
    $errorlog->st_from_ip       = $this->getClientIp();

    $ErrorLogTable->save($errorlog);
}

标签: cakephperror-handlingcakephp-3.0

解决方案


我不能谈论仅从某些代码部分记录的错误的问题,但通常这不是如何进行 custo 日志记录。永远不要修改供应商文件(当然除非出于测试目的),它们最终会在更新依赖项时被覆盖。

如果要实现自定义日志记录功能,请创建一个自定义记录器,如文档中所示:

// src/Log/Engine/DatabaseLog.php

namespace App\Log\Engine;
use Cake\Log\Engine\BaseLog;

class DatabaseLog extends BaseLog
{
    public function __construct($options = [])
    {
        parent::__construct($options);
        // ...
    }

    public function log($level, $message, array $context = [])
    {
        // Write to the database.
    }
}

请参阅Cookbook > 日志记录 > 创建日志适配器

您可以通过相应地更改config/app.php文件中的配置将其用作默认记录器:

'Log' => [
    'debug' => [
        'className' => 'Database',
        'scopes' => false,
        'levels' => ['notice', 'info', 'debug'],
    ],
    'error' => [
        'className' => 'Database',
        'scopes' => false,
        'levels' => ['warning', 'error', 'critical', 'alert', 'emergency'],
    ],
    // ...
],

推荐阅读