Using PaperTrail & Slack For Laravel Logging

Josh Pollock - July 21, 2017

I really like Papertrail – it’s a simple service that gives you a live updating view of your logs. I wrote a post for Torque awhile ago about using it in WordPress. Since we launched Caldera Forms Pro, most of which is built in Laravel, I’ve been meaning to setup Papertrail for logging.

When we launched, I had built a quick Slack webhook integration to send warnings and errors into Slack channel — and therefore my phone. I also have Laravel Log Viewer. Still I missed having real time log viewing.

I did some googling and found some info, but nothing complete. I got it working base on what I found in Matt Stauffer’s excellent Laravel with Forge series and in the docs and thought I’d share how I got it to send everything logged with Laravel’s Monolog instance to Papetrail.

Make It So

Before starting you need to find the URL and port for your Papertrail log destination. You can use this link while logged into find it. I then put that URL and port in the .env variables “PAPERTRAIL_URL” and “PAPERTRAIL_PORT”.

Then I used the register method of my application service provider to add a new “SyslogUdpHandler” handler, which reading the Monolog source tells me is “for logging to a remote syslogd server” which I assume Papertrail is because this works.

<?php
namespace App\Providers;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\SyslogUdpHandler;
class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$url = env( 'PAPERTRAIL_URL', '' );
if ( filter_var( $url, FILTER_VALIDATE_URL ) ) {
$output = "%channel%.%level_name%: %message%";
$formatter = new LineFormatter( $output );
$logger = Log::getMonolog();
$syslogHandler = new SyslogUdpHandler( "logs6.papertrailapp.com", env( 'PAPERTRAIL_PORT' ) );
$syslogHandler->setFormatter( $formatter );
$logger->pushHandler( $syslogHandler );
}
}
}

That’s About It

Just a quick post I wanted to share. I also setup the Papertrail system logger on the server, so that I get all system logs, but pretty sure that’s more than I need and I’ll remove that.