From 208e3b9f26a94ef7eb6e221e56028a74d8e30ead Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carl-Gerhard=20Lindesva=CC=88rd?= Date: Tue, 17 Sep 2024 23:37:44 +0200 Subject: [PATCH] chore(logger): get correct error in logs --- apps/api/src/index.ts | 15 +++++++++++++++ packages/logger/index.ts | 29 ++++++++++++++++++++++++++--- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index e3ce868c..b154684d 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -83,7 +83,16 @@ const startServer = async () => { done(); }); + const ignoreLog = ['/healthcheck', '/metrics', '/misc']; + const ignoreMethods = ['OPTIONS']; + fastify.addHook('onRequest', (request, reply, done) => { + if (ignoreMethods.includes(request.method)) { + return done(); + } + if (ignoreLog.some((path) => request.url.startsWith(path))) { + return done(); + } if (request.url.includes('trpc')) { request.log.info('request incoming', { url: request.url.split('?')[0], @@ -100,6 +109,12 @@ const startServer = async () => { }); fastify.addHook('onResponse', (request, reply, done) => { + if (ignoreMethods.includes(request.method)) { + return done(); + } + if (ignoreLog.some((path) => request.url.startsWith(path))) { + return done(); + } if (request.url.includes('trpc')) { request.log.info('request done', { url: request.url.split('?')[0], diff --git a/packages/logger/index.ts b/packages/logger/index.ts index aac0481c..259db6d1 100644 --- a/packages/logger/index.ts +++ b/packages/logger/index.ts @@ -12,9 +12,32 @@ const logLevel = process.env.LOG_LEVEL ?? 'info'; export function createLogger({ name }: { name: string }): ILogger { const service = `${name}-${process.env.NODE_ENV ?? 'dev'}`; - const format = process.env.HYPERDX_API_KEY - ? winston.format.json() - : winston.format.prettyPrint(); + const prettyError = (error: Error) => ({ + ...error, + stack: error.stack, + message: error.message, + }); + + const errorFormatter = winston.format((info) => { + if (info instanceof Error) { + return { + ...info, + ...prettyError(info), + }; + } + if (info.error) { + return { + ...info, + error: prettyError(info.error), + }; + } + return info; + }); + + const format = winston.format.combine( + errorFormatter(), + winston.format.json(), + ); const transports: winston.transport[] = [new winston.transports.Console()]; if (process.env.HYPERDX_API_KEY) {