laravel - 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);
}
解决方案
我有类似的要求。以下是我实现它的方法。
我有一个帮助方法来确定它是否是 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
。但是,在所有情况下,我的实现都对我有用:)
推荐阅读
- python - Keras 如何优化没有激活的层的权重?
- google-app-engine - 如何在 Google App Engine 中获取一段时间内的任务数?
- sql - PostgreSQL distinct on + order by 查询优化
- angular - index.html 中的条件视口元标记
- mysql - 用户生成的标签是否应该存储在单独的数据库表中?
- c# - SAP 中间件连接器错误
- google-cloud-platform - 为 GCP SQL 实例分配静态 IP
- sbt - 使用 sbt 在 fat jar manifest 中添加 git commit id
- php - (PHP) 你可以在计算中使用 if 语句的结果吗?
- redis - Redis sentinel 不会自动更新它正在监视的 IP 地址