technobase/alert 问题修复 & 功能扩展

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

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

technobase/alert

Composer 安装命令:

composer require technobase/alert

包简介

Laravel package for sending error notifications to Telegram channels with detailed context and stack traces

README 文档

README

Latest Version on Packagist Total Downloads License

A Laravel package for sending comprehensive error notifications to Telegram channels with detailed context, stack traces, and environment information.

Features

  • 🚨 Automatic Error Notifications - Captures all exceptions and sends them to Telegram
  • 📝 Rich Error Context - Includes file, line, URL, user ID, environment, and stack trace
  • ⚙️ Configurable - Control which environments send notifications
  • 🔒 Safe - Won't break your app if Telegram is unreachable
  • 🎯 Queue Support - Async notification processing to avoid blocking requests
  • 🧪 Testable - Includes test notification for verifying setup
  • 🎨 Markdown Formatting - Clean, readable error messages in Telegram

Requirements

  • PHP 8.2 or higher
  • Laravel 11.x or 12.x
  • A Telegram Bot Token (get one from @BotFather)
  • A Telegram Channel/Group/Chat ID

Installation

Install the package via Composer:

composer require technobase/alert

The service provider will be automatically registered via Laravel's package discovery.

Configuration

1. Publish Configuration File

php artisan vendor:publish --tag=alert-config

This creates config/alert.php in your application.

2. Set Environment Variables

Add these to your .env file:

# Telegram Bot Token (from @BotFather)
TELEGRAM_BOT_TOKEN=your-bot-token-here

# Telegram Chat ID (channel, group, or private chat)
TELEGRAM_CHAT_ID=your-chat-id-here

# Optional: Customize settings
ALERT_ENABLED=true
ALERT_NOTIFICATION_TITLE="🚨 Application Error"
ALERT_TRACE_LINES=10
ALERT_QUEUE=true

3. Configure Telegram Bot

  1. Create a bot by messaging @BotFather on Telegram
  2. Send /newbot and follow the prompts
  3. Copy the bot token to your .env file
  4. Create a Telegram channel for errors
  5. Add your bot as an administrator to the channel
  6. Get the channel ID (use @userinfobot or check Telegram API)
  7. Add the chat ID to your .env file

Usage

Automatic Error Notifications

Once configured, Alert automatically catches all exceptions in production and staging environments and sends them to your Telegram channel.

No additional code needed! Just let your application run.

Testing the Integration

Send a test notification to verify your setup:

use Illuminate\Support\Facades\Notification;
use Technobase\Alert\Notifications\TestTelegramNotification;

Notification::route('telegram', config('alert.chat_id'))
    ->notify(new TestTelegramNotification('Testing Alert integration'));

Or create a test route:

Route::get('/test-alert', function() {
    \Notification::route('telegram', config('alert.chat_id'))
        ->notify(new \Technobase\Alert\Notifications\TestTelegramNotification());
    
    return 'Test notification sent!';
});

Manual Error Notifications

You can manually send error notifications:

use Illuminate\Support\Facades\Notification;
use Technobase\Alert\Notifications\TelegramErrorNotification;

try {
    // Your code that might fail
    riskyOperation();
} catch (\Exception $e) {
    Notification::route('telegram', config('alert.chat_id'))
        ->notify(new TelegramErrorNotification(
            title: 'Custom Error Title',
            message: $e->getMessage(),
            context: [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'custom_data' => 'additional context',
            ]
        ));
    
    throw $e; // Re-throw if needed
}

Disabling for Specific Environments

Edit config/alert.php:

'enabled_environments' => [
    'production',
    'staging',
    // 'local' - not included, won't send notifications locally
],

Or disable entirely:

ALERT_ENABLED=false

Configuration Options

Option Environment Variable Default Description
enabled ALERT_ENABLED true Enable/disable package
bot_token TELEGRAM_BOT_TOKEN null Telegram bot API token
chat_id TELEGRAM_CHAT_ID null Telegram chat/channel ID
enabled_environments - ['production', 'staging'] Environments to send notifications
notification_title ALERT_NOTIFICATION_TITLE 🚨 Application Error Title of error notifications
trace_lines ALERT_TRACE_LINES 10 Max stack trace lines
queue ALERT_QUEUE true Queue notifications
queue_connection ALERT_QUEUE_CONNECTION null Queue connection to use
log_notification_errors ALERT_LOG_ERRORS false Log notification failures
include_request_data ALERT_INCLUDE_REQUEST true Include URL & user ID
include_environment ALERT_INCLUDE_ENV true Include environment name

Example Telegram Notification

🚨 **Application Error**

**Message**: Call to undefined method User::nonExistent()

**File**: `/var/www/app/Services/UserService.php:42`
**URL**: `https://api.example.com/users/5`
**User**: `ID: 123`
**Environment**: `production`

**Trace**:

#0 UserController.php(23): UserService->process() #1 Router.php(822): UserController->store() #2 Pipeline.php(180): Router->dispatch() ...

Troubleshooting

Bot Not Receiving Messages

  1. Check bot is admin: Your bot must be added as an administrator to the channel
  2. Verify chat ID: Use negative ID for channels (e.g., -1001234567890)
  3. Test with curl:
    curl -X POST "https://api.telegram.org/bot{YOUR_TOKEN}/sendMessage" \
      -d "chat_id={YOUR_CHAT_ID}" \
      -d "text=Test message"

No Notifications in Production

  1. Check environment: Verify APP_ENV=production or staging
  2. Check config: Run php artisan config:cache after changes
  3. Check logs: Enable ALERT_LOG_ERRORS=true and check storage/logs/laravel.log
  4. Check queue: If using queues, ensure queue worker is running: php artisan queue:work

DNS Resolution Errors

If you see Could not resolve host: api.telegram.org:

  1. Check internet connectivity
  2. Flush DNS cache: sudo dscacheutil -flushcache (macOS)
  3. Try different DNS servers (e.g., Google DNS 8.8.8.8)
  4. Check firewall/antivirus settings

Notifications Delayed

If notifications arrive late:

  1. Check queue worker: php artisan queue:work must be running
  2. Disable queue: Set ALERT_QUEUE=false for immediate sending
  3. Check queue connection: Verify your QUEUE_CONNECTION is working

Security

Sensitive Data

Be careful not to send sensitive information in error notifications:

  • Avoid logging passwords, API keys, or tokens
  • Consider filtering context data before sending
  • Use environment-specific chat channels
  • Review stack traces for sensitive information

Best Practices

  • Use separate Telegram channels for different environments
  • Restrict channel access to authorized personnel only
  • Regularly rotate bot tokens
  • Monitor notification volume to detect attacks

Testing

Run the package tests:

composer test

Or with PHPUnit directly:

vendor/bin/phpunit

Changelog

Please see CHANGELOG for recent changes.

Contributing

Contributions are welcome! Please submit pull requests to the main repository.

License

The MIT License (MIT). Please see License File for more information.

Credits

Support

For support, please contact dev@technobase.krd or open an issue on GitHub.

Made with ❤️ by Technobase

technobase/alert 适用场景与选型建议

technobase/alert 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 21 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 11 月 27 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 21
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 33
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-11-27