All guides
Errors and events·3 min read

SEND ERRORS FROM PHP AND LARAVEL

Report exceptions and events from PHP, with a Laravel example.

1

Add the function

It works in any PHP 7.4+ app and needs no extensions:

function upguru_report(string $level, string $message, array $context = []): void
{
    @file_get_contents(getenv('UPGURU_PUSH_URL'), false, stream_context_create(['http' => [
        'method' => 'POST',
        'header' => "Content-Type: application/json\r\n",
        'content' => json_encode(['level' => $level, 'message' => $message, 'context' => (object) $context]),
        'timeout' => 5,
    ]]));
}
2

Report exceptions

try {
    $gateway->charge($order);
} catch (Throwable $e) {
    upguru_report('error', $e->getMessage(), ['exception' => [
        'class' => get_class($e), 'message' => $e->getMessage(),
        'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(),
    ]]);
    throw $e;
}

With file and line, every error group shows where it happened.

3

In Laravel

In Laravel 11 and newer, report every exception from bootstrap/app.php. Put upguru_report() in a file that's always loaded, e.g. app/helpers.php listed under autoload.files in composer.json.

->withExceptions(function (Exceptions $exceptions) {
    $exceptions->report(function (Throwable $e) {
        upguru_report('error', $e->getMessage(), ['exception' => [
            'class' => get_class($e), 'message' => $e->getMessage(),
            'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(),
        ]]);
    });
})
Add UPGURU_PUSH_URL=… to your .env file. Laravel's own logging keeps working as before.