sebasparola
sebasparola

Reputation: 200

Error log on Laravel 5 with the URL where error occurred

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

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

Upvotes: 13

Views: 8773

Answers (4)

Hussein Elturkey
Hussein Elturkey

Reputation: 1

Nowadays in laravel 11, you can implement this in your bootstrap/app.php to do the same job:

->withExceptions(function (Exceptions $exceptions) {
        $exceptions->context(fn() => [
            'url' => request()->fullUrl(),
        ]);
    })

Upvotes: 0

fsasvari
fsasvari

Reputation: 1951

Even better way of doing this:

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

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

Upvotes: 21

Nikolay Votintsev
Nikolay Votintsev

Reputation: 472

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

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

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

Upvotes: 4

Fabio Antunes
Fabio Antunes

Reputation: 22882

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

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 url is logged and the request parameters either GET or POST will also be logged:

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

Upvotes: 25

Related Questions