How To Send Application Logs To Telegram In Laravel

Streamlining Error Monitoring: Integrating Laravel Application Logs with Telegram

How To Send Application Logs To Telegram In Laravel

How To Send Application Logs To Telegram Channel In Laravel

Hello Web Artisans,

Today's article will explore how to send application logs to a Telegram Channel using Laravel. But first, let's delve into the significance of logs in software development and why they're crucial for our work.

Logging is an important aspect of SD because it helps the developers to understand why and where these errors or execution happening in the Application.

Logger and Logger Types in Laravel

Laravel Logger - This logger functionality works with different types of channel specification information.

Laravel Logger Types - The List of Error Types and Functions

Logger TypeLogger Function
Debug: Used for detailed debug informationLog::debug("this is debug logger");
Info: Used to log informational messagesLog::info('This is an informational message.');
Notice: Used for normal but significant eventsLog::notice('This is a notice message.');
Warning: Used to indicate something unexpected that is not necessarily an errorLog::warning('This is a warning message.');
Error: Used to record error events that might still allow the application to continue running.Log::error('This is an error message.');
Critical: Used for critical conditions, like serious errors that cause major disruptions.Log::critical('This is a critical message.');
Alert: Used to indicate that immediate action is required.Log::alert('This is an alert message.');
Emergency: Used to log system is unusable situations.Log::emergency('This is an emergency message.');

The accepted parameters in Laravel Logger Functions:

  • message (string) - The information about the logger types.

  • context(array) - The message bind parameters in the logger.

Create a Telegram Bot and Make An Admin in a Channel

The List Of Steps to create a telegram bot and make an admin channel

  • Connect with Telegram Bot Father to create a Telegram Bot - Search in the Telegram App To Find.

  • Select start command and create the bot.

Connect with Telegram Bot Father to create a Telegram Bot

  • Select newbot command and give the name of the bot.

  • Then set the username that ends with _bot.

  • Get the Access Token for Future Use.

 newbot command and give the name of the bot

  • Navigate to Profile and Click Create Channel

  • Set The Channel Name, Description and Profile Pic(Optional)

Create Telegram Channel in Profile Section

  • Click the create button and make the channel if public or private.

  • Add the bot as member and make an admin

In the channel Text the message "Hi".

Telegram Channel Created!

Integrate and Send Application Logs to Telegram

Telegram Bot Configuration In Laravel Application Logging

In this section, we will walk through the process of setting up and integrating a Telegram bot for logging in a Laravel application, detailing each step along the way.

  • Add the Environment variables in .env .

      #.env
      TELEGRAM_API_KEY=Telegram-Access-Key
      TELEGRAM_CHANNEL=Channel-Id
    
  • Add the Logger Classes on top and Channel Configuration in logging.php .

      # config\logging.php
      <?php
      use Monolog\Handler\FilterHandler;
      use Monolog\Handler\TelegramBotHandler;
    
      # config\logging.php
      <?php
              'stack' => [
                  'driver' => 'stack',
                  'channels' => ['single','telegram'],
                  'ignore_exceptions' => false,
              ],
      #end of the array - add this channel
              "telegram" => [
                  'driver'  => 'monolog',
                  'handler' => FilterHandler::class,
                  'level' => env('LOG_LEVEL', 'debug'),
                  'with' => [
                      'handler' => new TelegramBotHandler($apiKey = env('TELEGRAM_API_KEY'), $channel = env('TELEGRAM_CHANNEL'))
                  ]
              ],
    
  • If Specific type of logger message only need set the level => logger_type

  • Better Understanding go through this commit changes 🔽 Click the Below Link

  • Telegram Bot Configuration Commit Link

  • Place the Telegram API Key and the Telegram Channel identifiers in the .env file.

  • We have already obtained the Laravel API Key from the Bot Father Channel, which is now set in the .env file.

  • The parameter for the Telegram channel can take either a string or an integer as its value.

  • if the channel is public set the value as channel username

      TELEGRAM_API_KEY=Telegram-Access-Key
      TELEGRAM_CHANNEL=@laravel_app_logger
    
  • If the channel is private get the channel id from the TelegramGetUpdatesAPI URL.

      #https://api.telegram.org/bot{TELEGRAM_API_KEY}/getUpdates
    
  • {TELEGRAM_API_KEY} -In this place add the API key and open the URL new tab in the browser.

  • In the new tab get the channel id in the JSON with Bot Integrated Channel

              "chat": {
                "id": "channel_id",
                "title": "Laravel-APP-Logger",
                "type": "channel"
              }
    
    💡
    NOTE:

    Before hit this endpoint send the "hi"message in the channel and get the channel id

  • If the channel id is starts with minus it is private. if it is without minus it is public or use username

  • set the channel id in the .env

      #IF public-channel
      TELEGRAM_CHANNEL=@laravel_app_logger
      #OR
      TELEGRAM_CHANNEL=12345678
      #IF PRIVATE CHANNEL
      TELEGRAM_CHANNEL=-12345678
    
  • Now we are ready to share the logs in telegram channel.

<?php
use Illuminate\Support\Facades\Log;

Log::error("error");
Log::debug("debug");

Send Application Logs to Telegram Channel in Laravel

💡
Reference Links
  1. Laravel Logging - https://laravel.com/docs/10.x/logging

  2. Explore Telegram Bot API's - https://core.telegram.org/bots/api#chat

💡
PRO-TIP

Send a Telegram Message using Custom Helper Function

The above Methods send telegram notification to application logs in the channel.

If you are planning to send other kind of notification in the channel use this helper function in for jobs , events and others.

  • if multiple channels use this function to send message based on chat id and bot token.

  • keep it safe the bot token and chat id for channel if it possible use encrypt and decrypt to processing the request.

In conclusion, integrating Telegram with your Laravel application for sending logs is a powerful way to monitor your application’s health and activity in real-time. By leveraging the simplicity and effectiveness of Telegram bots, you can keep a close eye on your application's behavior, receive instant notifications of issues, and maintain a high level of operational awareness.

I hope this article is helpful to all of you. follow and support 💜💜💜💰

💡
Connect With Me:
Gmail linkedin Whatsapp

Did you find this article valuable?

Support Dhanasekaran Ravichandran | PHP Blogs by becoming a sponsor. Any amount is appreciated!