Skip to content

Commit

Permalink
Added usage Monolog TelegramBotHandler for logging
Browse files Browse the repository at this point in the history
  • Loading branch information
tabuna committed Jan 11, 2025
1 parent d9bbbb6 commit c019c90
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 43 deletions.
37 changes: 1 addition & 36 deletions app/Services/TelegramBot.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use NotificationChannels\Telegram\TelegramMessage;

class TelegramBot
{
Expand Down Expand Up @@ -98,39 +96,6 @@ public function isSpam(?string $message, $userId = null): bool
return true;
}

$detector = new SpamDetector($message);

return $detector->isSpam();
}

/**
* Send notification to Telegram.
*/
public static function notificationToTelegram(\Throwable $exception): void
{
if (config('app.env') !== 'production') {
return;
}

// Send notification to Telegram
try {
TelegramMessage::create()
->to(config('services.telegram-bot-api.chat_id'))
->line('*⚠️ Ой-ой-ой!* Возникла неприятность в нашем коде. Пользователь столкнулся с неожиданной ошибкой на сайте.')
->line('`')
->escapedLine(Str::of($exception->getMessage())->ucfirst())
->line('`')
->escapedLine('📄 Код ошибки: '.$exception->getCode())
->escapedLine('📂 Файл: '.Str::after($exception->getFile(), base_path()).'#'.$exception->getLine())
->line('')
->line('*🔧 Что делать?*')
->line('Давайте взглянем на этот участок кода внимательно и исправим проблему. С вашими умениями мы сможем преодолеть эту преграду!')
->line('')
->line('*💪 Не сдавайтесь!*')
->line('Каждая ошибка - это шанс стать лучше. Давайте использовать этот момент, чтобы улучшить наш код и стать еще сильнее. Удачи!')
->send();
} catch (\Exception|\Throwable) {
// without recursive
}
return (new SpamDetector($message))->isSpam();
}
}
7 changes: 1 addition & 6 deletions bootstrap/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
use App\Http\Middleware\RedirectToBanPage;
use App\Http\Middleware\SetDefaultVersionForUrl;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
Expand All @@ -26,8 +25,4 @@
'goronich',
]);
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->report(function (Throwable $e) {
\App\Services\TelegramBot::notificationToTelegram($e);
});
})->create();
->create();
13 changes: 12 additions & 1 deletion config/logging.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Handler\TelegramBotHandler;
use Monolog\Processor\PsrLogMessageProcessor;

return [
Expand Down Expand Up @@ -54,7 +55,7 @@
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
'channels' => ['single', 'telegram'],
'ignore_exceptions' => false,
],

Expand Down Expand Up @@ -94,6 +95,16 @@
'processors' => [PsrLogMessageProcessor::class],
],

'telegram' => [
'driver' => 'monolog',
'handler' => TelegramBotHandler::class,
'level' => env('LOG_LEVEL', 'debug'),
'with' => [
'apiKey' => env('TELEGRAM_BOT_TOKEN', ''),
'channel' => env('TELEGRAM_CHAT_ID', ''),
],
],

'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
Expand Down

0 comments on commit c019c90

Please sign in to comment.