feat: implement update logger middleware to enhance bot API call tracking and performance measurement

This commit is contained in:
vchikalkin 2025-08-16 15:51:24 +03:00
parent c115be2e52
commit e308ba74ea
3 changed files with 37 additions and 0 deletions

View File

@ -4,6 +4,7 @@ import { type Context } from './context';
import * as features from './features'; import * as features from './features';
import { errorHandler } from './handlers/errors'; import { errorHandler } from './handlers/errors';
import { i18n } from './i18n'; import { i18n } from './i18n';
import * as middlewares from './middlewares';
import { env } from '@/config/env'; import { env } from '@/config/env';
import { logger } from '@/utils/logger'; import { logger } from '@/utils/logger';
import { getRedisInstance } from '@/utils/redis'; import { getRedisInstance } from '@/utils/redis';
@ -52,6 +53,7 @@ export function createBot({ apiRoot, token }: Parameters_) {
const protectedBot = bot.errorBoundary(errorHandler); const protectedBot = bot.errorBoundary(errorHandler);
protectedBot.use(middlewares.updateLogger());
protectedBot.use(setCommands); protectedBot.use(setCommands);
protectedBot.use(autoChatAction(bot.api)); protectedBot.use(autoChatAction(bot.api));
protectedBot.use(hydrate()); protectedBot.use(hydrate());

View File

@ -0,0 +1 @@
export * from './update-logger';

View File

@ -0,0 +1,34 @@
import { type Context } from '@/bot/context';
import { getUpdateInfo } from '@/bot/helpers/logging';
import { type Middleware } from 'grammy';
import { performance } from 'node:perf_hooks';
export function updateLogger(): Middleware<Context> {
return async (ctx, next) => {
ctx.api.config.use((previous, method, payload, signal) => {
ctx.logger.debug({
method,
msg: 'Bot API call',
payload,
});
return previous(method, payload, signal);
});
ctx.logger.debug({
msg: 'Update received',
update: getUpdateInfo(ctx),
});
const startTime = performance.now();
try {
return next();
} finally {
const endTime = performance.now();
ctx.logger.debug({
elapsed: endTime - startTime,
msg: 'Update processed',
});
}
};
}