Friday, September 20, 2013

How To integrate Laravel 4 with New Relic

A basic How To on integrating Laravel 4 with New Relic.
I will assume that you have already installed and configured the New Relic PHP module. I will also assume that you have already configured your site to set the New Relic application name.

You can integrate monolog to send Laravel 4 application errors to NewRelic:

<?php
// probably in your app/start/production.php
use Monolog\Handler\NewRelicHandler;
use Monolog\Logger;
$monolog = Log::getMonolog();
$monolog->pushHandler(new NewRelicHandler(Logger::DEBUG, false, 'App Name'));

But I found that this did not work as I had hoped. I find the monolog documentation to be poor and thus I am probably not leveraging it as well as it could be. You can find some basic documentation for monolog in vendor/monolog/monlog/doc.

I use controllers in Laravel and my controllers represent each sub-system of my websites. For example, I may have AuthController.php, NewsController.php, CommentController.php, etc. All my controllers are extended from app/controllers/BaseController.php in one way or another. All the extended controllers call their parent constructors - this is important

Here is my app/controllers/BaseController.php:

<?php
class BaseController extends Controller
{
    public function __construct()
    {
        // NewRelic Extension?
        if ( extension_loaded( 'newrelic' ) )
        {
            newrelic_name_transaction( get_class( $this ) );
        }
    }
....
}

And, as an example, here is my app/controllers/NewsController.php:

class NewsController extends BaseController
{
 public function __construct()
 {
  parent::__construct();

 }
...
}

Here is an example of what you may see in New Relic.

New Relic screen shot
New Relic screen shot

If you want finer resolution in your reporting then you should review the New Relic PHP API for more details.

Reference Material: New Relic PHP API


4 comments:

  1. Have you taken a look at the Laravel-NewRelic composer package?
    https://github.com/In-Touch/laravel-newrelic

    Then you can simply call NewRelic::setAppName( 'foo' ) from the App::before event and not have to subclass your controllers.

    ReplyDelete
    Replies
    1. Wasn't aware of it! I'll give it a try, Thank you!

      Delete
    2. I would highly recommend the intouch/newrelic for anyone who is reading this. It's very easy to implement and provides the information you are looking for. The auto-naming feature uses your routes!

      Delete
    3. could you provide sample example to setup intouch/newrelic for laravel 5.6

      Delete