UNPKG

@lexamica-modules/logger

Version:

The various loggers and transports used for API logging in the Lexamica Eco-system

76 lines (69 loc) 2.12 kB
import winston from 'winston'; // have to use any here since morgan does not make its types available export function requestFormatter(tokens: any, req: any, res: any) { return JSON.stringify({ method: tokens.method(req, res), url: tokens.url(req, res), status_code: Number.parseFloat(tokens.status(req, res)), content_length: tokens.res(req, res, 'content-length'), response_time: Number.parseFloat(tokens['response-time'](req, res)), }); } function logFormatTemplate(line: { level: string; message: string; timestamp?: string; label?: string; metadata?: { timestamp?: string; label?: string; }; [key: string]: unknown; }): string { const { timestamp = new Date().toISOString(), label = 'logger', ...meta } = line.metadata || line || {}; const metaEmpty = Object.keys(meta).length === 0 && meta.constructor === Object; const metaString = metaEmpty ? '' : JSON.stringify(meta, null, 2); return `${timestamp} [${label}] ${line.level}: ${line.message} ${metaString}`; } const jsonToString = winston.format((entry) => { const { message } = entry || {}; if (message instanceof Map || message instanceof Set) { entry.message = `Map/Set keys: ${[...message.keys()].join(',')}`; return entry; } else if (typeof message === 'object') { entry.message = JSON.stringify(message); return entry; } return entry; }); const colorFormat = winston.format.combine( jsonToString(), winston.format.timestamp(), winston.format.colorize(), winston.format.splat(), winston.format.simple(), winston.format.metadata(), winston.format.printf(logFormatTemplate) ); const jsonFormat = winston.format.combine( jsonToString(), winston.format.timestamp(), winston.format.splat(), winston.format.simple(), winston.format.metadata(), winston.format.json() ); export const getFormat = (formatType: 'color' | 'json') => { switch (formatType) { case 'color': return colorFormat; case 'json': default: return jsonFormat; } };