
The problem: errors that never become a 500
In our Telegram alert bot post, we watched for spikes of 5xx responses. That catches a lot, but plenty of real failures never produce an HTTP error at all:
A background job that fails every time it runs
A queue consumer that throws while processing a message
A webhook handler that catches an error and still returns
200A scheduled task (backup, report, sync) that silently stops working
What these have in common is that your code does notice the problem. It just writes an error log line and carries on. If you use Pino, that line goes to stdout or a file, and it stays there until someone happens to read the logs.
The fix is to make the logger itself the source of alerts. Every logger.error() call you already write becomes a Telegram message, without scattering alert code across your codebase.
This post connects the two earlier guides: Pino as the logging library (from the Pino vs Winston comparison) and Telegram as the alert channel (from the alert bot guide). We’ll build a custom Pino transport that does the forwarding.
How Pino transports work
Since version 7, Pino runs transports in a separate worker thread. Your application only serializes each log line and hands it over. The transport then does the slow work (formatting, HTTP requests) off the main thread, so a slow Telegram response never blocks your API.
The pino-abstract-transport package handles the plumbing. It gives you an async iterable of already-parsed log objects, and you decide what to do with each one:
for await (const log of source) {
// log is a plain object: { level: 50, time: 1700000000000, msg: '...', err: {...} }
}Pino can also send logs to several destinations at once. That means we can keep writing everything to stdout while sending only error and fatal logs to Telegram.
Requirements: Node.js 18+ (for built-in fetch), Pino 7 or later, and the bot token and chat ID from the Telegram alert bot post (Steps 1 and 2). If you don’t have them yet, create a bot with @BotFather and get your chat ID from the getUpdates endpoint.
Step 1: Install the packages
npm install pino pino-abstract-transportYour package.json should contain "type": "module" so the import syntax works.
Set your credentials as environment variables:
export TELEGRAM_BOT_TOKEN="123456789:AAH..."
export TELEGRAM_CHAT_ID="987654321"
export SERVICE_NAME="my-api"Step 2: Write the transport
Create telegram-transport.js. It has three jobs: format a log object into a readable message, decide whether it should be sent, and send it safely.
// telegram-transport.js
import build from 'pino-abstract-transport';
const LEVELS = { 10: 'TRACE', 20: 'DEBUG', 30: 'INFO', 40: 'WARN', 50: 'ERROR', 60: 'FATAL' };
const ICONS = { 40: '⚠️', 50: '🚨', 60: '🔥' };
// Fields Pino adds itself. Everything else is shown as context.
const RESERVED = new Set(['level', 'time', 'pid', 'hostname', 'msg', 'err']);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const escapeHtml = (value) =>
String(value).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
// Cut the RAW text first, then escape it, so an HTML entity is never split in half.
function clip(value, max) {
const raw = String(value);
let text = raw;
while (escapeHtml(text).length > max) {
text = text.slice(0, Math.floor(text.length * 0.9));
text = text.replace(/[\uD800-\uDBFF]$/, ''); // never leave half an emoji at the end
}
return escapeHtml(text) + (text.length < raw.length ? '…' : '');
}
export function formatLog(log, { service } = {}) {
const level = LEVELS[log.level] ?? String(log.level);
const icon = ICONS[log.level] ?? '🚨';
const lines = [`${icon} <b>${level}${service ? ` · ${clip(service, 40)}` : ''}</b>`];
// logger.error(err) sets msg to the error message, so avoid printing it twice
if (log.msg && log.msg !== log.err?.message) lines.push(clip(log.msg, 500));
if (log.err) {
lines.push(`<b>${clip(log.err.type ?? 'Error', 60)}:</b> ${clip(log.err.message ?? '', 400)}`);
const frames = String(log.err.stack ?? '')
.split('\n')
.map((line) => line.trim())
.filter((line) => line.startsWith('at '))
.slice(0, 5);
if (frames.length) lines.push(`<pre>${clip(frames.join('\n'), 1000)}</pre>`);
}
// Extra fields passed to the logger, e.g. { orderId: 981 }
const context = Object.entries(log).filter(([key]) => !RESERVED.has(key)).slice(0, 8);
for (const [key, value] of context) {
const text = typeof value === 'string' ? value : JSON.stringify(value);
lines.push(`<b>${clip(key, 30)}:</b> ${clip(text, 150)}`);
}
const host = log.hostname ? `${clip(log.hostname, 60)} · ` : '';
lines.push(`<i>${host}${new Date(log.time ?? Date.now()).toISOString()}</i>`);
return lines.join('\n');
}
async function postToTelegram(token, chatId, text) {
for (let attempt = 1; attempt <= 2; attempt++) {
const res = await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: chatId,
text,
parse_mode: 'HTML',
link_preview_options: { is_disabled: true },
}),
signal: AbortSignal.timeout(5000),
});
if (res.ok) return;
// Telegram says "slow down" with a 429 and a retry_after value (in seconds)
if (res.status === 429 && attempt === 1) {
const body = await res.json().catch(() => ({}));
await sleep(Math.min((body.parameters?.retry_after ?? 5) * 1000, 30_000));
continue;
}
throw new Error(`Telegram responded with ${res.status}: ${await res.text()}`);
}
}
export function createHandler(opts = {}) {
const token = opts.token ?? process.env.TELEGRAM_BOT_TOKEN;
const chatId = opts.chatId ?? process.env.TELEGRAM_CHAT_ID;
const cooldownMs = opts.cooldownMs ?? 5 * 60_000; // same error at most once per 5 min
const maxPerMinute = opts.maxPerMinute ?? 20; // hard cap across all errors
const minIntervalMs = opts.minIntervalMs ?? 1_100; // stay under Telegram's ~1 msg/sec
const seen = new Map(); // signature -> { lastSent, suppressed }
let sentTimes = [];
let dropped = 0;
let lastRequestAt = 0;
if (!token || !chatId) {
console.error('[telegram-transport] missing token or chat id, alerts are disabled');
}
function prune(now) {
if (seen.size < 500) return;
for (const [signature, entry] of seen) {
if (now - entry.lastSent >= cooldownMs) seen.delete(signature);
}
}
// This function must never throw: a failing alert should not break logging.
return async function handle(log) {
if (!token || !chatId) return;
try {
const now = Date.now();
const signature = [log.level, log.err?.type, log.err?.message ?? log.msg].join('|');
const entry = seen.get(signature);
// 1. Same error as recently? Count it, but don't send it again.
if (entry && now - entry.lastSent < cooldownMs) {
entry.suppressed++;
return;
}
// 2. Too many alerts this minute? Drop it and remember how many we dropped.
sentTimes = sentTimes.filter((t) => now - t < 60_000);
if (sentTimes.length >= maxPerMinute) {
dropped++;
return;
}
sentTimes.push(now);
const suppressed = entry?.suppressed ?? 0;
seen.set(signature, { lastSent: now, suppressed: 0 });
prune(now);
let text = formatLog(log, { service: opts.service });
if (suppressed > 0) text += `\n<i>+${suppressed} identical errors suppressed</i>`;
if (dropped > 0) {
text += `\n<i>+${dropped} other alerts dropped (rate limit)</i>`;
dropped = 0;
}
const wait = lastRequestAt + minIntervalMs - Date.now();
if (wait > 0) await sleep(wait);
lastRequestAt = Date.now();
await postToTelegram(token, chatId, text);
} catch (err) {
// Use console, not the Pino logger: logging here could create an infinite loop
console.error('[telegram-transport] failed to send alert:', err.message);
}
};
}
export default async function (opts) {
const handle = createHandler(opts);
return build(async function (source) {
for await (const log of source) {
await handle(log);
}
});
}A few details worth understanding:
formatLog()turns the log object into Telegram-flavored HTML: a level header, the message, the error type and top stack frames, and any extra fields you passed to the logger.clip()truncates the raw text before escaping it. Cutting an already-escaped string could split an entity like&in half, and Telegram rejects malformed HTML. It also drops a dangling half of an emoji if the cut lands in the middle of one. Every section has a size budget, so a message can never exceed Telegram’s 4096-character limit.The signature (level + error type + error message) identifies "the same error". Repeats within the cooldown are counted instead of sent, and the count is attached to the next alert for that error.
maxPerMinuteprotects you from a flood of different errors, such as a failing database taking down fifty code paths at once.The
429handling waits for theretry_aftervalue Telegram returns, then retries once.handle()never throws. Failures go toconsole.error, not to the Pino logger, because logging from inside the transport could trigger the transport again.
Step 3: Register the transport with Pino
Create logger.js:
// logger.js
import pino from 'pino';
import { fileURLToPath } from 'node:url';
// Pino loads the transport in a worker thread, so give it an absolute path
const telegramTarget = fileURLToPath(new URL('./telegram-transport.js', import.meta.url));
export const logger = pino({
level: process.env.LOG_LEVEL ?? 'info',
redact: ['password', '*.password', '*.token', 'req.headers.authorization'],
transport: {
targets: [
// Everything at info and above still goes to stdout as JSON
{ target: 'pino/file', level: 'info', options: { destination: 1 } },
// Only error and fatal go to Telegram
{
target: telegramTarget,
level: 'error',
options: {
service: process.env.SERVICE_NAME ?? 'my-api',
token: process.env.TELEGRAM_BOT_TOKEN,
chatId: process.env.TELEGRAM_CHAT_ID,
cooldownMs: 5 * 60_000,
maxPerMinute: 20,
},
},
],
},
});Two things to notice:
Each target has its own
level. The stdout target receivesinfoand above, while the Telegram target only ever receiveserrorandfatal.The
redactoption runs in your main thread before a log line reaches any transport. Secrets removed here never reach stdout or Telegram.
Step 4: Use it in your app
Now every logger.error() call is an alert. Pass the error under the err key so Pino serializes its type, message and stack:
import { logger } from './logger.js';
// An HTTP route
app.post('/orders', async (req, res) => {
try {
await chargeCustomer(req.body);
res.status(201).json({ ok: true });
} catch (err) {
logger.error({ err, route: 'POST /orders' }, 'Payment request failed');
res.status(502).json({ error: 'Payment service unavailable' });
}
});
// A background job: no HTTP response, so the 5xx monitor would never see this
setInterval(async () => {
try {
await syncInventory();
} catch (err) {
logger.error({ err, job: 'inventory-sync' }, 'Inventory sync failed');
}
}, 60_000);The second example is the case from the start of this post. Nothing returns a 500, but the failure still reaches your phone.
Step 5: Test it
Create test-logger.js:
// test-logger.js
import { logger } from './logger.js';
logger.info('Only goes to stdout');
logger.error({ err: new Error('Payment API responded with 503'), orderId: 981 }, 'Payment request failed');
logger.fatal({ err: new Error('Cannot connect to database') }, 'Database unavailable');
// The same error five times: only the first one is sent to Telegram
for (let i = 0; i < 5; i++) {
logger.error({ err: new Error('Inventory API timeout'), job: 'inventory-sync' }, 'Inventory sync failed');
}
// Give the transport's worker thread a few seconds to deliver before the process exits
setTimeout(() => {}, 3000);Run it:
node test-logger.jsIn your terminal you’ll see all eight JSON log lines on stdout. In Telegram you’ll receive three messages: the payment error, the fatal database error, and the first inventory error. The four repeats are suppressed. A message looks like this:
🚨 ERROR · my-api
Payment request failed
Error: Payment API responded with 503
at chargeCustomer (file:///app/payments.js:18:11)
at file:///app/server.js:30:13
orderId: 981
web-01 · 2026-11-17T10:30:41.000ZThe stack frames appear in a monospace block in Telegram. If the same inventory error happens again after the five-minute cooldown, the next alert ends with +4 identical errors suppressed.
Gotchas and best practices
Keep your log message constant. Deduplication relies on the error type and message. If you write logger.error('Payment failed for order ' + id), every message is unique and nothing gets deduplicated. Put the variable part in a field instead: logger.error({ orderId: id }, 'Payment failed').
Reserve error for things a human must act on. If everything is an error, you’ll mute the chat within a week. Use warn for problems the app handles on its own, and you can always change the target’s level later.
Don’t rely on it right before process.exit(). The transport runs in a worker and sends alerts asynchronously, so a log written just before the process exits may never be delivered. For crash handlers, use the direct sendAlert() approach from the Telegram bot post, which awaits the request before exiting, or let the process exit on its own instead of calling process.exit().
Use a compiled JavaScript file for the transport. The worker loads the target as a separate file. If you use TypeScript or a bundler, build the transport to plain JavaScript and point target at the output.
Redact secrets. Anything you log may end up in a chat that other people can read. Use Pino’s redact option for passwords, tokens and authorization headers, and avoid logging full request bodies.
Send severity to different chats if you need to. Pino supports multiple targets, so you can add a second Telegram target with level: 'fatal' pointing at an on-call group, and keep error in a quieter chat.
Don’t make Telegram your only copy. The transport sends alerts, but stdout (or a file, or a log platform) should remain your source of truth. If Telegram is unreachable, the failure is printed to stderr and your app keeps running.
Conclusion
With one small transport file and a few lines of Pino configuration, every logger.error() call in your application becomes an instant, readable Telegram alert, covering background jobs, queue consumers and webhooks that an HTTP-based monitor can’t see. Because Pino runs the transport in a worker thread, the alerts cost your main thread almost nothing, and the cooldown and rate limit keep a bad day from becoming a flood of notifications.
Comments0
Log in to join the discussion.
No comments yet.