Skip to main content

Simple Query Logging with Heroku, Papertrail and Laravel

May 22 '15

One frequent need for beta and production stage applications is to log all queries to a facility which can be analyzed by developers. Papertrail provides such a facility for Heroku applications. I’ll walk you through an easy method to use Papertrail to provide live query logging capabilities.

First, install the Papertrail addon to your Heroku app. Next, we want to set logging to use stderr. Edit app/start/global.php and find the section labeled “Application Error Logging”. By default, Laravel is configured to use a single log file located at app/storage/logs/laravel.log.

Replace the line that reads

Log::useFiles(storage_path().'/logs/laravel.log');
</php
<p>
</p>
 
<p>with</p>
<p>
</p>
<php>
Log::useFiles('php://stderr');

Optionally, you could check the application’s current environment and enable file-based login selectively, which might be useful if you want to use the file-based logging method locally and Papertrail on your Heroku app:

if (App::environment('heroku'))
{
  Log::useFiles('php://stderr');
}
else
{
  Log::useFiles(storage_path().'/logs/laravel.log');
}

At this point, we have a Laravel app which will log to Papertrail. Now we just need to instruct Laravel to log all queries. We can create an event listener to do this. In app/start/global.php, right below your Log::useFiles call, insert the following listener:

Event::listen("illuminate.query", function($query, $bindings, $time, $name)
{ 
  \Log::info($query."\n"); 
  \Log::info(json_encode($bindings)."\n"); 
});

That’s it! Now push your application to Heroku and check Papertrail. You should see all queries along with any variables bound to them. Happy logging!