2023-03-07 10:29:05 -05:00
|
|
|
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,
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
export const logger = createLogger({
|
2023-03-07 11:20:22 -05:00
|
|
|
format: format.combine(format.timestamp(), format.json()),
|
2023-03-07 10:29:05 -05:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
|
|
|
res.status(500).send({ status: 'error', message: err.message, code: res.locals.uuid })
|
2023-03-07 11:20:22 -05:00
|
|
|
logger.warn({
|
|
|
|
message: err.message,
|
|
|
|
endpoint: req.originalUrl,
|
|
|
|
reqId: res.locals.uuid,
|
|
|
|
origin: req.headers.origin,
|
|
|
|
})
|
2023-03-07 10:29:05 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
export const uuid = (req: Request, res: Response, next: NextFunction) => {
|
|
|
|
res.locals.uuid = randomUUID()
|
2023-03-07 11:20:22 -05:00
|
|
|
next()
|
2023-03-07 10:29:05 -05:00
|
|
|
}
|