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

Monitor Bundle Laravel Package

a5sys/monitor-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Run:

    composer require a5sys/monitor-bundle
    
  2. Enable Bundles Add to app/AppKernel.php:

    new A5sys\MonitorBundle\MonitorBundle(),
    new JMS\TranslationBundle\JMSTranslationBundle(), // Required dependency
    
  3. Configure Monolog In app/config/config.yml:

    monolog:
        channels: ['monitor']
        handlers:
            monitor:
                type: rotating_file
                max_files: 60
                path: "%kernel.logs_dir%/monitor.log"
                channels: ['monitor']
                formatter: monitor.monolog.formatter
    

    Exclude monitor from your main log to avoid spam:

    monolog:
        handlers:
            main:
                type: rotating_file
                channels: [!'monitor']
    
  4. Route Access Add to app/config/routing.yml:

    monitor_controller:
        resource: "@MonitorBundle/Controller/"
        type: annotation
        prefix: /monitor
    
  5. First Use Case Access /monitor in your browser (ensure security is configured). The dashboard will show:

    • Unfinished requests (timeouts/errors).
    • Slow requests (thresholds configurable via bundle settings).
    • Performance killers (e.g., long-running queries or external API calls).

Implementation Patterns

Core Workflow

  1. Data Collection The bundle hooks into Symfony’s event system (e.g., kernel.request, kernel.response) to log:

    • Request duration.
    • Response status codes (e.g., 500, 200).
    • Memory usage spikes.
    • Exceptions (if uncaught).
  2. Threshold Configuration Customize performance thresholds in config.yml:

    monitor:
        slow_request_threshold: 500  # ms (default)
        error_threshold: 100          # requests before alerting
    
  3. Integration with Existing Logs

    • Correlation IDs: Use Request::get('X-Request-ID') to trace logs across services.
    • Structured Logging: Extend the monitor.monolog.formatter to include custom metadata (e.g., user IDs, request payloads).
  4. Scheduled Reports Use Symfony’s CronBundle or a queue worker (e.g., Symfony Messenger) to:

    • Parse monitor.log daily.
    • Generate reports (e.g., Slack alerts for 5xx spikes).
    • Archive logs via Logrotate.
  5. Dashboard Customization Override the default controller (MonitorBundle:Controller\MonitorController) to:

    • Add filters (e.g., by route, user role).
    • Integrate with Grafana for visualization.
    • Example:
      // src/Acme/MonitorBundle/Controller/MonitorController.php
      class MonitorController extends \A5sys\MonitorBundle\Controller\MonitorController
      {
          public function indexAction()
          {
              $data = parent::indexAction();
              $data['custom_metric'] = $this->getCustomMetric();
              return $this->render('AcmeMonitorBundle:monitor:index.html.twig', $data);
          }
      }
      
  6. API Access Expose metrics via a custom endpoint:

    # app/config/routing.yml
    monitor_api:
        path: /api/monitor/metrics
        defaults: { _controller: AcmeMonitorBundle:MonitorApi:metrics }
    

Gotchas and Tips

Pitfalls

  1. Log Bloat

    • Issue: Rotating logs (max_files: 60) may fill disk space if not monitored.
    • Fix: Set up log rotation via logrotate or increase max_files temporarily during debugging.
  2. Performance Overhead

    • Issue: Logging every request adds ~1–5ms overhead. Disable in production for non-critical routes:
      monitor:
          enabled_environments: [dev, staging]
      
    • Fix: Use environment checks in the bundle’s event listeners.
  3. Security Risks

    • Issue: The /monitor route exposes sensitive data (e.g., slow queries, error stacks).
    • Fix: Restrict access in security.yml:
      access_control:
          - { path: ^/monitor, roles: [ROLE_ADMIN] }
      
  4. Formatter Conflicts

    • Issue: The monitor.monolog.formatter may conflict with other bundles using the same channel.
    • Fix: Define a custom formatter in services.yml:
      services:
          monitor.monolog.formatter:
              class: Monolog\Formatter\LineFormatter
              arguments: ["[%datetime%] %channel% %level% %message% %context%\n"]
      
  5. Outdated Dependencies

    • Issue: The bundle relies on JMS/TranslationBundle (last updated 2017) and Symfony 2.x.
    • Fix: Fork the bundle and update dependencies if using Symfony 3.4+/4.x.

Debugging Tips

  1. Verify Log Output Check var/logs/monitor.log for raw data:

    tail -f var/logs/monitor.log | grep "slow_request"
    
  2. Test Event Listeners Trigger a slow request manually:

    // In a controller
    sleep(1); // Simulate slow request
    return new Response('Test');
    

    Verify it appears in the dashboard.

  3. Custom Metrics Extend the bundle’s logger service to add context:

    // src/Acme/MonitorBundle/DependencyInjection/CompilerPass.php
    public function process(ContainerBuilder $container)
    {
        $definition = $container->findDefinition('monitor.logger');
        $definition->addMethodCall('addContext', ['custom_key', 'custom_value']);
    }
    
  4. Database Queries To log slow queries, patch the bundle’s QueryListener:

    // Override A5sys\MonitorBundle\EventListener\QueryListener
    public function onQuery(QueryEvent $event)
    {
        if ($event->getStartTime() > 500) { // 500ms threshold
            $this->logger->warning('Slow query', ['query' => $event->getSql()]);
        }
    }
    

Extension Points

  1. Add Custom Metrics Inject metrics via the monitor.event service:

    // In a controller/service
    $this->get('monitor.event')->addMetric('custom_metric', ['value' => 123]);
    
  2. Alerting System Hook into the monitor.log handler to send alerts:

    # app/config/config.yml
    monolog:
        handlers:
            monitor_alert:
                type:         fingers_crossed
                action_level: error
                handler:      nested
                excluded_404s: ~
                channels:     ['monitor']
                buffer_size:  0
                handlers:
                    slack:
                        type:        stream
                        path:        "php://temp"
                        formatter:  monolog.formatter.slack
                        streams:     ["https://hooks.slack.com/..."]
    
  3. Export Data Use the MonitorBundle\Service\MonitorService to fetch raw data:

    $monitorService = $this->get('monitor.service');
    $slowRequests = $monitorService->getSlowRequests(300); // Threshold in ms
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle