Laravel 5.7 如何使用 URL 记录 404

标签 laravel laravel-5.7 laravel-exceptions

我想在 Laravel 5.7 中记录 404 错误,但我不明白如何打开它。除了记录 404 错误之外,我还想记录所请求的 URL。其他错误已正确记录。

.env

APP_DEBUG=true
LOG_CHANNEL=stack

config/logging.php

'stack' => [
    'driver' => 'stack',
    'channels' => ['daily'],
],

根据 Error Handling documentation :

The $dontReport property of the exception handler contains an array of exception types that will not be logged. For example, exceptions resulting from 404 errors, as well as several other types of errors, are not written to your log files. You may add other exception types to this array as needed:

app/Exceptions/Handler 中,$dontReport 数组为空。

我通过 Blade 文件 resources/views/errors/404.blade.php

自定义了 404 View

基于this answer我已在 app/Exceptions/Handler 中尝试过此代码, 但日志中没有显示任何内容:

public function report(Exception $exception)
{
    if ($this->isHttpException($exception)) {
        if ($exception instanceof NotFoundHttpException) {
            Log::warning($message);
            return response()->view('error.404', [], 404);
        }
        return $this->renderHttpException($exception);
    }

    parent::report($exception);
}

接受 Mozammil 的答案后进行更新,效果很好。 我已将他的回答缩短为以下内容。不要忘记将 use Illuminate\Support\Facades\Log 添加到处理程序文件中。

public function render($request, Exception $exception)
{
    if ($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
        Log::warning('404: ' . $request->url());
        return response()->view('errors.404', [], 404);
    }
    return parent::render($request, $exception);
}

最佳答案

我也有类似的需求。这是我实现这一目标的方法。

我有一个辅助方法来确定它是否是 404。

private function is404($exception)
{
    return $exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException
            || $exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
}

我还有另一种方法来实际记录 404。

private function log404($request) 
{
    $error = [
        'url'    => $request->url(),
        'method' => $request->method(),
        'data'   => $request->all(),
    ];

    $message = '404: ' . $error['url'] . "\n" . json_encode($error, JSON_PRETTY_PRINT);

    Log::debug($message);
}

然后,为了记录错误,我只需在 render() 方法中执行类似的操作:

public function render($request, Exception $exception)
{
    if($this->is404($exception)) {
        $this->log404($request);
    }

    return parent::render($request, $exception);
}

我不知道$internalDontReport。然而,在所有情况下,我的实现都对我有用:)

关于Laravel 5.7 如何使用 URL 记录 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54392184/

相关文章:

laravel - 如何为创建的用户发送电子邮件验证?

php - Laravel 异常 405 方法不允许

php - Laravel 自定义异常

php - 为什么 laravel save() 会这样工作(有时会返回 false)

javascript - 如何在点击提交按钮之前检测我被点击的位置

arrays - 将 Laravel 路由中的数组传递给 Blade 模板

laravel - Composer 要求 laravel/passport 在 laravel 5.8 中不起作用

php - Laravel 5.7 验证带星号的字段,required_if

php - Laravel Collective 中多重选择的选定值