首页 > 解决方案 > Laravel 5.7 如何使用 URL 记录 404

问题描述

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

.env

APP_DEBUG=true
LOG_CHANNEL=stack

配置/日志记录.php

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

根据错误处理文档

异常处理程序的 $dontReport 属性包含一个不会记录的异常类型数组。例如,由 404 错误以及其他几种类型的错误导致的异常不会写入您的日志文件。您可以根据需要向该数组添加其他异常类型:

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

我通过拥有 Blade 文件自定义了 404 视图resources/views/errors/404.blade.php

基于这个答案,我尝试了这段代码,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到 Handler 文件。

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);
}

标签: laravellaravel-5.7laravel-exceptions

解决方案


我有类似的要求。以下是我实现它的方法。

我有一个帮助方法来确定它是否是 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。但是,在所有情况下,我的实现都对我有用:)


推荐阅读