Cakephp 3 - 如何在单独的文件中记录所有 404 错误

Cakephp 3 - how can I log all 404 errors in a separate file

机器人或黑客用 /phpmyadmin/ 等不存在的 URL 请求轰炸我们的网站,这使我的错误日志变得毫无用处,因为我需要查看的错误非常少而且介于两者之间。我不想使用 skiplog 选项跳过记录它们,因为我仍然可能需要在某些时候查看所有这些 NotFoundException 和 MissingControllerExceptions。

在您的 app.php 文件中配置一个新的日志选项:

'Log' => [
    '404' => [
        'className' => 'Cake\Log\Engine\FileLog',
        'path' => LOGS,
        'file' => '404',
        'url' => env('LOG_ERROR_URL', null),
        'scopes' => ['404'],
    ],
    ...

在此处创建一个新文件:src/Error/AppErrorHandler.php 使用此内容

namespace App\Error;

use Cake\Error\ErrorHandler;
use Cake\Log\Log;
use Exception;
class AppErrorHandler extends ErrorHandler
{
    /**
     * Handles exception logging
     *
     * @param \Exception $exception Exception instance.
     * @return bool
     */
    protected function _logException(Exception $exception)
    {
        $notFoundExceptions = [
            'Cake\Routing\Exception\MissingControllerException',
            'Cake\Http\Exception\NotFoundException',
            'Cake\Http\Exception\UnauthorizedException',
        ];
        if (in_array(get_class($exception), $notFoundExceptions)) {
            return Log::error($this->_getMessage($exception), '404');
        } else {
            return parent::_logException();
        }
    }
}

在您应用的 bootstrap.php 文件中注册此 AppErrorHandler。对我来说,这意味着在第 109 行中替换默认 ErrorHandler (new ErrorHandler(Configure::read('Error')))->register(); 的注册,如下所示:

(new \App\Error\AppErrorHandler(Configure::read('Error')))->register();