diff --git a/javascript_typescript/logging.js b/javascript_typescript/logging.js new file mode 100644 index 0000000..c1b5b05 --- /dev/null +++ b/javascript_typescript/logging.js @@ -0,0 +1,64 @@ +/** +Author: T31M +2019 +*/ + +const { createLogger, format, transports } = require("winston"); + +const { combine, timestamp, printf, colorize, splat, json } = format; + +const maxFunctionLogLength = 60; + +const myFormat = printf(({ timestamp, loc, level, message }) => { + const start = process.hrtime(); + if (loc) { + return `${timestamp} ${level}: ${message.padEnd(90)} ${loc.padEnd( + 60 + )} log: ${(process.hrtime(start)[1] / 1000000).toFixed(2)}ms`; + } + return `${timestamp} ${level}: ${message} ${( + process.hrtime(start)[1] / 1000000 + ).toFixed(2)}ms`; +}); + +const preProcessing = format((info, opts) => { + const stack = new Error().stack.split("\n"); + stack.shift(); + for (elem of Object.values(stack)) { + elem = elem.toString().trim(); + if (elem.indexOf("node_modules") < 0 && elem.indexOf("utils") < 0) { + info.loc = elem.slice(3, elem.length); + if (info.loc.length > maxFunctionLogLength) { + info.loc = `${info.loc.slice( + 0, + info.loc.indexOf(" ") + )} -> ${info.loc.slice( + info.loc.lastIndexOf("\\") + 1, + info.loc.length - 1 + )}`; + } + return info; + } + } + return info; +}); + +module.exports.logger = createLogger({ + level: "debug", + format: combine( + colorize(), + timestamp(), + // splat(), + preProcessing(), + myFormat + // json(), + ), + transports: [ + // - Write to all logs with level `info` and below to `combined.log` + // - Write all logs error (and below) to `error.log`. + // new winston.transports.File({ filename: 'error.log', level: 'error' }), + // new winston.transports.File({ filename: 'combined.log' }) + + new transports.Console({ format: format.myFormat }) + ] +}); \ No newline at end of file