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

Telegram Log Channel Laravel Package

arhx/telegram-log-channel

Laravel log channel that sends Monolog messages to a Telegram chat via bot token and chat ID. Configure via .env or logging.php, add to your logging stack, and it safely falls back to a NullHandler when unset. Includes optional queued job failure alerts.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Laravel-Centric Design: Perfectly aligned with Laravel’s Monolog-based logging stack, requiring zero architectural changes. Acts as a drop-in channel without disrupting existing logging pipelines (e.g., daily, slack).
  • Event-Driven Extensibility: Leverages Laravel’s Queue::failing listener for job failure notifications, integrating seamlessly with the queue system. Ideal for asynchronous workflows where immediate feedback is critical.
  • Lightweight Footprint: No database or external service dependencies beyond Telegram’s API, making it suitable for serverless or containerized Laravel deployments (e.g., Docker, AWS Lambda).
  • Log Level Granularity: Supports Monolog’s log level hierarchy (debugemergency), enabling fine-grained control over what reaches Telegram (e.g., only error/critical logs).

Integration Feasibility

  • Zero-Bootstrap: Requires <15 minutes to integrate:
    1. Install via Composer.
    2. Add .env variables (TELEGRAM_LOG_BOT_TOKEN, TELEGRAM_LOG_CHAT_ID).
    3. Configure config/logging.php to include the telegram channel.
  • Backward Compatibility: Works with Laravel 8–12 and PHP 8.0+. No breaking changes to existing logging configurations.
  • Configuration Overrides: Supports environment-specific settings (e.g., disable in staging via .env):
    TELEGRAM_LOG_LEVEL=error # Production
    TELEGRAM_LOG_LEVEL=debug # Local
    
  • Queue Integration: Automatic job failure notifications reduce context-switching for developers debugging async tasks (e.g., failed sendEmail jobs).

Technical Risk

  • Telegram API Constraints:
    • Rate Limits: Telegram’s API enforces 30 messages/second per bot. Exceeding this risks temporary bans or dropped logs. Mitigation: Implement a Monolog processor to batch or throttle logs.
    • Message Length: Telegram messages are limited to 4096 characters. Long stack traces may truncate. Mitigation: Use Log::stack() with a custom processor to split messages.
  • Error Resilience:
    • Silent Failures: By default, API errors are swallowed (throw: false). Mitigation: Set throw: true in config to log API failures to Laravel’s default channel.
    • No Retries: Failed API calls aren’t retried. Mitigation: Wrap the handler in a queue job with exponential backoff.
  • Security:
    • Credential Exposure: .env files can be leaked. Mitigation: Use Laravel’s Vault or AWS Secrets Manager for tokens in production.
    • Data Leakage: Sensitive logs (e.g., passwords) may be sent to Telegram. Mitigation: Sanitize logs with a Monolog processor (e.g., Log::replace()).
  • Configuration Cache:
    • config:cache Pitfalls: Environment variables aren’t read after caching. Mitigation: Publish the config file (php artisan vendor:publish --tag=telegram-log-channel-config) or use Laravel’s config() helper with fallbacks.

Key Questions

  1. Log Volume and Velocity:
    • What’s the expected messages/second? For >10 logs/sec, implement rate limiting (e.g., sleep() between batches).
    • Are there spiky workloads (e.g., batch jobs) that could trigger API limits?
  2. Alert Fatigue:
    • How will the team triage Telegram notifications? Consider adding log level filters (e.g., ignore info logs).
  3. Compliance:
    • Does the use case involve regulated data (e.g., HIPAA, GDPR)? If so, avoid sending raw logs and use masking.
  4. Monitoring:
    • How will you track delivery success? Add a health check endpoint to verify Telegram API connectivity.
  5. Alternatives:
    • Could Laravel Echo + Pusher or Slack Webhooks better fit real-time alerts?
  6. Cost:
    • Are there hidden costs (e.g., Telegram Business API for high volume)?

Integration Approach

