import { randomUUID } from 'crypto' import { createLogger, format, transports } from 'winston' import { NextFunction, Request, Response } from 'express' import util from 'util' const logLevels = { fatal: 0, error: 1, warn: 2, info: 3, debug: 4, trace: 5, }; let currentUUID: string; const addReqId = format((info) => { info.reqId = currentUUID return info }) export const logger = createLogger({ format: format.combine(addReqId(), format.timestamp(), format.json()), transports: [new transports.Console({}), new transports.File({ filename: './serverLog.log' })], levels: logLevels }); export const errorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => { if (res.headersSent) { return next(err) } currentUUID = res.locals.uuid res.status(500).send({ status: 'error', message: err.message, code: res.locals.uuid }) logger.warn(err.message) } export const uuid = (req: Request, res: Response, next: NextFunction) => { res.locals.uuid = randomUUID() next(res) }