Skip to content

Instantly share code, notes, and snippets.

@giobi
Created February 4, 2025 15:20
Show Gist options
  • Save giobi/12836d50f71119ee4776083eb3e4aad1 to your computer and use it in GitHub Desktop.
Save giobi/12836d50f71119ee4776083eb3e4aad1 to your computer and use it in GitHub Desktop.
<?php
namespace App\Modules;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
final class NewRelic
{
private $insertKey;
private $accountId;
private $client;
/**
* Constructor.
*
* @param string $insertKey Your New Relic Insert Key.
* @param int $accountId Your New Relic Account ID.
*/
public function __construct($insertKey, $accountId)
{
$this->insertKey = $insertKey;
$this->accountId = $accountId;
// Create a new Guzzle client; you can pass additional options if needed
$this->client = new Client([
'base_uri' => 'https://insights-collector.newrelic.com/',
'timeout' => 5, // seconds
]);
}
public static function send($eventName, $attributes = [])
{
$newRelic = new self(env('NEW_RELIC_INSERT_KEY'), env('NEW_RELIC_ACCOUNT_ID'));
return $newRelic->sendEvent($eventName, $attributes);
}
/**
* Send a single custom event to New Relic.
*
* @param string $eventName The event type (name) you want to record.
* @param array $attributes Key-value pairs of event attributes.
*
* @return bool True on success, false on failure.
*/
public function sendEvent($eventName, array $attributes = [])
{
// Build the payload according to New Relic's Insert API spec
// check if artisan or cli
if (php_sapi_name() === 'cli') {
$attributes['artisan'] = true;
}
$payload = [
[
'eventType' => 'laravelLog',
'event' => $eventName,
'appName' => env('APP_NAME'),
'appUrl' => env('APP_URL'),
// 'framework' => 'Laravel',
'version' => app()->version(),
'hostname' => gethostname(),
'realpath' => realpath(base_path()),
'user' => auth()->user() ? auth()->user()->name : null,
]
];
// Merge user attributes into the first event
$payload[0] = array_merge($payload[0], $attributes);
try {
$response = $this->client->post(
"v1/accounts/{$this->accountId}/events",
[
'headers' => [
'X-Insert-Key' => $this->insertKey,
'Content-Type' => 'application/json',
],
'json' => $payload,
]
);
// Optionally, you could inspect $response->getStatusCode() == 200
if ($response->getStatusCode() === 200) {
return true;
}
} catch (RequestException $e) {
// Log error details as needed
// e.g., error_log($e->getMessage());
return false;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment