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

Multichannel Log Notification Laravel Package

bzilee/multichannel-log-notification

Laravel package to send log notifications over multiple channels (Telegram, email, SMS, HTTP). Configure per log level, enable via env, plug into Monolog as a custom channel, and dispatch notifications to a dedicated queue for performance.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bzilee/multichannel-log-notification
    

    Publish the config file:

    php artisan vendor:publish --provider="Bzilee\MultichannelLogNotification\MultichannelLogNotificationServiceProvider" --tag="config"
    
  2. Configure Channels Edit config/multichannel-log-notification.php to define your channels (e.g., Telegram, HTTP, SMS, Email) with their respective credentials and endpoints.

  3. First Use Case Log a notification via a channel:

    use Bzilee\MultichannelLogNotification\Facades\MultichannelLogNotification;
    
    MultichannelLogNotification::send('telegram', 'Error in API', ['user_id' => 123]);
    

Key Files to Review

  • config/multichannel-log-notification.php – Channel configurations.
  • app/Providers/AppServiceProvider.php – Register any custom channels (if needed).
  • routes/web.php – If using HTTP channel, ensure the endpoint is exposed.

Implementation Patterns

Core Workflow

  1. Channel Registration Extend the package by registering custom channels in AppServiceProvider:

    public function boot()
    {
        MultichannelLogNotification::extend('slack', function ($app) {
            return new \Bzilee\MultichannelLogNotification\Channels\SlackChannel();
        });
    }
    
  2. Sending Notifications

    • Basic Usage:
      MultichannelLogNotification::send('telegram', 'Deployment failed', ['commit' => 'abc123']);
      
    • Multi-Channel Dispatch:
      MultichannelLogNotification::sendToChannels(['telegram', 'email'], 'Critical error', ['trace' => $exception->getTraceAsString()]);
      
  3. Logging Context Attach metadata (e.g., user IDs, timestamps) for debugging:

    MultichannelLogNotification::send('http', 'Payment processed', [
        'user_id' => auth()->id(),
        'amount' => $order->amount,
        'timestamp' => now()->toIso8601String(),
    ]);
    
  4. Integration with Laravel Logging Hook into Laravel’s log system to auto-send notifications:

    use Illuminate\Support\Facades\Log;
    
    Log::channel('multichannel')->error('Database connection failed', ['context' => 'production']);
    

    Configure the multichannel log channel in config/logging.php:

    'channels' => [
        'multichannel' => [
            'driver' => 'custom',
            'via' => \Bzilee\MultichannelLogNotification\Logging\MultichannelHandler::class,
        ],
    ],
    

Best Practices

  • Channel-Specific Payloads: Customize payloads per channel (e.g., Telegram uses Markdown, HTTP expects JSON).
  • Rate Limiting: Implement middleware to throttle notifications (e.g., throttle:60,1 for HTTP channel).
  • Environment-Specific Configs: Use .env variables for sensitive data (e.g., TELEGRAM_BOT_TOKEN).

Gotchas and Tips

Common Pitfalls

  1. Channel Misconfiguration

    • Issue: Notifications fail silently due to invalid API keys or endpoints.
    • Fix: Enable debug mode in config ('debug' => true) and check Laravel logs (storage/logs/laravel.log).
    • Tip: Validate channel configs during deployment:
      if (!MultichannelLogNotification::isChannelConfigured('telegram')) {
          throw new \RuntimeException('Telegram channel not configured!');
      }
      
  2. Payload Formatting

    • Issue: Some channels (e.g., Telegram) require specific formatting (e.g., Markdown, HTML).
    • Fix: Use channel-specific payload builders:
      MultichannelLogNotification::send('telegram', 'Alert', ['message' => '```' . $error . '```']);
      
  3. HTTP Channel CORS

    • Issue: HTTP notifications may fail if the endpoint doesn’t accept requests from your Laravel app.
    • Fix: Configure CORS on the receiving endpoint or use Laravel’s VerifyCsrfToken middleware if needed.
  4. SMS Gateway Delays

    • Issue: SMS providers may throttle or delay messages.
    • Fix: Implement retry logic with exponential backoff:
      MultichannelLogNotification::send('sms', 'OTP: 12345', [], ['retries' => 3]);
      

Debugging Tips

  • Log All Sent Notifications: Enable the log_sent config option to track all dispatched notifications:
    'telegram' => [
        'token' => env('TELEGRAM_BOT_TOKEN'),
        'log_sent' => true, // Logs to storage/logs/multichannel.log
    ],
    
  • Mock Channels for Testing: Create a null channel for unit tests:
    MultichannelLogNotification::extend('null', function () {
        return new class {
            public function send($message, $context) {}
        };
    });
    

Extension Points

  1. Custom Channel Development Extend the base Channel class:

    namespace App\Channels;
    
    use Bzilee\MultichannelLogNotification\Contracts\Channel;
    
    class CustomChannel implements Channel {
        public function send($message, $context) {
            // Implement logic (e.g., Webhook to Datadog)
        }
    }
    

    Register it in AppServiceProvider.

  2. Middleware for Pre/Post-Processing Add middleware to modify messages or contexts:

    MultichannelLogNotification::extend('telegram', function () {
        return tap(new \Bzilee\MultichannelLogNotification\Channels\TelegramChannel(), function ($channel) {
            $channel->pushMiddleware(new class {
                public function handle($message, $context, callable $next) {
                    $context['processed_at'] = now();
                    return $next($message, $context);
                }
            });
        });
    });
    
  3. Dynamic Channel Selection Use environment variables or user input to switch channels:

    $channel = config('multichannel-log-notification.default') ?? 'telegram';
    MultichannelLogNotification::send($channel, 'Dynamic alert');
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky