esk*_*imo 4 laravel laravel-exceptions laravel-5.7
我想在 Laravel 5.7 中记录 404 错误,但我不明白如何打开它。除了记录 404 错误之外,我还想记录请求的 URL。其他错误被正确记录。
.env
APP_DEBUG=true
LOG_CHANNEL=stack
Run Code Online (Sandbox Code Playgroud)
配置/日志记录.php
'stack' => [
'driver' => 'stack',
'channels' => ['daily'],
],
Run Code Online (Sandbox Code Playgroud)
根据错误处理文档:
异常处理程序的 $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);
}
Run Code Online (Sandbox Code Playgroud)
接受 Mozammil 的回答后更新,效果很好。
我已经缩短了他对下面的回答。不要忘记添加use Illuminate\Support\Facades\Log到处理程序文件中。
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);
}
Run Code Online (Sandbox Code Playgroud)
我也有类似的需求。这是我如何实现的。
我有一个辅助方法来确定它是否是 404。
private function is404($exception)
{
return $exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException
|| $exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
}
Run Code Online (Sandbox Code Playgroud)
我还有另一种方法来实际记录 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);
}
Run Code Online (Sandbox Code Playgroud)
然后,为了记录错误,我只是在render()方法中做这样的事情:
public function render($request, Exception $exception)
{
if($this->is404($exception)) {
$this->log404($request);
}
return parent::render($request, $exception);
}
Run Code Online (Sandbox Code Playgroud)
我不知道$internalDontReport. 但是,在所有情况下,我的实现都对我有用:)
| 归档时间: |
|
| 查看次数: |
2756 次 |
| 最近记录: |