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 Sms Laravel Package

tylercd100/monolog-sms

Laravel/Lumen package that adds an SMS handler to Monolog, letting you send log alerts and critical errors via text message using popular SMS gateways. Useful for on-call notifications when something breaks in production.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require tylercd100/monolog-sms
    
  2. Basic Configuration Add the SMS handler to your Monolog configuration in config/logging.php:

    'channels' => [
        'sms' => [
            'driver' => 'sms',
            'provider' => env('SMS_PROVIDER', 'twilio'),
            'from' => env('SMS_FROM', '+1234567890'),
            'to' => env('SMS_TO', '+1987654321'),
            'options' => [
                'account_sid' => env('TWILIO_SID'),
                'auth_token' => env('TWILIO_TOKEN'),
            ],
        ],
    ],
    
  3. First Use Case Log an SMS alert via the logger facade:

    Log::channel('sms')->alert('Database connection failed!');
    

Where to Look First


Implementation Patterns

Common Workflows

  1. Conditional SMS Alerts Use Monolog’s levels to control when SMS alerts fire:

    if ($criticalError) {
        Log::channel('sms')->emergency('Critical failure detected!');
    }
    
  2. Dynamic Recipients Override the to field dynamically in runtime:

    $handler = new \TylerCD100\MonologSms\Handler\SmsHandler(
        new \Monolog\Logger('sms'),
        '+1' . $user->phone_number,
        $provider
    );
    $logger->pushHandler($handler);
    
  3. Structured Logging Attach context to SMS messages for debugging:

    Log::channel('sms')->error('Payment failed', [
        'user_id' => $user->id,
        'amount' => $amount,
        'transaction_id' => $txnId,
    ]);
    

Integration Tips

  • Queue SMS for Async Delivery Pair with Laravel Queues to avoid blocking requests:

    Log::channel('sms')->debug('Queued SMS alert'); // Log to file first
    dispatch(new SendSmsJob($message, $recipient));
    
  • Rate Limiting Use Monolog’s Filter to throttle SMS alerts:

    $filter = new \Monolog\Filter\CallbackFilter(function ($record) {
        return !Cache::has('sms_alert_throttle');
    });
    $handler->pushFilter($filter);
    
  • Fallback Channels Combine with other channels (e.g., Slack) for redundancy:

    Log::channels(['sms', 'slack'])->error('High severity alert!');
    

Gotchas and Tips

Pitfalls

  1. Provider-Specific Quirks

    • Twilio: Requires from number to be verified. Unverified numbers may fail silently.
    • Generic Providers: Some may truncate messages over 1600 characters (SMS concatenation may be needed).
    • Rate Limits: Twilio defaults to 1 SMS/sec for trial accounts. Exceeding limits may cause delays or failures.
  2. Message Formatting

    • Monolog’s default formatter may not handle SMS constraints (e.g., no HTML, limited special chars).
    • Fix: Use a custom formatter:
      $handler->setFormatter(new \Monolog\Formatter\LineFormatter(
          "%message%\n[Context: %context%]",
          ['date' => 'Y-m-d H:i:s']
      ));
      
  3. Error Handling

    • Failed SMS sends may not throw exceptions by default. Wrap usage in try-catch:
      try {
          Log::channel('sms')->alert('Error!');
      } catch (\Exception $e) {
          Log::channel('single')->error('SMS failed: ' . $e->getMessage());
      }
      
  4. Environment-Specific Config

    • Avoid hardcoding to numbers. Use feature flags or environment variables:
      'to' => env('SMS_TO', config('services.sms.default_recipient')),
      

Debugging Tips

  • Log Provider Responses Enable debug mode for the SMS provider (e.g., Twilio’s debug logs) to inspect API responses.

    $provider->setDebug(true); // If supported by your provider wrapper.
    
  • Test with a Fake Handler Replace the SMS handler with a StreamHandler during development:

    $handler = new \Monolog\Handler\StreamHandler(storage_path('logs/sms_test.log'));
    $logger->pushHandler($handler);
    
  • Check for Silent Failures Monitor your SMS provider’s dashboard for undelivered messages or errors.

Extension Points

  1. Custom Providers Extend the base handler to support new providers:

    class CustomSmsHandler extends \TylerCD100\MonologSms\Handler\SmsHandler {
        protected function sendSms($message, $to) {
            // Implement custom logic (e.g., HTTP client calls)
        }
    }
    
  2. Message Templates Use Laravel’s Blade or a templating library to pre-process messages:

    $message = view('logs.sms_template', ['error' => $record->message])->render();
    
  3. Webhook Fallback Combine with a webhook handler to retry failed SMS via email or push notifications:

    Log::channel('webhook')->pushHandler(
        new \Monolog\Handler\PushHandler([
            new \Monolog\Handler\SmsHandler(...),
            new \Monolog\Handler\HttpHandler(env('WEBHOOK_URL')),
        ])
    );
    
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope