uzhlaravel/telegramlogs 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

uzhlaravel/telegramlogs

Composer 安装命令:

composer require uzhlaravel/telegramlogs

包简介

Monitor your Laravel application logs in real-time through Telegram. This package delivers instant notifications of critical events directly to your Telegram channel, with support for threaded discussions and Markdown formatting.

README 文档

README

Latest Version on Packagist GitHub Tests Action Status Code style Total Downloads License

A Laravel package that sends your application logs, exceptions, and model activity events directly to a Telegram channel or group — in real time.

Supports Laravel 10 → 13, PHP 8.2+, and includes production-only mode so notifications stay silent during local development.

Table of Contents

Features

  • Monolog integration — drop-in telegram log channel; works with LOG_CHANNEL=telegram or as a stacked channel
  • Direct messaging — send arbitrary text to any chat from anywhere in your app
  • Activity log — track Eloquent model created / updated / deleted events and push them to Telegram (inspired by spatie/laravel-activitylog)
  • Production-only mode — restrict notifications to specific environments with a single env var
  • Smart formatting — emoji-labelled MarkdownV2 messages with context, exception details, and stack traces
  • Long message splitting — automatically splits messages that exceed Telegram's 4096-char limit
  • Forum/topic support — route messages to specific threads in a Telegram group
  • Interactive install — guided telegramlogs:install command

Requirements

Dependency Version
PHP ^8.2
Laravel ^10.0 | ^11.0 | ^12.0 | ^13.0

Installation

composer require uzhlaravel/telegramlogs

Run the interactive setup wizard:

php artisan telegramlogs:install

The wizard will publish the config file, help you set environment variables, optionally enable activity log, and send a test message.

Or publish the config manually:

php artisan vendor:publish --tag="telegramlogs-config"

Configuration

Environment Variables

Add these to your .env file:

# Required
TELEGRAM_BOT_TOKEN=your_bot_token_here
TELEGRAM_CHAT_ID=your_chat_id_here

# Optional
TELEGRAM_LOG_LEVEL=critical          # minimum level to forward (default: critical)
TELEGRAM_TOPIC_ID=                   # forum thread / topic ID
TELEGRAM_TIMEOUT=10                  # Telegram API timeout in seconds

# Environment control — see next section
TELEGRAM_ENVIRONMENTS=production     # default: production only

# Activity log
TELEGRAM_ACTIVITY_LOG=false          # set true to enable model event tracking
TELEGRAM_ACTIVITY_LOG_LEVEL=info     # log level for activity notifications

Full Reference

Variable Required Default Description
TELEGRAM_BOT_TOKEN Yes Bot API token from @BotFather
TELEGRAM_CHAT_ID Yes Target chat, channel, or group ID
TELEGRAM_TOPIC_ID No null Forum topic (thread) ID
TELEGRAM_TOPIC_MESSAGE_ID No null Forum thread message ID
TELEGRAM_LOG_LEVEL No critical Minimum PSR-3 level to send
TELEGRAM_TIMEOUT No 10 HTTP timeout in seconds
TELEGRAM_ENVIRONMENTS No production Comma-separated env list, or *
TELEGRAM_ACTIVITY_LOG No false Enable model activity tracking
TELEGRAM_ACTIVITY_LOG_LEVEL No info Log level for activity messages

Restrict to Production Only

By default, notifications are only sent when APP_ENV=production. This prevents your local machine or CI from flooding your Telegram channel.

# Only production (default)
TELEGRAM_ENVIRONMENTS=production

# Production and staging
TELEGRAM_ENVIRONMENTS=production,staging

# Every environment — useful for local debugging
TELEGRAM_ENVIRONMENTS=*

The current environment and whether notifications are active are both shown in:

php artisan telegramlogs:test --config

Usage

Log Channel Integration

Set Telegram as your default channel:

LOG_CHANNEL=telegram

Or add it to a stack so critical logs go to both your file log and Telegram:

// config/logging.php
'channels' => [
    'stack' => [
        'driver'   => 'stack',
        'channels' => ['daily', 'telegram'],
    ],
],

Use it like any Laravel logger:

use Illuminate\Support\Facades\Log;

Log::error('Payment processing failure');

Log::critical('Database unreachable', [
    'connection' => 'mysql',
    'host'       => config('database.connections.mysql.host'),
]);

try {
    // ...
} catch (\Exception $e) {
    Log::error('Unexpected exception', ['exception' => $e]);
}

Messages arrive in Telegram formatted like this:

❌ ERROR — MyApp [production]

Payment processing failure

Context:
{
  "connection": "mysql"
}

🕐 2025-08-19 14:32:01 UTC

Direct Messaging

Send arbitrary messages to Telegram without going through the logger — useful for contact forms, webhooks, or manual alerts.

use Uzhlaravel\Telegramlogs\Facades\TelegramMessage;

// Simple text
TelegramMessage::message('Scheduled backup completed.');

