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

Monolog Sentry Bundle Laravel Package

dziki/monolog-sentry-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dziki/monolog-sentry-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Dziki\MonologSentryBundle\DzikiMonologSentryBundle::class => ['all' => true],
    ];
    
  2. Configure Sentry: Add Sentry client configuration to config/packages/dev/monolog.yaml (or your environment):

    monolog:
        handlers:
            sentry:
                type: sentry
                dsn: "%env(SENTRY_DSN)%"
                level: !php/const Monolog\Logger::ERROR
                bubble: false
                channels: ["!doctrine", "!console"]
                with_locals: true
                with_extra: true
    
  3. First Use Case: Log an error with enriched context:

    $this->logger->error('Failed to process payment', [
        'user_id' => $user->id,
        'amount' => $amount,
    ]);
    

    The bundle auto-attaches:

    • User data (if available in Request or User context)
    • User agent (parsed)
    • Symfony version
    • Git revision (if in a Git repo)

Implementation Patterns

Core Workflows

  1. Context Injection:

    • Request Context: Automatically attaches user, ip, user_agent, and referer from the Symfony Request stack.
    • User Context: Uses security.token_storage to fetch the current user (must implement Serializable or have a getId() method).
    • Custom Context: Override Dziki\MonologSentryBundle\Processor\UserContextProcessor to inject additional data:
      public function __invoke(array $record): array {
          $record['extra']['custom_data'] = $this->getCustomData();
          return $record;
      }
      
  2. Tagging Strategy:

    • Define global tags in config/packages/monolog.yaml:
      monolog:
          processors:
              dziki.sentry.tags: ['env:production', 'app:myapp']
      
    • Dynamically add tags per log:
      $this->logger->critical('Database down', [], ['tag' => 'db']);
      
  3. Environment-Specific Logging:

    • Disable in dev:
      # config/packages/dev/monolog.yaml
      monolog:
          handlers:
              sentry:
                  level: !php/const Monolog\Logger::OFF
      
  4. Integration with Monolog Channels:

    • Route logs to Sentry only for specific channels (e.g., api.errors):
      monolog:
          channels:
              - { name: api.errors, type: channel }
          handlers:
              sentry:
                  channels: ["api.errors"]
      

Advanced Patterns

  • Git Metadata: Enable Git revision logging by adding to config/packages/monolog.yaml:

    monolog:
        processors:
            dziki.sentry.git: true
    

    Requires git CLI installed on the server.

  • Custom Processors: Create a service to extend context:

    // src/Service/CustomSentryContext.php
    class CustomSentryContext implements ProcessorInterface {
        public function __invoke(array $record): array {
            $record['extra']['feature_flag'] = $this->featureFlagService->isEnabled('new_ui');
            return $record;
        }
    }
    

    Register in config/services.yaml:

    services:
        App\Service\CustomSentryContext:
            tags: ['monolog.processor']
    

Gotchas and Tips

Pitfalls

  1. User Context Missing:

    • If $user is not attached, the bundle silently skips user-related fields. Ensure your User entity implements Serializable or has a getId() method.
    • Debug with:
      $this->logger->debug('User context', ['user' => $this->get('security.token_storage')->getToken()?->getUser()]);
      
  2. Performance Overhead:

    • Parsing user agents and fetching Git metadata adds ~5-10ms per log. Disable unused processors in config/packages/monolog.yaml:
      monolog:
          processors:
              dziki.sentry.user: false  # Disable if not needed
              dziki.sentry.git: false   # Disable if not in Git repo
      
  3. DSN Exposure:

    • Ensure SENTRY_DSN is never committed to version control. Use .env and .env.local:
      echo "SENTRY_DSN=your_dsn" >> .env.local
      git add .env.local  # Oops! Undo with `git rm --cached .env.local`
      
  4. Symfony Version Mismatch:

    • The bundle is tested for Symfony 3.x/4.x. For Symfony 5/6, manually patch UserContextProcessor if TokenStorage changes break it.

Debugging

  • Log the Raw Record: Add a stream handler temporarily to inspect processed logs:

    monolog:
        handlers:
            stream:
                type: stream
                path: "%kernel.logs_dir%/%kernel.environment%.log"
                level: debug
    

    Check for missing fields like extra.user or extra.git.

  • Disable Processors Individually: Isolate which processor is causing issues:

    monolog:
        processors:
            dziki.sentry.user: false
            dziki.sentry.git: false
            dziki.sentry.tags: false
    

Extension Points

  1. Custom Fields: Override the processor to add fields like:

    // src/Processor/CustomSentryProcessor.php
    class CustomSentryProcessor extends AbstractProcessor {
        public function __invoke(array $record): array {
            $record['extra']['locale'] = $this->requestStack->getCurrentRequest()->getLocale();
            return parent::__invoke($record);
        }
    }
    

    Register as a Monolog processor:

    services:
        App\Processor\CustomSentryProcessor:
            tags: ['monolog.processor']
            arguments:
                $requestStack: '@request_stack'
    
  2. Conditional Logging: Skip Sentry for specific logs:

    if (!$this->isProduction()) {
        $this->logger->error('Test error', [], ['skip_sentry' => true]);
    }
    

    Add a custom processor to filter:

    public function __invoke(array $record): array {
        if (isset($record['extra']['skip_sentry'])) {
            $record['level'] = Monolog\Logger::WARNING; // Downgrade to avoid Sentry
        }
        return $record;
    }
    
  3. Breadcrumbs: Manually add breadcrumbs for critical paths:

    $this->logger->info('User clicked "Submit"', [
        'level' => 'breadcrumb',
        'category' => 'ui',
        'data' => ['button' => 'submit']
    ]);
    

    Ensure your Sentry client supports breadcrumbs (most modern SDKs do).

Configuration Quirks

  • Processor Order: Processors run in the order defined in config/packages/monolog.yaml. Place dziki.sentry.* after your custom processors to override their data.

  • RequestStack Dependency: The bundle requires request_stack to be available. For CLI commands, mock the request:

    $request = Request::create('/cli');
    $this->container->get('request_stack')->push($request);
    
  • Git Metadata: If git CLI is unavailable, the bundle falls back to git describe --always --dirty. Ensure the repo is initialized and the user has permissions.

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