jacklul / monolog-telegram
Monolog处理器,通过Telegram机器人将日志以HTML格式发送到任何聊天
3.1.0
2023-11-21 18:26 UTC
Requires
- php: ^8.1
- ext-json: *
- ext-mbstring: *
- monolog/monolog: ^3.0
Requires (Dev)
- ext-curl: *
- phpunit/phpunit: ^9.0
- squizlabs/php_codesniffer: ^3.2
- vlucas/phpdotenv: ^5.0
Suggests
- ext-curl: cURL generally works better and is recommended
README
通过Telegram机器人将日志发送到任何聊天,并使其看起来更专业!
特性
先决条件
- 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-code
和 composer test
。
许可证
见 LICENSE。