Stack Fit

  • Laravel Logging Stack:
    • Monolog Integration: Extends Laravel’s LogManager via a custom handler (TelegramHandler). No changes to core logging logic required.
    • Channel Stacking: Works with Laravel’s stack driver for multi-channel logging:
      'stack' => [
          'driver' => 'stack',
          'channels' => ['daily', 'telegram'], // Telegram as secondary channel
      ],
      
  • Queue System:
    • Job Failure Listener: Automatically triggers on Queue::failing, reducing boilerplate for error handling.
    • Queue Workers: If using database queues, ensure workers are always running to avoid missed failures.
  • Telegram API:
    • Bot Requirements: Bot must have admin rights in the target chat (group/channel).
    • API Endpoint: Uses https://api.telegram.org/bot{token}/sendMessage (no custom endpoints needed).

Migration Path

  1. Phase 1: Setup and Validation
    • Step 1: Create a Telegram bot and note the bot_token and chat_id.
    • Step 2: Install the package and configure .env:
      TELEGRAM_LOG_BOT_TOKEN=123456:ABC-DEF...
      TELEGRAM_LOG_CHAT_ID=-1001234567890
      TELEGRAM_LOG_LEVEL=error
      
    • Step 3: Test locally with php artisan telegram-log:test (sends a sample error log).
  2. Phase 2: Staging Integration
    • Step 4: Add the telegram channel to config/logging.php:
      'telegram' => [
          'driver' => 'telegram',
          'token' => env('TELEGRAM_LOG_BOT_TOKEN'),
          'chat_id' => env('TELEGRAM_LOG_CHAT_ID'),
          'level' => env('TELEGRAM_LOG_LEVEL', 'error'),
          'url' => env('TELEGRAM_API_URL', 'https://api.telegram.org'),
          'throw' => env('TELEGRAM_THROW', false),
      ],
      
    • Step 5: Update the logging stack in .env (Laravel 12+):
      LOG_STACK=daily,telegram
      
    • Step 6: Test with a non-critical log:
      Log::error('Test Telegram log', ['context' => 'integration']);
      
  3. Phase 3: Production Rollout
    • Step 7: Enable job failure notifications (default: true).
    • Step 8: Monitor for false positives (e.g., noise from debug logs).
    • Step 9: Set up alerts for Telegram API failures (e.g., throw: true + monitoring).

Compatibility

  • Laravel Versions:
    • Tested: 8–12. Untested: Laravel 7 (PHP 7.4) may require dependency updates.
    • Queue Drivers: Works with database, redis, sync queues. For beanstalkd, verify Queue::failing compatibility.
  • Monolog Processors:
    • Supports standard processors (e.g., LineFormatter, FilterProcessor) for log formatting.
    • Example: Add a processor to truncate long messages:
      $processor = new class {
          public function __invoke(array $record) {
              if (strlen($record['formatted']) > 3000) {
                  $record['formatted'] = substr($record['formatted'], 0, 3000) . ' [TRUNCATED]';
              }
              return $record;
          }
      };
      
  • Customization:
    • Override the Handler: Extend Arhx\TelegramLogChannel\Handlers\TelegramHandler to add retries or rate limiting.
    • Custom Message Formatting: Use Monolog’s FormatterInterface to modify log output.

Sequencing

  1. Prerequisites:
    • Set up a Telegram bot and obtain credentials.
    • Ensure Laravel’s logging is configured (default in new projects).
    • Verify queue workers are running (if using job failure notifications).
  2. Implementation Order:
      1. Install and configure the package.
      1. Test locally with telegram-log:test.
      1. Deploy to staging and validate logs.
      1. Enable job failure notifications.
      1. Monitor for API limits/errors in production.
  3. Rollback Plan:
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.
f1monkey/eve-esi-bundle
f-froehlich/symfony-validator
f-froehlich/api
ezsystems/templated-uri-bundle
ezsystems/stash-bundle
ezsystems/share-buttons-bundle
ezsystems/privacy-cookie-bundle
ezsystems/payment-paypal-bundle
ezsystems/payment-core-bundle
ezsystems/job-queue-bundle
ezsystems/hybrid-platform-ui
ezsystems/ezmigrationbundle
ezsystems/ezcommerce-econtent-installer
ezsystems/comment-bundle
ezsystems/apache-tika-bundle
ezar101/easyadmin-trix-extension-bundle
eyerim/oauth2-azure-bundle
exu/bundle-skeleton
extrablind/monithomebundle
extendy/jormall-sms-bundle