Configuring centralized logging from PHP apps

Papertrail can accept logs from any PHP app, including CakePHP, CodeIgniter, Laravel, Symfony, Zend, and “plain” PHP.

If you aren’t sure how to configure logging for your PHP app at all, start with the PHP manual coverage of Error Handling, especially Error Handling Functions.

Method A: Use log file

Configure your Web server or app to log to a file as usual, then use remote_syslog2 to watch that file. Setup instructions.

Method B: Send remote syslog from PHP app

Where the setup above do not suffice, your app can send a log message directly to Papertrail. Here are a few ways to send syslog to Papertrail from PHP.

Generic PHP log sender

Here is simple PHP code to construct and transmit a UDP remote syslog log message.

As the code comments show, call that PHP function from your app (or from a log handler) to transmit the message to Papertrail.

Monolog

Consider Monolog and its SyslogHandler or SyslogUdpHandler. This works particularly well with Laravel and Laravel Forge, since Laravel already uses Monolog.

For example, here is an example Monolog SyslogUdpHandler which sends to Papertrail:

require 'vendor/autoload.php';

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\SyslogUdpHandler;

// Set the format
$output = "%channel%.%level_name%: %message%";
$formatter = new LineFormatter($output);

// Setup the logger
$logger = new Logger('my_logger');
$syslogHandler = new SyslogUdpHandler("logsN.papertrailapp.com", XXXXX);
$syslogHandler->setFormatter($formatter);
$logger->pushHandler($syslogHandler);

// Use the new logger
$logger->addInfo('Monolog test');

Change logsN and XXXXX to match your Papertrail log destination

Kohana

Users of the Kohana framework can use the kohana-papertrail module. Setup instructions can be found in the README.

Logging via the Heroku add-on

Rather than logging directly to syslog, send everything to stderr and Heroku will forward it over to Papertrail. An example of how do this using Monolog, adapted from this Heroku Dev Center article, is shown below.

require('vendor/autoload.php');

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;

// set the format
$output = "%message%";
$formatter = new LineFormatter($output);

// create a log channel to STDOUT
$log = new Logger('my_logger');
$streamHandler = new StreamHandler('php://stdout', Logger::WARNING);
$streamHandler->setFormatter($formatter);
$log->pushHandler($streamHandler);

// test messages
$log->addWarning("testing 1");
$log->addWarning("testing 2");