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

  • Monolithic vs. Microservices: Fits seamlessly into a monolithic Laravel architecture where centralized logging is preferred. Less ideal for microservices unless logs are aggregated externally (e.g., via ELK or Loki).
  • Logging Strategy: Aligns with Laravel’s built-in logging stack (Monolog), acting as a custom channel for Telegram notifications. Complements existing channels (e.g., single, daily, slack) without disrupting core logging workflows.
  • Real-Time vs. Batch: Designed for real-time alerts (e.g., errors, critical logs) rather than batch processing. Not suitable for high-volume log ingestion (e.g., debug logs for all requests).

Integration Feasibility

  • Laravel Compatibility: Works with Laravel 8+ (PHP 8.0+). Minimal setup required—just configure the channel in config/logging.php and provide a Telegram bot token/channel ID.
  • Dependency Overhead: Lightweight (no heavy DB or external service dependencies). Only requires guzzlehttp/guzzle (already bundled with Laravel) for HTTP calls to Telegram’s API.
  • Customization: Supports log level filtering (e.g., only ERROR/CRITICAL logs) and message formatting via Monolog processors. Can extend via service providers or custom processors.

Technical Risk

  • Telegram API Limits:
    • Risk of rate limits if spammy logs flood the channel (Telegram’s API has strict limits).
    • No built-in throttling in the package; requires custom logic (e.g., Monolog processor to debounce messages).
  • Security:
    • Bot token exposure: Hardcoding TELEGRAM_BOT_TOKEN in .env is secure, but misconfiguration (e.g., committing .env) could leak credentials.
    • No encryption: Logs sent to Telegram are unencrypted in transit (use HTTPS, but sensitive data should still be masked).
  • Error Handling:
    • Silent failures: If Telegram’s API is down, logs are dropped unless throw is set to true in config (default: false).
    • Retry logic: No built-in retries for failed API calls (would need custom middleware or queue job).

Key Questions

  1. Use Case Clarity:
    • Is this for alerting only (e.g., errors) or full log replication? If the latter, consider volume and cost (Telegram API isn’t free for high traffic).
    • Are there SLA requirements for log delivery (e.g., must logs reach Telegram within 5 seconds)?
  2. Scalability:
    • What’s the expected log volume? For >100 logs/minute, evaluate Telegram’s API limits or consider a queue (e.g., Laravel Queues + telegram-notify job).
  3. Compliance:
    • Does the use case involve PII/PHI? If so, ensure logs are sanitized before sending (e.g., via Monolog processors).
  4. Alternatives:
    • Why Telegram? Could other channels (e.g., Slack, PagerDuty, custom webhooks) better fit operational needs?
  5. Maintenance:
    • Who will monitor the Telegram channel for false positives/negatives (e.g., noise from non-critical logs)?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Native Integration: Designed for Laravel’s Monolog stack. No need for external libraries beyond guzzlehttp/guzzle (already included).
    • Service Provider: Registers as a logging channel via Laravel’s extend() method in LogServiceProvider.
    • Configuration: Minimal setup in config/logging.php:
      'telegram' => [
          'driver' => 'telegram',
          'bot_token' => env('TELEGRAM_BOT_TOKEN'),
          'chat_id' => env('TELEGRAM_CHAT_ID'),
          'level' => env('TELEGRAM_LOG_LEVEL', 'error'),
          'url' => env('TELEGRAM_API_URL', 'https://api.telegram.org'),
          'throw' => env('TELEGRAM_THROW', false),
      ],
      
  • PHP Version: Requires PHP 8.0+. Test compatibility if using older versions (e.g., 7.4).
  • Telegram Bot Setup:
    • Requires a bot token (from @BotFather) and a chat ID (group/channel ID where logs should post).
    • Bot must be an admin in the target chat to post messages.

Migration Path

  1. Pilot Phase:
    • Start with non-critical logs (e.g., debug level) to test formatting and volume.
    • Use throw: false initially to avoid disrupting production.
  2. Gradual Rollout:
    • Phase 1: Add to config/logging.php and test locally.
    • Phase 2: Deploy to staging with TELEGRAM_LOG_LEVEL=error.
    • Phase 3: Monitor for false positives (e.g., stack traces overwhelming the channel).
  3. Fallback Plan:
    • If Telegram fails, ensure logs still route to a secondary channel (e.g., single file or syslog).

Compatibility

  • Laravel Versions: Officially supports 8+. Test with 9/10 for compatibility (e.g., dependency conflicts).
  • Monolog Processors: Supports standard Monolog processors (e.g., StreamHandler, FilterHandler) for log formatting.
  • Customization:
    • Extend via custom processors to modify log messages before sending.
    • Override the TelegramHandler class to add retries or rate limiting.

Sequencing

  1. Prerequisites:
    • Set up a Telegram bot and obtain bot_token and chat_id.
    • Ensure Laravel’s logging is configured to use Monolog (default in Laravel).
  2. Implementation Steps:
    • Install the package: composer require arhx/telegram-log-channel.
    • Publish config (if needed): php artisan vendor:publish --provider="Arhx\TelegramLogChannel\TelegramLogChannelServiceProvider".
    • Configure config/logging.php and .env.
    • Test with Log::error('Test message') in a Tinker session.
  3. Validation:
    • Verify logs appear in Telegram within expected time (account for API latency).
    • Check for malformed messages (e.g., truncated stack traces).

Operational Impact

Maintenance

  • Configuration Drift:
    • Risk of bot_token/chat_id being misconfigured in environments (use Laravel’s .env validation).
    • Mitigation: Add validation to AppServiceProvider:
      Validator::extend('valid_telegram_token', function ($attribute, $value, $parameters) {
          return strlen($value) === 10 && ctype_alnum($value);
      });
      
  • Log Rotation:
    • No built-in log rotation for Telegram (unlike file channels). Monitor chat history for clutter.
    • Workaround: Use Telegram’s export chat history feature periodically.
  • Dependency Updates:
    • Package is lightweight, but guzzlehttp/guzzle may require updates. Monitor for breaking changes.

Support

  • Debugging:
    • No built-in metrics: Hard to track delivery success/failure without custom logging (e.g., log HTTP response codes).
    • Workaround: Add a Monolog processor to log Telegram API responses:
      $processor = new class {
          public function __invoke(array $record) {
              if (isset($record['context']['telegram_response'])) {
                  Log::debug('Telegram API response', $record['context']['telegram_response']);
              }
              return $record;
          }
      };
      
  • Escalation Path:
    • Telegram API issues (e.g., downtime) require manual intervention. No SLA guarantees from the package.
    • Recommendation: Pair with another channel (e.g., email) for critical alerts.

Scaling

  • Volume Limits:
    • Telegram’s API allows 30–300 requests/second (depending on bot age). For high-traffic apps:
      • Rate Limiting: Implement a Monolog processor to throttle logs (e.g., 1 message/second).
      • Queue Jobs: Offload to Laravel Queues to avoid blocking HTTP requests:
        // Custom queue handler
        TelegramLogChannel::dispatch($level, $message, $context);
        
  • Performance Impact:
    • Each log triggers an HTTP call to Telegram. For high-frequency logs, this could impact response times.
    • Mitigation: Use async: true in config (if supported) or queue jobs.

Failure Modes

| Failure Scenario | Impact | Mitigation | |--------------------------------|-------------------------------------|

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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge