【问题标题】:Error log on laravel 5 with the url where error occuredlaravel 5 上的错误日志以及发生错误的 url
【发布时间】:2016-05-21 04:59:57
【问题描述】:

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

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

【问题讨论】:

    标签: laravel logging laravel-5.1 error-logging error-log


    【解决方案1】:

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

    use Request;
    use Log;
    

    然后在您的报告方法中添加:

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

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

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

    【讨论】:

    • 像魅力一样工作。谢谢大家,很有用。
    • 我发现了一个艰难的方法:在将其写入日志之前,请务必从 Request::all() 数组中取消设置 passwordpassword_confirmation。重大安全风险!
    • 我认为最好不要包含输入,使用 url + 错误行足以开始调试
    • 应该是:使用Illuminate\Http\Request;使用 Illuminate\Support\Facades\Log;
    • @MartijnHiemstra 这些通常在 config/app.php 中有别名
    【解决方案2】:

    更好的方法:

    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 [];
        }
    }
    

    【讨论】:

    • 这是一个更好的答案。
    • 在 Laravel 5.2 中不工作。 (我知道它的旧版本,但由于某些商业原因,我坚持使用它)
    • 我应该在哪个页面添加这段代码以及我应该如何扩展 Laravel 的上下文并将它与我的 app/Exceptions/Handler 连接起来
    • @EmmanuelDavid 您将其添加到“App\Exceptions\Handler.php”中,这一切都在描述中说明
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-10-30
      • 2016-07-06
      • 2014-05-09
      • 2012-03-26
      • 2013-09-17
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多