vsavritsky/monolog-telegram

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

1.9 2019-12-25 07:45 UTC

This package is not auto-updated.

Last update: 2024-09-17 10:01:08 UTC


README

通过 Telegram 机器人将您的日志发送到任何聊天,并使它们看起来更精致!

特性

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

先决条件

  • Telegram Bot API 令牌 - 查看此处 了解如何获取一个
  • 您想要发送日志的聊天 ID - 详见下文

获取聊天 ID

获取聊天 ID 最简单的方法之一是与目标聊天中的机器人互动

  • 私人聊天和群组聊天 - 发送任何虚拟命令
  • 频道 - 在其中发布内容

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

安装

使用 Composer 安装

$ composer require jacklul/monolog-telegram

使用方法

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

require 'vendor/autoload.php';

$api_token = '123456789:teMbvbETojnSG93jDhnynvH8pT28H9TIB1h';    // Bot API token
$chat_id = 987654321;    // Target Chat ID
$level = Logger::ERROR;     // Log level
$bubble = true;     // Bubble up the stack or not
$use_curl = true;    // Use cURL or not? (default: use when available)
$timeout = 10;   // Timeout for API requests
$verify_peer = true;   // Verify SSL certificate or not? (development/debugging)

$logger = new Logger('My project');
$handler = new TelegramHandler($api_token, $chat_id, $level, $bubble, $use_curl, $timeout, $verify_peer);
$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 = "<b>%level_name%</b> (%channel%) [%date%]\n\n%message%\n\n%context%%extra%";   // 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

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

许可

查看 LICENSE