Skip to content

Instantly share code, notes, and snippets.

@gundamew
Last active April 26, 2022 19:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gundamew/acfa0154a41efff6810046381d3f061c to your computer and use it in GitHub Desktop.
Save gundamew/acfa0154a41efff6810046381d3f061c to your computer and use it in GitHub Desktop.
Custom Logger for Laravel 5.6. Send messages to Telegram.
<?php
namespace App\Logging;
use DateTimeZone;
use Monolog\Logger;
use App\Logging\TelegramBotHandler;
use Monolog\Formatter\LineFormatter;
class FooLogger
{
/**
* Create a custom Monolog instance.
*
* @param array $config
* @return \Monolog\Logger
*/
public function __invoke(array $config)
{
Logger::setTimezone(new DateTimeZone('...'));
$handler = new TelegramBotHandler(
$config['token'], $config['chatId'], $config['level']
);
$handler->setFormatter(new LineFormatter(
null, null, false, true
));
return new Logger(config('app.name'), [$handler]);
}
}
<?php
use Monolog\Logger;
return [
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['telegram'],
],
'telegram' => [
'driver' => 'monolog',
'handler' => App\Logging\TelegramBotHandler::class,
'handler_with' => [
'token' => '...',
'chatId' => '...',
],
'formatter' => Monolog\Formatter\LineFormatter::class,
'formatter_with' => [
'dateFormat' => 'Y-m-d H:i:s',
'allowInlineLineBreaks' => false,
'ignoreEmptyContextAndExtra' => true,
],
],
],
];
<?php
namespace App\Logging;
use Monolog\Logger;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\Client as GuzzleClient;
use Monolog\Handler\AbstractProcessingHandler;
class TelegramBotHandler extends AbstractProcessingHandler
{
protected $token;
protected $chatId;
public function __construct($token, $chatId, $level = Logger::ERROR)
{
$this->token = $token;
$this->chatId = $chatId;
parent::__construct($level);
}
public function write(array $record)
{
$this->sendMessage($record['formatted']);
}
protected function sendMessage($message)
{
$client = new GuzzleClient([
'base_uri' => 'https://api.telegram.org/bot' . $this->token . '/',
]);
$client->post('sendMessage', [
'headers' => [
'Accept' => 'application/json',
],
'form_params' => [
'chat_id' => $this->chatId,
'text' => $message,
],
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment