Publications / .NET Logging Provider for Telegram

Sunday, 31 January 2021
.NET Logging Provider for Telegram

It’s no secret that Telegram is currently one of the most popular messengers, especially among IT professionals. Telegram is user-friendly, has no embedded ads, and works very stable. Quite a lot of the time, I use this messenger for work and personal communication. Therefore, one day I thought it would be useful to receive notifications about some important events from services that I manage in this messenger. At that time, I was actively working on integrating the //devdigest project and Telegram, so I used the same native Telegram Bot SDK. In few days, I quickly implemented the logger.

Few days ago, I decided to return to this project. I cleaned up and refactored the source code and then deploy it to GitHub. Maybe the ability to get logs in Telegram will be useful to someone else.


Preparing bot and channel

Before moving on to configuring the logger itself, you will need to complete a few preliminary steps. Firstly you need to create a channel (public or private) where your services will display logs. After it, you need to create a bot in Telegram. Through this bot, the services will publish messages into the Telegram channel.

According to the official Telegram website’s instructions, we need another bot to create our bot. I will not describe the entire process of creating a bot since the Telegram developers themselves described it as simple and accessible as possible. I only note that we will need to get the token of the newly-created bot, and also, you must add this with the “administrator” role to the channel where we want to see the logs.

Next, you need to get the channel ID. For public channels, everything is simple — you can use the channel name as an identifier. For private channels, things are a little more complicated.

Getting ID of a private channel

To get the identifier of a private channel, you will have to use another bot — @JsonDumpBot. You need to forward any message from this channel to this bot. In response, you will receive a message similar to the following:

{
"update_id": 111001100,
"message": {
"message_id": 123456,
"from": {
"id": 12345678,
"is_bot": false,
"first_name": "FirstName",
"username": "username",
"language_code": "en"
},
"chat": {
"id": 123456,
"first_name": "FirstName",
"username": "username",
"type": "private"
},
"date": 1111111111,
"forward_from_chat": {
"id": -1123456789101,
"title": "torf.tv logs",
"type": "channel"
},
"forward_from_message_id": 1,
"forward_date": 1111111111,
"text": "test"
}
}

Channel ID is in the block forward_from_chat -> id

Now, as we have the channel ID and the bot token, we can configure the logger.

Logger configuration

To configure the logger, the TelegramLoggerOptions class is used, which contains the following fields:

  • AccesToken — bot token;
  • ChatId — identifier of the channel (private or public), or chat, where the bot will send messages;
  • LogLevel — the minimum level after which the bot should send messages into the channel. Usually, I send messages to the channel starting from the Warning or Error level;
  • Source — is the human-readable name of the service. It is useful if messages from several services come to one channel;

There are different options for configuring the logger — via code or through the configuration file.

Configura via source code

Firstly, you need to create and initialize an instance of the TelegramLoggerOptions class.

var options = new TelegramLoggerOptions
{
AccessToken = "1234567890:AAAaaAAaa_AaAAaa-AAaAAAaAAaAaAaAAAA",
ChatId = "-0000000000000",
LogLevel = LogLevel.Information,
Source = "Human Readable Project Name"
};

After it you need pass this object to extension method AddTelegram():

builder
.ClearProviders()
.AddTelegram(options)
.AddConsole();

You can fin example here.

Configure loger via appconfig.json file

Also, the logger can be configured through the application configuration file, as shown below:

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"Telegram": {
"LogLevel": "Warning",
"AccessToken": "1234567890:AAAaaAAaa_AaAAaa-AAaAAAaAAaAaAaAAAA",
"ChatId": "@channel_name",
"Source": "Human Readable Project Name"
}
},
"AllowedHosts": "*"
}
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" }, "Telegram": { "LogLevel": "Warning", "AccessToken": "1234567890:AAAaaAAaa_AaAAaa-AAaAAAaAAaAaAaAAAA", "ChatId": "@channel_name", "Source": "Human Readable Project Name" } }, "AllowedHosts": "*" }

Next you need pass insgtance of IConfiguration int extensions method AddTelegram():

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((context, builder) =>
{
if (context.Configuration != null)
builder
.AddTelegram(context.Configuration)
.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<startup>(); });

Example of this case you can find here.

How add X.Extensions.Logging.Telegram to your project

You can install package from NuGet Package Manager, or you can get source code from GitHub. Project developed under MIT license.


Read publication