UNPKG

winterspec

Version:

Write Winter-CG compatible routes with filesystem routing and tons of features

39 lines (38 loc) 1.25 kB
import kleur from "kleur"; const colorStatus = (status) => { if (status >= 500) { return kleur.red(status.toString()); } if (status >= 400) { return kleur.yellow(status.toString()); } return kleur.green(status.toString()); }; export const withRequestLogging = async (req, ctx, next) => { // ENABLE COLORS ALWAYS kleur.enabled = true; if (!ctx.logger) { ctx.logger = { error: (...args) => console.error(...args), info: (...args) => console.log(...args), warn: (...args) => console.warn(...args), debug: (...args) => console.log(...args), }; } try { ctx.logger.info(kleur.blue(`> ${req.method} ${req.url}`)); const response = await next(req, ctx); try { const responseBody = await response.clone().text(); ctx.logger.info(`< ${colorStatus(response.status)} ${kleur.gray(responseBody.slice(0, 40).replace(/(\r\n|\n|\r)/gm, ""))}`); } catch (e) { ctx.logger.info(`< ${colorStatus(response.status)}`); } return response; } catch (e) { ctx.logger.info(kleur.red(`< ERROR ${e.toString().slice(0, 50)}...`)); throw e; } };