How to send application logs to Telegram in Laravel.
Tags: laravel, telegram, logs, php
Published: 2023-01-08 20:12:35

The Laravel framework has a robust logging system that allows you to send log messages to files, system logs, and various other destinations. Logging in Laravel is channel-based, and each channel defines a specific way of writing log messages. For example, the `single` channel writes log files to a single log file, while the `daily` channel writes log to file based on date e.g. `laravel-2023-01-09.log`, and the `slack` channel sends log messages to Slack.

Laravel logging is created on top of [Monolog](https://github.com/Seldaek/monolog), which is a powerful logging library for PHP projects. In this guide, we will be looking at how to send our laravel logs to telegram channel with the help of the Telegram Bot API.

#### Prerequisites

You need to have the latest version of PHP and [Composer](https://getcomposer.org/) installed on your computer. You should also create a new Laravel project so that you can test the code snippets in this article. You can consult Laravel's [official documentation](https://laravel.com/docs/9.x/installation#your-first-laravel-project) for details on creating a new project on your machine.

Let's start by creating a laravel project with the command below:
```sh
laravel new telegram-app
```
#### OR
```sh
composer create-project laravel/laravel telegram-app
```
Navigate to the project directory using the command below:
```sh
cd telegram-app
```
Let's open the project in VsCode using the command below:
```sh
code .
```
#### Exploring the logging config file
Laravel projects include a `config` directory containing several configuration files used to customize the project's different aspects, such as the database setup, caching, session management, and more. In addition, the configuration options related to logging are also present in this directory in the `logging.php` file. Go ahead and open this file in your editor to examine its contents:
```php
<?php

use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;

return [

    'default' => env('LOG_CHANNEL', 'stack'),

    'deprecations' => [
        'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
        'trace' => false,
    ],

    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['single'],
            'ignore_exceptions' => false,
        ],

        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => env('LOG_LEVEL', 'debug'),
        ],

        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => env('LOG_LEVEL', 'debug'),
            'days' => 14,
        ],

        'slack' => [
            'driver' => 'slack',
            'url' => env('LOG_SLACK_WEBHOOK_URL'),
            'username' => 'Laravel Log',
            'emoji' => ':boom:',
            'level' => env('LOG_LEVEL', 'critical'),
        ],
        ...
     ]
];
```
As we can see, there are several options in the channel array which can be used to customize the logging aspect of our project. Let's proceed by setting up our Telegram channel and creating a Bot through [BotFather](https://telegram.me/BotFather). Open the link in your browser and start the conversation by sending the message `/start`. You should receive a message with the next steps to creating your bot.

![BotFather](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96d2uot67wwns2biwp04.png)

Click `/newbot` and choose a name & a username for your bot. The bot will generate your API token for you as seen in the image below.

![Bot setup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mbdmainhp9i5q8hpezdf.png)

We will now proceed to create a new channel `LaravelDemoLogging` and add our new bot `DemoLoggingBot` to it.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ymrbio3f12kgkp1q7z8k.png)

We need to change the channel type to public. Click the channel info and edit the channel type and set it to public. Also, set the channel username which we are going to use in our laravel project along with the API token.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rukyljdipe8rg0rtsiyy.png)

Next, let's open the `.env` file and the following variables:
```sh
TELEGRAM_API_KEY="your-api-key"
TELEGRAM_CHANNEL="@laraveldemologging"
```

> Note: the channel must have a @ prefix when setting it in the .env file.

Open the `logging.php` file and add a new channel after the `stack` array and it to the channels like so:
```php
'stack' => [
            'driver' => 'stack',
            'channels' => ['single', 'telegram'],
            'ignore_exceptions' => false,
],
"telegram" => [
            'driver'  => 'monolog',
            'handler' => FilterHandler::class,
            'level' => env('LOG_LEVEL', 'debug'),
            'with' => [
                'handler' => new TelegramBotHandler($apiKey = env('TELEGRAM_API_KEY'), $channel = env('TELEGRAM_CHANNEL'))

            ]
],
```
Next, add the handlers used within the telegram array to the top of the file like so:
```php
use Monolog\Handler\FilterHandler;
use Monolog\Handler\TelegramBotHandler;
```
Let's start Laravel tinker from the terminal then log something:
```sh
info("This is a demo log");
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/krzuad5v31obcwchj1uy.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/crh0fakm00xlrubl6ws3.png)

#### Wrapping up
In this article, you have learned about logging in Laravel and how to setup a telegram channel & bot to receive your application logs in realtime.

Don't forget to give me a shoutout on [LinkedIn](https://www.linkedin.com/in/kasim-ridwan/) & [Twitter](https://twitter.com/oluwalosheyii)

Keep learning and happy coding!!!