使用发生错误的 url 登录 laravel 5 时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35322037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:13:23  来源:igfitidea点击:

Error log on laravel 5 with the url where error occured

laravellogginglaravel-5.1error-loggingerror-log

提问by sebasparola

I want to append to each error log, the url of the page the user requested before the error occured. The logs already give me where the error occurs, but it's valuable for me know the url.

我想在每个错误日志中附加用户在错误发生之前请求的页面的 url。日志已经为我提供了错误发生的位置,但是知道 url 对我来说很有价值。

I saw there is a Handler.php file but how can I append the url there?

我看到有一个 Handler.php 文件,但我如何在那里附加 url?

回答by Fabio Antunes

It's quite simple, on your app/Exceptions/Handler.phpon top the of it add this two imports:

这很简单,在你的app/Exceptions/Handler.php上添加这两个导入:

use Request;
use Log;

Then on your report method add this:

然后在您的报告方法中添加以下内容:

public function report(Exception $e) {
    Log::info($e->getMessage(), [
        'url' => Request::url(),
        'input' => Request::all()
    ]);
    return parent::report($e);
}

Now whenever you get an exception the current urlis logged and the request parameters either GETor POSTwill also be logged:

现在,每当您遇到异常时,都会记录当前 url,并且还会记录请求参数GETPOST

[2016-02-10 19:25:13] local.INFO: Error Processing Request {"url":"http://localhost:8002/list","input":{"name":"fabio","surname":"antunes"}} 

回答by fsasvari

Even better way of doing this:

这样做的更好方法:

In App\Exceptions\Handlerextend Laravel's base context()function:

App\Exceptions\Handler扩展 Laravel 的基本context()函数:

use Throwable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;


/**
 * Get the default context variables for logging.
 *
 * @return array
 */
protected function context()
{
    try {
        return array_filter([
            'url' => Request::fullUrl(),
            'input' => Request::except(['password', 'password_confirmation']),
            'userId' => Auth::id(),
            'email' => Auth::user() ? Auth::user()->email : null,
        ]);
    } catch (Throwable $e) {
        return [];
    }
}

回答by Nikolay Votintsev

You can extend context()method in App\Exceptions\Handler. In this implementation, you keep original method and just expand the data array.

您可以在App\Exceptions\Handler 中扩展context()方法。在此实现中,您保留原始方法并扩展数据数组。

protected function context()
{
    try {
        $context = array_filter([
            'url' => Request::url()
        ]);
    } catch (Throwable $e) {
        $context = [];
    }

    return array_merge($context, parent::context());
}