telegram-private-logger
v1.0.1
Published
A lightweight, typed logger for sending logs directly to Telegram chats using the official Telegram Bot API with full TypeScript support.
Downloads
5
Readme
Telegram Private Logger
A lightweight, typed logger for sending logs directly to Telegram chats using the official Telegram Bot API with full TypeScript support.
Installation
npm install telegram-private-loggerQuick Start
import { init } from "telegram-private-logger";
// Initialize the logger client
const logger = init({
token: "your-telegram-bot-token",
chatId: "your-chat-id",
});
// Send a log message
await logger.track({
title: "User Login",
icon: "🔐",
source: "auth-service",
content: "User successfully logged in",
tags: {
userId: "12345",
method: "email",
},
});Usage
Basic Setup
Create a logger client in your project:
// logger.ts
import { init } from "telegram-private-logger";
export const telegramLogger = init({
token: process.env.PRIVATE_LOGGER_TOKEN!,
chatId: process.env.PRIVATE_LOGGER_CHAT_ID!,
});Using the Logger
// app.ts
import { telegramLogger } from "./logger";
// Track user actions
await telegramLogger.track({
title: "Dashboard Loaded",
icon: "📊",
source: "dashboard-service",
content: "User dashboard loaded successfully",
tags: {
userId: "12345",
organizationId: "67890",
},
});
// Track errors
await telegramLogger.track({
title: "API Error",
icon: "❌",
source: "api-service",
content: "Failed to fetch user data from database",
tags: {
endpoint: "/api/users",
statusCode: "500",
error: "database_connection_failed",
},
});
// Track simple events
await telegramLogger.track({
title: "User Action",
icon: "👤",
source: "user-service",
});Environment Variables
# .env
PRIVATE_LOGGER_TOKEN=your_bot_token_here
PRIVATE_LOGGER_CHAT_ID=your_chat_id_hereAPI Reference
init(config: TelegramPrivateLoggerConfig): TelegramPrivateLoggerClient
Initializes a new telegram logger client.
Parameters
config(TelegramPrivateLoggerConfig): Configuration objecttoken(string): Your Telegram bot authentication tokenchatId(string): The chat ID where logs will be sent
Returns
TelegramPrivateLoggerClient: A client instance with tracking capabilities
TelegramPrivateLoggerClient.track(options: LoggerOptions): Promise<void>
Sends a log entry to your Telegram chat.
Parameters
options(LoggerOptions): Logging options objecttitle(string): Title for the log entryicon(string): Emoji or icon (e.g., "🔐", "❌", "✅")source(string): Source identifier (e.g., "auth-service", "api-gateway")content?(string): Optional detailed content/messagetags?(Record<string, string>): Optional key-value pairs for categorization
Returns
Promise<void>: Resolves when the log is sent successfully
TypeScript Support
This package is written in TypeScript and provides full type definitions. All parameters are properly typed and will show up in your IDE with autocomplete and type checking.
import {
init,
LoggerOptions,
TelegramPrivateLoggerConfig,
} from "telegram-private-logger";
// Full type safety
const config: TelegramPrivateLoggerConfig = {
token: process.env.PRIVATE_LOGGER_TOKEN!,
chatId: process.env.PRIVATE_LOGGER_CHAT_ID!,
};
const logData: LoggerOptions = {
title: "Database Connection",
icon: "💾",
source: "database-service",
content: "Successfully connected to PostgreSQL",
tags: {
database: "postgres",
connection: "pool",
},
};
const client = init(config);
await client.track(logData);Examples
Error Tracking
const logError = async (error: Error, context: Record<string, string>) => {
await telegramLogger.track({
title: "Application Error",
icon: "🚨",
source: "error-handler",
content: error.message,
tags: {
errorType: error.name,
stack: error.stack?.split("\n")[0] || "",
...context,
},
});
};User Activity Tracking
const trackUserAction = async (
action: string,
userId: string,
details?: string
) => {
await telegramLogger.track({
title: `User Action: ${action}`,
icon: "👤",
source: "user-service",
content: details,
tags: {
userId,
action,
timestamp: new Date().toISOString(),
},
});
};API Request Logging
const logApiRequest = async (
method: string,
endpoint: string,
statusCode: number
) => {
await telegramLogger.track({
title: `API ${method} ${endpoint}`,
icon: statusCode >= 400 ? "❌" : "✅",
source: "api-gateway",
content: `HTTP ${method} ${endpoint} returned ${statusCode}`,
tags: {
method,
endpoint,
statusCode: statusCode.toString(),
},
});
};Configuration
Required Parameters
- token: Your Telegram bot token (get it from @BotFather)
- chatId: The chat ID where logs will be sent (can be a user chat, group, or channel)
Required Log Fields
The following fields are required for each log entry:
- title: The main title of the log entry
- icon: An emoji or icon to represent the log type
- source: The source/service identifier
Optional Log Fields
- content: Detailed description of what happened
- tags: Key-value pairs for additional context
// Minimal required log
await telegramLogger.track({
title: "Simple event",
icon: "🔔",
source: "service-name",
});
// Full log with all fields
await telegramLogger.track({
title: "Complex event",
icon: "🎯",
source: "service-name",
content: "Detailed description of what happened",
tags: {
category: "user-action",
priority: "high",
environment: "production",
},
});Getting Your Telegram Bot Token and Chat ID
1. Create a Bot
- Message @BotFather on Telegram
- Send
/newbotand follow the instructions - Save the bot token you receive
2. Get Your Chat ID
- Start a chat with your bot
- Send any message to the bot
- Visit:
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates - Find your chat ID in the response
Error Handling
The logger will automatically log errors to the console if the request fails:
try {
await telegramLogger.track({
title: "Test log",
icon: "🧪",
source: "test-service",
});
} catch (error) {
// The logger will automatically console.error the response
// You can also handle errors here if needed
console.error("Failed to send log:", error);
}Message Format
The logger sends formatted messages to Telegram using MarkdownV2 format:
🔐 User Login:
Source: auth-service
User successfully logged in
userId: *12345*
method: *email*License
MIT
