PHP Exception & Error Tracking

Typical installation time: 3 minutes

Hi there! You've found Honeybadger's guide to PHP exception and error tracking. Note: if you use Laravel, go check out the Laravel Integration Guide. If not, then read on!

This guide will teach you how to install and configure the default Honeybadger for PHP client and use it to manually report errors to Honeybadger.

On this page:


First, install the honeybadger-php package via composer:

composer require honeybadger-io/honeybadger-php

Then, configure the Honeybadger client in your application:

$honeybadger = Honeybadger\Honeybadger::new([ 'api_key' => 'Your project API key' ]);

Honeybadger can report exceptions in several ways. To test that the Honeybadger client is working, try sending a custom notification:

$honeybadger->customNotification([ 'title' => 'Special Error', 'message' => 'Special Error: a special error has occurred', ]);

To catch exceptions in your code and report them to Honeybadger:

try { throw new Exception('Whoops!'); } catch (Exception $e) { // You can optionally include your own // \Symfony\Component\HttpFoundation\Request::class request. $honeybadger->notify($e, $app->request()); }

Adding Context

In Honeybadger, context is a custom array of data that's displayed with your error reports. You can add context from anywhere in your app, and it will be included automatically when reporting errors. For example, you could include the ID of the currently logged-in user:

$honeybadger->context('user_id', $this->Auth->user('id'));

See Customizing Error Reports for more info.

Handling Service Exceptions

When the client is unable to send a report to Honeybadger's service, it will throw an instance of \Honeybadger\Exceptions\ServiceException. To prevent this from crashing your app and hiding the original error, you can set the service_exception_handler option to a closure where you can handle the exception yourself:

$honeybadger = Honeybadger\Honeybadger::new([ 'api_key' => 'Your project API key', 'service_exception_handler' => function (ServiceException $e) { $logger->error($e); }, ]);

Using Honeybadger as a Logger

If you're using the PHP logging library Monolog in your app, you can also choose to use Honeybadger as a log handler, by using the LogHandler class. Then write log messages as normal with Monolog, and they'll show up on your Honeybadger dashboard.

$logger = new Monolog\Logger('my-logger'); $honeybadger = Honeybadger\Honeybadger::new([ 'api_key' => 'my-api-key' ]); $logger->pushHandler(new Honeybadger\LogHandler($honeybadger)); $logger->info('An info message'); $logger->info('An info message with context data', ["some-key" => "some-value"]); $logger->error('An error message');

If you include an exception context item in your error messages, we'll automatically format them for easy viewing:

$e = new \Exception('Something happened'); $logger->error('An error message', ['exception' => $e]);