Faran Khan
Faran Khan

Reputation: 1593

Displaying the error in production mode with log number in laravel

I have an application built in laravel 5.8 which is in production mode. As the site is live I don't want to display any errors to our users. But If some error occurs then I want the log number or any reference that indicates what error was thrown at that particular time.

So I wanted to know if there is any way to display "Oops something went wrong ref#123456" to our users. So that they can send us a screenshot or reference number and we can track what actually happend by checking our log file.

Thanks in advance. Happy coding.

Upvotes: 7

Views: 3257

Answers (3)

omitobi
omitobi

Reputation: 7334

It should be as simple as using uniqueid() function to create an id for an exception, and returning a view in the render part of your app.

public function render($request, Exception $exception)
{
    $errorCode = uniqid('error_');

    Log::error("$errorCode", [
        //... The log information here
    ]);

    return view('welcome', compact('errorCode'));
}

As an example above I am using the default welcome.blade.php page, and then showing the content below:

Error occurred #error_5ec385d7c4d25

It means you can actually search your logs for this error code to know what went wrong.

Upvotes: 0

Luis Ozuna
Luis Ozuna

Reputation: 425

I thing that you can do it saving the logs in database and render its id.

You can do it in App\Exceptions\Handler: https://laravel.com/docs/5.8/errors

For example:

    /**
     * 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)
    {
        // Create log in db
        $log = Log::create([
            'message' => $exception->getMessage(), 
            'code' => $exception->getCode(),
            'line' => $exception->getLine(),
        ]);

        // Print log id in logs
        logger("LogId {$log->id}");

        //Return view error with log id
        return return response()->view('errors', ['logId' => $log->id]);
    }

Upvotes: 6

TEFO
TEFO

Reputation: 1653

maybe you want something more professional than logging the exception, and laravel have a great package for it named telescope you got all your exceptions and queries or events redis and ... so many. you can authorize the users that only admins can access telescope information. and because its a lot of info probably you want prune the records with a seceule:

$schedule->command('telescope:prune --hours=48')->daily();

all of this you can find it in docs: https://laravel.com/docs/telescope

Upvotes: 0

Related Questions