// With Telegram API options
TelegramMessage::send('Deployment finished', [
    'parse_mode'               => 'HTML',
    'disable_web_page_preview' => true,
]);

// Send to a different chat
TelegramMessage::toChat('-100987654321', 'Alert for ops team');

// Test connectivity
TelegramMessage::test();

// Get bot information
TelegramMessage::getBotInfo();

Activity Log

Inspired by spatie/laravel-activitylog, the activity log tracks Eloquent model events and pushes a formatted notification to Telegram.

Enable it in .env:

TELEGRAM_ACTIVITY_LOG=true

HasTelegramActivity Trait

Add the trait to any Eloquent model to automatically track its lifecycle events:

use Uzhlaravel\Telegramlogs\Traits\HasTelegramActivity;

class Post extends Model
{
    use HasTelegramActivity;
}

On created, updated, or deleted, a message like the following is sent to Telegram:

🟢 Activity — MyApp [production]

Created Post

Subject: Post #42
Properties:
{
  "attributes": { "title": "Hello World", "status": "draft" }
}

🕐 2025-08-19 14:32:01 UTC

Customise per model:

use Uzhlaravel\Telegramlogs\Traits\HasTelegramActivity;

class Order extends Model
{
    use HasTelegramActivity;

    // Track only these events for this model
    protected array $telegramActivityEvents = ['created', 'deleted'];

    // Custom description
    public function getTelegramActivityDescription(string $event): string
    {
        return ucfirst($event) . ' order #' . $this->id . '' . $this->status;
    }

    // Extra properties to include
    public function getTelegramActivityProperties(string $event): array
    {
        return ['total' => $this->total, 'customer' => $this->customer->name];
    }
}

Global event list is controlled in config/telegramlogs.php:

'activity_log' => [
    'events'             => ['created', 'updated', 'deleted'],
    'include_old_values' => true,   // previous values on update
    'include_new_values' => true,   // changed values on update
],

TelegramActivity Facade

For manual / one-off activity notifications, use the fluent facade:

use Uzhlaravel\Telegramlogs\Facades\TelegramActivity;

TelegramActivity::performedOn($post)
    ->causedBy(auth()->user())
    ->withProperty('plan', 'pro')
    ->event('published')
    ->dispatch('Post was published');

// Simpler form
TelegramActivity::log('Nightly cleanup job finished');

Artisan Commands

# Interactive setup
php artisan telegramlogs:install

# Send a test log message
php artisan telegramlogs:test

# Send with a custom message and level
php artisan telegramlogs:test --message="Health check OK" --level=warning

# Send a test activity notification
php artisan telegramlogs:test --activity

# Show current configuration (includes environment status)
php artisan telegramlogs:test --config

# List available log levels
php artisan telegramlogs:test --list

Log Levels

Level Emoji Use Case
emergency 🚨 System is unusable
alert 🔴 Immediate action required
critical 💥 Critical conditions
error Runtime errors
warning ⚠️ Potential issues
notice 📢 Significant normal events
info ℹ️ General operational messages
debug 🐛 Detailed diagnostic information

Getting Telegram Credentials

1. Create a Bot

  1. Open @BotFather in Telegram
  2. Send /newbot and follow the prompts
  3. Copy the token into TELEGRAM_BOT_TOKEN

2. Get Your Chat ID

  • Channel — add the bot as an admin; the channel username (@mychannel) or numeric ID (-100xxxxxxxxx) works
  • Group — add the bot to the group; send a message, then call https://api.telegram.org/bot<token>/getUpdates to find chat.id
  • Private chat — start a chat with the bot, then use getUpdates

3. Forum Topics (optional)

  1. Enable Topics in your group settings
  2. Create a topic and send a message
  3. From getUpdates, copy message_thread_idTELEGRAM_TOPIC_ID

Security

  • Store TELEGRAM_BOT_TOKEN only in .env — never commit it
  • Restrict which commands the bot can receive (via BotFather → /mybots → Bot Settings → Group Privacy)
  • Audit who has access to your Telegram channel regularly

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/my-feature
  3. Commit your changes: git commit -m 'Add my feature'
  4. Push: git push origin feature/my-feature
  5. Open a pull request

Development commands:

git clone https://github.com/Uzziahlukeka/telegrammonitor.git
cd telegrammonitor
composer install
composer test        # run test suite
composer analyse     # PHPStan static analysis
composer format      # Laravel Pint code style

License

This package is open-sourced software licensed under the MIT License.

💖 Made with love by Uzziah Lukeka

uzhlaravel/telegramlogs 适用场景与选型建议

uzhlaravel/telegramlogs 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.6k 次下载、GitHub Stars 达 8, 最近一次更新时间为 2025 年 02 月 01 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「markdown」 「notifications」 「monitoring」 「laravel」 「logs」 「realtime」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 uzhlaravel/telegramlogs 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 uzhlaravel/telegramlogs 我们能提供哪些服务?
定制开发 / 二次开发

基于 uzhlaravel/telegramlogs 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.6k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 9
  • 点击次数: 11
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 8
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-02-01