Weave 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

Sam Monitoring Bundle Laravel Package

canaltp/sam-monitoring-bundle

Laravel bundle for monitoring and diagnostics, providing health/status checks and runtime insights to help detect issues early. Includes endpoints and tooling to track application availability and performance in production environments.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require canal/sam-monitoring-bundle
    

    Enable it in config/bundles.php (Symfony) or register the service provider in config/app.php (Laravel 5.x):

    Canal\SamMonitoringBundle\SamMonitoringBundle::class => ['all' => true],
    
  2. Configuration Publish the default config:

    php artisan vendor:publish --provider="Canal\SamMonitoringBundle\SamMonitoringBundle" --tag="config"
    

    Update config/sam_monitoring.php with your SAM (Simple Application Monitoring) API credentials and project settings.

  3. First Use Case: Tracking Events Inject the SamMonitoringClient service and log an event:

    use Canal\SamMonitoringBundle\Client\SamMonitoringClient;
    
    class MyController extends Controller
    {
        public function __construct(private SamMonitoringClient $samMonitoring)
        {
        }
    
        public function trackUserAction()
        {
            $this->samMonitoring->trackEvent('user_action', [
                'user_id' => auth()->id(),
                'action' => 'profile_update',
                'metadata' => ['ip' => request()->ip()]
            ]);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Event Tracking

    • Use trackEvent() for user interactions (e.g., clicks, form submissions).
    • Pass contextual data (e.g., user_id, timestamp) as an associative array.
    • Example:
      $this->samMonitoring->trackEvent('checkout_started', [
          'cart_value' => $cartTotal,
          'items' => count($cartItems)
      ]);
      
  2. Performance Monitoring

    • Wrap critical sections with measurePerformance() to log execution time:
      $this->samMonitoring->measurePerformance('api_request', function () {
          return Http::get('https://api.example.com/data');
      });
      
  3. Error Tracking

    • Automatically capture exceptions via the SamMonitoringListener (configured in config/sam_monitoring.php):
      'listeners' => [
          'exceptions' => true,
          'errors' => true,
      ],
      
    • Manually log errors:
      $this->samMonitoring->trackError(new \RuntimeException('Failed to process payment'), [
          'user_id' => auth()->id(),
          'amount' => $paymentAmount
      ]);
      
  4. User Sessions

    • Track session start/end or custom session events:
      $this->samMonitoring->trackSession('user_login', ['device' => 'mobile']);
      

Integration Tips

  • Middleware for Automatic Tracking Create middleware to log requests automatically:

    class MonitorRequests
    {
        public function handle($request, Closure $next)
        {
            $this->samMonitoring->trackEvent('http_request', [
                'path' => $request->path(),
                'method' => $request->method(),
                'ip' => $request->ip()
            ]);
            return $next($request);
        }
    }
    

    Register it in app/Http/Kernel.php:

    protected $middleware = [
        \App\Http\Middleware\MonitorRequests::class,
    ];
    
  • Queue Delayed Events Offload tracking to a queue to avoid blocking requests:

    $this->samMonitoring->queueEvent('user_signup', $userData);
    
  • Custom Dimensions Define reusable dimensions in config:

    'dimensions' => [
        'user_type' => fn() => auth()->user()->role,
        'environment' => fn() => app()->environment(),
    ],
    

    Reference them in events:

    $this->samMonitoring->trackEvent('page_view', [
        'dimensions' => ['user_type', 'environment']
    ]);
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting

    • SAM APIs may throttle requests. Use queueEvent() for high-frequency events (e.g., clicks).
    • Monitor Laravel queue workers (php artisan queue:work) to avoid backlogs.
  2. Sensitive Data Leaks

    • Avoid logging PII (e.g., passwords, credit cards) or sensitive tokens. Use hashed/anonymized values:
      'metadata' => ['user_email_hash' => sha1($user->email)]
      
  3. Configuration Overrides

    • Bundle config is merged with defaults. Override specific keys in config/sam_monitoring.php:
      'api_url' => env('SAM_API_URL_OVERRIDE', 'https://api.sam.example.com'),
      
  4. Listener Conflicts

    • If using Symfony’s event system, ensure the bundle’s listeners don’t conflict with existing ones. Disable via:
      'listeners' => [
          'exceptions' => false, // Disable auto-capture
      ],
      

Debugging

  • Log Levels Enable debug logs in config/sam_monitoring.php:

    'debug' => env('APP_DEBUG', false),
    

    Check Laravel logs (storage/logs/laravel.log) for failed requests.

  • Payload Validation Validate payload structure before sending:

    $this->samMonitoring->validateEvent([
        'event' => 'invalid_event_name', // Will trigger a warning
        'metadata' => ['invalid_key' => null]
    ]);
    
  • API Response Handling Handle HTTP errors gracefully:

    try {
        $this->samMonitoring->trackEvent('test_event', []);
    } catch (\Canal\SamMonitoringBundle\Exception\ApiException $e) {
        Log::error('SAM API failed', ['error' => $e->getMessage()]);
    }
    

Extension Points

  1. Custom Event Transformers Extend Canal\SamMonitoringBundle\Transformer\EventTransformer to modify payloads:

    class CustomEventTransformer extends EventTransformer
    {
        public function transform(array $event): array
        {
            $event['custom_field'] = 'value';
            return parent::transform($event);
        }
    }
    

    Bind it in config/sam_monitoring.php:

    'transformer' => \App\Transformers\CustomEventTransformer::class,
    
  2. Webhook Listeners Subscribe to SAM webhooks (if supported) to react to real-time events:

    Route::post('/sam-webhook', [SamWebhookController::class, 'handle']);
    
  3. Batch Processing For large datasets, implement batch processing:

    $this->samMonitoring->batchTrack([
        ['event' => 'view', 'metadata' => ['page' => 'home']],
        ['event' => 'view', 'metadata' => ['page' => 'about']],
    ], 100); // Batch size
    
  4. Testing Mock the SamMonitoringClient in tests:

    $mock = Mockery::mock(SamMonitoringClient::class);
    $mock->shouldReceive('trackEvent')->once();
    $this->app->instance(SamMonitoringClient::class, $mock);
    
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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style