Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mbo's avatar
Level 3

Logging 404

good day,

I moved over an wordpress website to laravel. By doing so i want to keep track of 404 errors.

So a created a custom handler and in this handler the url that is not found is saved.

I like to add the url where the link is activated (clicked). What is the best way to do this?

I was thinking of

(basename(url()->previous()) 

Any better idea's?

thanks for the reaction

maarten

0 likes
1 reply
MichalOravec's avatar

Add this to your app\Exceptions\Handler.php

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Support\Facades\Log;
use Request;

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Throwable  $exception
 * @return \Symfony\Component\HttpFoundation\Response
 *
 * @throws \Throwable
 */
public function render($request, Throwable $exception)
{
    if ($exception instanceof ModelNotFoundException || $exception instanceof NotFoundHttpException) {
        $url = Request::fullUrl();

        Log::info("404 in {$url}");
    }

    return parent::render($request, $exception);
}

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

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

The context method is useful if you want to store additional informations for all errors in the log file.

1 like

Please or to participate in this conversation.