Setting Up New Relic Logging in Laravel
I’m getting ready to launch a new application soon, and on my launch list I usually include APM and Logging as important items. New Relic not long ago came out with their new logging service. They are offering 100gb of free log ingestion so I figured I would give it a trial run.
Laravel logging by default uses the very powerful Monolog library, but finding good instructions on how to setup a new custom logging channel was a bit of a challenge. Hopefully this guide will provide some useful instructions on how to setup New Relic logging in your applications.
Prerequisites
We are going to assume you have the New Relic PHP agent already installed on your host. If you don’t you can follow these instructions. The benefit of having the agent installed is you don’t need to include the New Relic License Key in your logging handler.
Setup
Start off by installing the New Relic Logs library.composer require newrelic/monolog-enricher
Next we are going edit config/logging.php
and add a new custom log channel.
'newrelic' => [
'driver' => 'custom',
'via' => App\Logging\NewRelicLogger::class,
],
As you can see we are pointing to a new class App\Logging\NewRelicLogger::class
. Let’s create that file in app/Logging/NewRelicLogger.php.
The NewRelicLogger class handles creating the processor and handler for the monolog instance. I also included some additional metadata like the authenticated user email, id, and hostname so that we have some context in every log we record.
Make sure you clear your configuration cache with php artisan config:cache
.
Adding new log entries is easy enough with Laravel using the Log facade.
Log::info('Hi Medium! Thanks for reading!', [
'type' => 'article',
'favorite_soup' => 'Clam Chowder'
]);
Hopefully if you did everything correctly and you will see a log record in New Relic Logs like so.
Thanks for reading! I hope you find this helpful! Cheers.