Send PHP errors to Telegram with lograh-php package

Send PHP errors to Telegram with lograh-php package

Photo by KOBU Agency on Unsplash

Introduction

Error handling in PHP

Error handling is one of the critical aspects of any PHP application. When unexpected situations occur during program execution, proper error management ensures that the application can easily handle these scenarios without crashing or producing undesirable outcomes.

In PHP, the ‘try’ and ‘catch’ constructs are fundamental components of the language’s exception handling mechanism. These basically tells the source code to ‘try’ and execute a block of code and if an exception occurs, it ‘catch’es it and any action can be taken in the ‘catch’ block without stopping the running process.

Here’s a basic example of a try-catch block in action.

<?php
 try {
  // run piece of code that may throw an exception
 } catch (\Throwable $exception) {
  // log or process the exception
  echo “Caught an exception: “ . $exception->getMessage();
 }
 // do some other things

In this example, we have a ‘try’ block that might throw an exception and if one were to occur, it is caught in the corresponding ‘catch’ block and you can access any information about the exception from the ‘$exception’ variable.

The lograh-php package

Let’s say we have a scenario where you have a critical process running in your PHP project and you would like to be notified outside of your app as soon as an exception occurs. There are a lot of packages and third-party tools out there that can be used to implement, but a host of them are either too complicated to set up, have a lot of dependencies (which can impact performance) or cost you to use.

The lograh-php package is a very light-weight solution for this as it easily utilizes Telegram’s popular Bots API, allowing you to send information about these exceptions directly to any dedicated chat, group or channel on your Telegram account.


Setup

Before you can use this package, you need a Telegram Bot setup on your account. What we need here is the API Key generated after creating your Bot and your chat, group or channel ID.

Obtain your bot token

Obtaining your Bot token is a pretty straightforward process in the steps listed below.

Follow this link https://t.me/botfather to interact with the BotFather to generate a new Telegram bot.

Once it opens up, if not already selected, type in the command ‘/newbot’ in the message box or select the option from the side menu and follow through with the prompts as shown in the screenshot below. screenshot of how to create your Telegram bot and get generate an API token

Copy the token and keep in a secure place. screenshot of the section with the API token

Then click on your bot link. screenshot of the section with the Telegram bot link

This takes you to a chat window with your window, then you click “Start” button at the bottom of the screen or enter the “/start” command in the message box.

Get your chat ID

Your chat ID is used to identify the chat that the logs would be sent to. This could be your direct inbox, a public/private that you have admin access to. In this scenario, we will be sending the logs directly to your chat.

Follow this link https://t.me/userinfobot to interact with the “userinfobot” to display your user info when you forward a message to it.

Click the “start” button on the bottom of the screen or type in the command “/start”.

screenshot of user details after using the start prompt

This should show your user details.

Copy your ID and also keep in a secure place for later.

Include the lograh-php package

If your PHP project is setup with composer, you can easily import the package by running the command below

composer require codelikesuraj/lograh-php

screenshot of terminal process after adding the lograh-php package to the package Or you can copy/clone the project from github, github.com/codelikesuraj/lograh-php.


Usage

We are going to be using a skeleton project I created specifically for this tutorial, you can check out the source-code here github.com/codelikesuraj/lograh-tut.

Create an index.php file in the root of the project

touch index.php

Inside the index.php file, initialize an instance of the LograhPHP\Logger class with your project name, bot token and chat ID.

<?php
require_once("vendor/autoload.php");

$logger = new Codelikesuraj\LograhPHP\Logger(
    appName: "Lograh Tutorial",
    botToken: "api_key_generated_from_your_telegram_bot",
    chatId: "id_of_your_telegram_chat_or_channel_or_group"
);
...

Then add this simple try-catch block just below it.

...
try {
    throw new \Exception("I am an error from Lograh-tut");
} catch (\Throwable $exception) {
    // send exception to Telegram using any
    // of the following methods
    $logger->reportAsText($exception);
}

Now run the code and you should receive a message on your telegram that looks something like this.

php index.php

screenshot of message when an exception is caught and the 'reportAsText' method is used Also, for a JSON style message, you can use either use the ‘reportAsJson()’ or ‘reportAsJsonWithStackTrace()’ method which as the name suggests sends the report as a JSON without and with the stack trace respectively.

Here’s a sample of what those implementations might look like.

...
$logger->reportAsJson($exception);
...

screenshot of message when 'reportAsJson' method is used

...
$logger->reportAsJsonWithStackTrace($exception);
...

screenshot of message when 'reportAsJsonWithStackTrace' method is used