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
    
  2. Publish Configuration

    php artisan vendor:publish --provider="Arhx\TelegramLogChannel\TelegramLogChannelServiceProvider"
    

    Edit .env with your Telegram bot token and chat ID:

    TELEGRAM_BOT_TOKEN=your_bot_token_here
    TELEGRAM_CHAT_ID=your_chat_id_here
    
  3. Configure config/logging.php Add the channel under channels:

    'telegram' => [
        'driver' => 'telegram',
        'bot_token' => env('TELEGRAM_BOT_TOKEN'),
        'chat_id' => env('TELEGRAM_CHAT_ID'),
        'level' => env('TELEGRAM_LOG_LEVEL', 'debug'),
        'formatted' => env('TELEGRAM_LOG_FORMATTED', true),
    ],
    
  4. Register the Channel Add 'telegram' to your stack in logging.php:

    'stack' => env('LOG_STACK', 'single'),
    'channels' => [
        'telegram' => [...],
    ],
    
  5. Test It Log a test message:

    \Log::channel('telegram')->info('Test message from Laravel!');
    

Implementation Patterns

Basic Logging Workflow

  • Log Levels: Use standard Laravel log levels (debug, info, warning, error, critical).
    \Log::channel('telegram')->error('Database connection failed!');
    
  • Contextual Data: Pass arrays for structured logging:
    \Log::channel('telegram')->debug('User login attempt', [
        'user_id' => 123,
        'ip' => request()->ip(),
    ]);
    

Integration with Laravel’s Logging

  • Stacked Channels: Combine with other channels (e.g., single, daily) in logging.php:
    'stack' => [
        'channels' => ['stack', 'telegram'],
    ],
    
  • Conditional Logging: Use if checks to route logs dynamically:
    if (app()->environment('production')) {
        \Log::channel('telegram')->warning('Production alert!');
    }
    

Customizing Output

  • Disable Formatting: Set formatted: false in config to send raw log data.
  • Add Markdown: Use Telegram’s MarkdownV2 for rich formatting:
    \Log::channel('telegram')->info('*Bold text* and `code`', [], [
        'format' => 'markdown',
    ]);
    

Scheduling Logs

  • Queue Logs for Async Delivery: Use Laravel Queues to avoid blocking:
    \Log::channel('telegram')->useQueue(true)->info('Async log message');
    
    Ensure QUEUE_CONNECTION is configured in .env.

Gotchas and Tips

Common Pitfalls

  1. Bot Token/Chat ID Mismatch

    • Verify TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID are correct.
    • Test with a simple bot like @BotFather.
  2. Rate Limits

    • Telegram bots have strict rate limits.
    • Avoid spamming logs; use warning/error for critical alerts only.
  3. Queue Delays

    • If using queues, logs may delay. Monitor failed_jobs table for errors.
  4. Formatting Issues

    • If formatted: true, ensure log data is JSON-serializable.
    • Escape special characters (e.g., _, *) in Markdown mode.

Debugging

  • Check Bot Permissions: Ensure the bot has permission to send messages to the chat.
  • Inspect Raw Output: Temporarily set formatted: false to debug payloads.
  • Log Channel Errors: Wrap logs in try-catch:
    try {
        \Log::channel('telegram')->error('Test error');
    } catch (\Exception $e) {
        \Log::channel('single')->error('Telegram log failed: ' . $e->getMessage());
    }
    

Extension Points

  1. Custom Formatting Override the formatter via a service provider:

    $this->app->bind(\Arhx\TelegramLogChannel\Formatter\FormatterInterface::class, function () {
        return new CustomFormatter();
    });
    
  2. Filtering Logs Extend the channel to filter logs before sending:

    \Log::channel('telegram')->extend('filtered', function ($app) {
        return tap(new \Arhx\TelegramLogChannel\TelegramChannel($app), function ($channel) {
            $channel->setFilter(function ($level, $message, $context) {
                return str_contains($message, 'critical');
            });
        });
    });
    
  3. Multiple Chats Use a single bot token with multiple chat IDs by extending the channel:

    \Log::channel('telegram')->extend('multi', function ($app) {
        return new \Arhx\TelegramLogChannel\TelegramChannel($app, [
            'chat_ids' => [123, 456], // Array of chat IDs
        ]);
    });
    

Pro Tips

  • Log Exceptions Globally: Add to App\Exceptions\Handler:
    public function report(Throwable $exception) {
        \Log::channel('telegram')->error('Uncaught exception', [
            'exception' => $exception->getMessage(),
            'trace' => $exception->getTraceAsString(),
        ]);
    }
    
  • Environment-Specific Logging: Disable in local:
    'telegram' => [
        'driver' => 'telegram',
        'enabled' => app()->environment('production'),
    ],
    
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