gpt4 book ai didi

Laravel 5.7 如何使用 URL 记录 404

转载 作者:行者123 更新时间:2023-12-02 15:27:09 25 4
gpt4 key购买 nike

我想在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com