jacklul/monolog-telegram

Monolog处理器,通过Telegram机器人将日志以HTML格式发送到任何聊天

3.1.0 2023-11-21 18:26 UTC

This package is auto-updated.

Last update: 2024-09-21 20:07:53 UTC


README

通过Telegram机器人将日志发送到任何聊天,并使其看起来更专业!

特性

  • 持续记录批量记录 支持
  • 使用 <code></code> 标签包裹标准堆栈跟踪
  • 当消息超过最大限制时自动拆分消息

先决条件

  • Telegram机器人API令牌 - 查看这里 了解如何获取一个
  • 您想要发送日志的聊天ID - 见下方

获取聊天ID

最简单的方法之一是与目标聊天中的机器人进行交互

  • 私有和群组聊天 - 发送任何测试命令
  • 频道 - 在其中发布内容

交互后,访问 https://api.telegram.org/botTOKEN/getUpdates(将 TOKEN 替换为您的实际机器人令牌),您可以在结果JSON中找到聊天ID(chat_id)。

安装

使用 Composer 安装

$ composer require jacklul/monolog-telegram

用法

要使用此处理器,只需像添加其他 Monolog 处理器一样添加它

require 'vendor/autoload.php';

$logger = new Logger('My project');
$handler = new TelegramHandler(
    '123456789:teMbvbETojnSG93jDhnynvH8pT28H9TIB1h',  // Bot API token
    987654321,  // Target Chat ID
    Logger::ERROR,  // Log level, default: DEBUG
    true,  // Bubble up the stack or not, default: true
    true,  // Use cURL or not? default: true = use when available
    10,    // Timeout for API requests, default: 10
    true   // Verify SSL certificate or not? default: true, false only useful for development - avoid in production
);

$handler->setFormatter(new TelegramFormatter());    // Usage of this formatter is optional but recommended if you want better message layout
$logger->pushHandler($handler);

$logger->error('Error!');

为防止聊天中垃圾邮件和超出Telegram API限制,建议使用 DeduplicationHandler 和/或 BufferHandler,对于生产环境,理想的解决方案是

$handler = new TelegramHandler('TOKEN', 123456789);
$handler->setFormatter(new TelegramFormatter());

// Combine all log entries into one and force batch processing
$handler = new BufferHandler($handler);

// Make sure that particular log stack wasn't sent before
$handler = new DeduplicationHandler($handler);

// Keep collecting logs until ERROR occurs, after that send collected logs to $handler
$handler = new FingersCrossedHandler($handler, new ErrorLevelActivationStrategy(Logger::ERROR));

$logger->pushHandler($handler);

您可以自定义格式化程序

$html = true;    // Choose whether to send the message in HTMl format
$format = "%emoji% <b>%level_name%</b> (%channel%) [%date%]\n\n%message%\n\n%context%%extra%";   // EMOJI ERROR (My project) [2018-05-01 15:55:15 UTC]
$date_format = 'Y-m-d H:i:s e';       // 2018-05-01 15:55:15 UTC, format must be supported by DateTime::format
$separator = '-';       // Seperation character for batch processing - when empty one empty line is used
$emojis = [         // Override any level emoji
    'NOTICE' => '🤖'
];

$handler->setFormatter(new TelegramFormatter($html, $format, $date_format, $separator, $emojis));

运行测试

创建 .env 文件

TELEGRAM_TOKEN=BOT_TOKEN
TELEGRAM_CHAT_ID=CHAT_ID_THE_BOT_WILL_SPAM;

运行 composer check-codecomposer test

许可证

LICENSE