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

Getting Started

Minimal Setup

  1. Install the package:

    composer require arhx/telegram-log-channel
    

    The service provider auto-registers.

  2. Configure .env:

    TELEGRAM_LOG_BOT_TOKEN=your_bot_token_here
    TELEGRAM_LOG_CHAT_ID=your_chat_id_here
    TELEGRAM_LOG_LEVEL=error  # Optional: defaults to 'debug'
    
  3. Enable the channel:

    • For Laravel 12, add to .env:
      LOG_STACK=daily,telegram
      
    • For older versions, modify config/logging.php:
      'stack' => [
          'driver' => 'stack',
          'channels' => ['daily', 'telegram'],
      ],
      
  4. Test immediately:

    php artisan telegram-log:test
    

    Verify a test message appears in your Telegram chat.


Implementation Patterns

Core Workflows

1. Logging to Telegram

  • Standard Usage:

    Log::error('User not found', ['user_id' => 123]);
    

    If TELEGRAM_LOG_LEVEL is error or lower, the message sends to Telegram.

  • Conditional Logging: Use Monolog’s if logic to filter messages:

    if (app()->environment('production')) {
        Log::channel('telegram')->info('Production event');
    }
    

2. Queue Job Failures

  • Auto-Enabled: Listens to Queue::failing by default.
  • Disable:
    TELEGRAM_LOG_QUEUE_FAILURES=false
    
  • Customize Payload: Extend the QueueFailureListener in app/Providers/EventServiceProvider:
    public function boot()
    {
        Queue::failing(function ($connection, $job, $exception) {
            Log::channel('telegram')->error(
                "Job [{$job->resolveName()}] failed on {$connection} queue",
                ['exception' => $exception->getMessage()]
            );
        });
    }
    

3. Log Formatting

  • Customize Messages: Use Monolog processors in config/logging.php:
    'telegram' => [
        'driver' => 'telegram',
        'processors' => [
            function ($record) {
                $record['formatted'] = "[$record['level_name']] {$record['message']}";
                return $record;
            },
        ],
    ],
    

4. Environment-Specific Config

  • Development:
    TELEGRAM_LOG_LEVEL=debug
    
  • Production:
    TELEGRAM_LOG_LEVEL=error
    TELEGRAM_THROW=true  # Fail loudly if Telegram API fails
    

Integration Tips

With Laravel Queues

  • Rate Limiting: Telegram’s API has rate limits. For high-volume jobs:
    // In a custom QueueFailureListener
    $telegramClient = new TelegramClient($token, $chatId);
    try {
        $telegramClient->send($message);
    } catch (RateLimitException $e) {
        // Retry logic or log to another channel
    }
    

With Monolog Stacks

  • Prioritize Channels:
    'stack' => [
        'driver' => 'stack',
        'channels' => ['telegram', 'daily'], // Telegram first for alerts
    ],
    

With Custom Log Levels

  • Extend Monolog’s levels in app/Providers/AppServiceProvider:
    use Monolog\Logger;
    
    public function boot()
    {
        Logger::addLevel('custom', Logger::WARNING);
    }
    

With Config Caching

  • Publish the config for production:
    php artisan vendor:publish --tag=telegram-log-channel-config
    
    Then update config/telegram-log-channel.php:
    return [
        'queue_failures' => env('TELEGRAM_LOG_QUEUE_FAILURES', true),
    ];
    

Gotchas and Tips

Pitfalls

  1. Recursive Logging:

    • The package protects against infinite loops when Telegram API calls fail, but ensure your custom processors don’t trigger recursion:
    // Avoid this in processors:
    Log::channel('telegram')->info('Processed'); // ❌ Recursion risk
    
  2. Telegram API Limits:

    • Rate Limits: Telegram blocks bots after ~30 messages/second. For high-volume logs:
      • Throttle messages using a queue (e.g., telegram-notify job).
      • Example:
        Queue::later(now()->addSeconds(10), fn() => $telegramClient->send($message));
        
  3. Config Cache Issues:

    • If using php artisan config:cache, publish the config first:
      php artisan vendor:publish --tag=telegram-log-channel-config
      
    • Otherwise, TELEGRAM_LOG_QUEUE_FAILURES may not load correctly.
  4. Log Level Mismatches:

    • Queue failures are logged at error level. If TELEGRAM_LOG_LEVEL is higher (e.g., critical), failures won’t trigger.
    • Fix: Set TELEGRAM_LOG_LEVEL=error or lower.
  5. Bot Permissions:

    • The bot must be an admin in the target chat/group to post messages. Test with:
      php artisan telegram-log:test
      
  6. Sensitive Data Exposure:

    • Logs sent to Telegram are not encrypted. Avoid sending:
      • Passwords, tokens, or PII.
      • Stack traces with sensitive data (use except in log arrays):
        Log::error('Failed', ['user_id' => 123, 'except' => ['password']]);
        

Debugging

  1. Test Locally:

    • Use TELEGRAM_LOG_LEVEL=debug to verify all logs are sent.
    • Check the bot’s API URL for errors:
      curl "https://api.telegram.org/bot<TOKEN>/getUpdates"
      
  2. Enable Debug Mode:

    • Temporarily set TELEGRAM_THROW=true in .env to see API errors:
      TELEGRAM_THROW=true
      
  3. Inspect Monolog:

    • Add a single file channel to debug:
      'telegram' => [
          'driver' => 'telegram',
          'handler' => 'single', // Fallback to file if Telegram fails
      ],
      
  4. Check Queue Listeners:

    • Verify the Queue::failing listener is registered:
      php artisan queue:listen
      
    • Test with a failing job:
      Queue::fake();
      Bus::dispatch(new FailingJob());
      Queue::assertPushed(FailingJob::class);
      

Extension Points

  1. Custom Message Formatting:

    • Override the TelegramHandler in app/Handlers/TelegramHandler.php:
      namespace App\Handlers;
      
      use Arhx\TelegramLogChannel\TelegramHandler as BaseHandler;
      
      class TelegramHandler extends BaseHandler
      {
          protected function formatMessage($record)
          {
              return "[{$record['level_name']}] {$record['message']}\n```json
              {$record['context']}
              ```";
          }
      }
      
    • Register it in config/logging.php:
      'telegram' => [
          'driver' => 'custom-telegram',
          'handler' => App\Handlers\TelegramHandler::class,
      ],
      
  2. Add Retry Logic:

    • Extend the TelegramClient to retry failed API calls:
      use Arhx\TelegramLogChannel\TelegramClient as BaseClient;
      
      class TelegramClient extends BaseClient
      {
          public function send($message, $maxRetries = 3)
          {
              $retries = 0;
              while ($retries < $maxRetries) {
                  try {
                      return parent::send($message);
                  } catch (RateLimitException $e) {
                      sleep(2 ** $retries); // Exponential backoff
                      $retries++;
                  }
              }
              throw new \RuntimeException('Failed to send message after retries');
          }
      }
      
  3. Dynamic Chat IDs:

    • Route logs to different chats based on log level:
      'telegram' => [
          'driver' => 'telegram',
          'chat_id_resolver' => function ($record) {
              return $record['level'] === Logger::ERROR
                  ? env('TELEGRAM_ERROR_CHAT_ID')
                  : env('TELEGRAM_DEBUG_CHAT_ID');
          },
      ],
      
  4. Webhook Fallback:

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.
nexmo/api-specification
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes