Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Newrelic Bundle Laravel Package

ekino/newrelic-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ekino/newrelic-bundle
    

    Add to config/bundles.php:

    Ekino\NewRelicBundle\EkinoNewRelicBundle::class => ['all' => true],
    
  2. Configuration Add to config/packages/ekino_newrelic.yaml:

    ekino_newrelic:
        license_key: '%env(NEW_RELIC_LICENSE_KEY)%'
        application_name: '%env(NEW_RELIC_APP_NAME)%'
    
  3. First Use Case

    • Automatic Transaction Naming: The bundle auto-names transactions by route/controller. Verify in New Relic dashboard under "Transactions" to see Symfony routes appear.
    • Console Commands: Run a command (e.g., php bin/console cache:clear) and check New Relic for the transaction named after the command.

Implementation Patterns

Core Workflows

  1. Custom Transaction Naming Override the default naming strategy by implementing Ekino\NewRelicBundle\TransactionNamingStrategy\TransactionNamingStrategyInterface:

    // src/Transaction/Naming/CustomNamingStrategy.php
    use Ekino\NewRelicBundle\TransactionNamingStrategy\TransactionNamingStrategyInterface;
    
    class CustomNamingStrategy implements TransactionNamingStrategyInterface
    {
        public function getTransactionName(Request $request): string
        {
            return 'Custom:' . $request->get('_route');
        }
    }
    

    Register in config/packages/ekino_newrelic.yaml:

    ekino_newrelic:
        transaction_naming_strategy: App\Transaction\Naming\CustomNamingStrategy
    
  2. Ignoring Routes/URLs Exclude specific routes or URLs from tracking:

    ekino_newrelic:
        ignored_routes: ['app_login', 'app_logout']
        ignored_urls: ['^/health', '^/api/v1/webhooks']
    
  3. Custom Attributes Add custom attributes to transactions (e.g., user ID, plan type):

    use Ekino\NewRelicBundle\NewRelic;
    
    class MyController extends AbstractController
    {
        public function index(Request $request, NewRelic $newRelic)
        {
            $newRelic->addCustomAttribute('user_id', $request->get('user_id'));
            return $this->render('...');
        }
    }
    
  4. Error Handling Automatically capture exceptions with custom error messages:

    $newRelic->noticeError('Failed to process payment', ['user_id' => 123]);
    
  5. Background Jobs Name background jobs (e.g., queues) explicitly:

    $newRelic->setTransactionName('Background:ProcessOrder');
    

Integration Tips

  • Symfony Events Listen to kernel.request to dynamically modify transaction names or attributes:

    // src/EventListener/NewRelicListener.php
    use Ekino\NewRelicBundle\NewRelic;
    use Symfony\Component\HttpKernel\Event\RequestEvent;
    
    class NewRelicListener
    {
        public function onKernelRequest(RequestEvent $event, NewRelic $newRelic)
        {
            if ($event->isMainRequest()) {
                $newRelic->addCustomAttribute('locale', $event->getRequest()->getLocale());
            }
        }
    }
    

    Register in config/services.yaml:

    services:
        App\EventListener\NewRelicListener:
            tags:
                - { name: 'kernel.event_listener', event: 'kernel.request', method: 'onKernelRequest' }
    
  • API Requests For API endpoints, use Ekino\NewRelicBundle\NewRelic to set custom transaction names:

    $newRelic->setTransactionName('API:Users:Get');
    
  • Console Commands Extend Ekino\NewRelicBundle\Command\NewRelicAwareCommand for automatic command naming:

    use Ekino\NewRelicBundle\Command\NewRelicAwareCommand;
    
    class MyCommand extends NewRelicAwareCommand
    {
        protected function configure()
        {
            $this->setName('app:custom-task');
            // Transaction name auto-set to 'app:custom-task'
        }
    }
    

Gotchas and Tips

Pitfalls

  1. License Key Validation

    • The bundle does not validate the New Relic license key on startup. Silent failures may occur if the key is invalid. Test in a staging environment first.
    • Fix: Use NEW_RELIC_DEBUG env var to enable verbose logging:
      ekino_newrelic:
          debug: '%env(bool:NEW_RELIC_DEBUG)%'
      
  2. Transaction Name Collisions

    • Default naming (e.g., controller_name_action) may clash with other transactions. Use ignored_routes or a custom strategy to avoid duplicates.
    • Tip: Prefix custom transactions (e.g., Custom:MyTransaction).
  3. Console Command Overhead

    • New Relic adds overhead to console commands. Disable for long-running or non-critical commands:
      ekino_newrelic:
          ignore_console_commands: ['app:long-running-task']
      
  4. Attribute Limits

    • New Relic has a 300KB limit for custom attributes per transaction. Avoid logging large payloads (e.g., entire request bodies).
    • Tip: Use serialize() for complex data and truncate strings:
      $newRelic->addCustomAttribute('user_data', substr(serialize($user), 0, 1000));
      
  5. Caching and New Relic

    • Cached responses (e.g., cache:page) may show as duplicate transactions. Use ignored_urls to exclude cache routes:
      ekino_newrelic:
          ignored_urls: ['^/cache']
      
  6. Symfony 5.4+ Deprecations

    • The bundle is unmaintained post-2022. Test thoroughly with newer Symfony versions (e.g., 6.x). Consider forking if critical issues arise.

Debugging

  1. Enable Debug Mode

    ekino_newrelic:
        debug: true
    
    • Logs transaction names and attributes to var/log/dev.log.
  2. Check Transaction Names

    • Use NewRelic::getTransactionName() to verify current transaction names in runtime:
      $currentName = $newRelic->getTransactionName();
      $this->addFlash('debug', "Current transaction: $currentName");
      
  3. New Relic UI Tips

    • Filter transactions by symfony.route or symfony.controller in the New Relic dashboard.
    • Use the "Attributes" tab to inspect custom attributes added via the bundle.
  4. Common Errors

    • "Transaction name too long": New Relic truncates names after 255 characters. Shorten custom names or use route-based naming.
    • "License key invalid": Verify the key in NEW_RELIC_LICENSE_KEY and check for typos.

Extension Points

  1. Custom Transaction Naming Strategies

    • Implement TransactionNamingStrategyInterface for full control over naming logic. Example:
      class RouteBasedNamingStrategy implements TransactionNamingStrategyInterface
      {
          public function getTransactionName(Request $request): string
          {
              $route = $request->attributes->get('_route');
              return $route ? "Route:$route" : 'Unknown';
          }
      }
      
  2. Event Listeners

    • Extend functionality by subscribing to ekino_newrelic.transaction events:
      use Ekino\NewRelicBundle\Event\TransactionEvent;
      
      $dispatcher->addListener('ekino_newrelic.transaction', function (TransactionEvent $event) {
          if ($event->getTransactionName() === 'API:Users:Get') {
              $event->setTransactionName('API:Users:Fetch');
          }
      });
      
  3. Custom Metrics

    • Use New Relic’s PHP API directly via the bundle’s NewRelic service:
      $newRelic->increment('custom.metric.count');
      $newRelic->recordMetric('custom.metric.value', 42);
      
  4. Middleware Integration

    • Add New Relic logic to middleware:
      use Ekino\NewRelicBundle\NewRelic;
      
      class NewRelicMiddleware implements MiddlewareInterface
      {
          public function __construct(private NewRelic $newRelic) {}
      
          public function process(Request $request, RequestHandler $handler): Response
          {
              $this->newRelic->addCustomAttribute('middleware', 'auth');
              return $handler->handle($request);
          }
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware