Advertisement
tringuyen25

logger.js

Dec 10th, 2020
849
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const winston = require("winston");
  2. const path = require("path");
  3. const rootDir = path.join(__dirname, "../../..");
  4. const colorize = require("winston/lib/winston/config").colorize;
  5. const TSFORMAT = () => (new Date().toISOString());
  6.  
  7. const transports = process.env.NODE_ENV !== "production"
  8.     ? [new winston.transports.Console({
  9.         level: "debug",
  10.         handleExceptions: true,
  11.         humanReadableUnhandledException: true,
  12.         json: false,
  13.         prettyPrint: true,
  14.         timestamp: TSFORMAT,
  15.         colorize: "all",
  16.         formatter: (data) => {
  17.             let finalResult = "";
  18.             finalResult += `[${data.timestamp()} - ${data.level.toUpperCase()}]: ${data.message}`;
  19.             if (data.meta && Object.keys(data.meta).length) {
  20.                 finalResult += data.meta.message + "\n";
  21.                 finalResult += data.meta.stack;
  22.             }
  23.             if (data.level !== "info") {
  24.                 return colorize(data.level, finalResult);
  25.             } else {
  26.                 return finalResult;
  27.             }
  28.         }
  29.     })]
  30.     : [
  31.         new winston.transports.File({
  32.             name: "error",
  33.             level: "error",
  34.             filename: "./logs/error-level.txt",
  35.             handleExceptions: true,
  36.             json: false,
  37.             maxsize: 5242880, //5MB
  38.             maxFiles: 50,
  39.             timestamp: TSFORMAT,
  40.             prettyPrint: true,
  41.             colorize: "all",
  42.             formatter: (data) => {
  43.                 let finalResult = "";
  44.                 finalResult += `[${data.timestamp()} - ${data.level.toUpperCase()}]: ${data.message}`;
  45.                 if (data.meta && Object.keys(data.meta).length) {
  46.                     finalResult += data.meta.message + "\n";
  47.                     finalResult += data.meta.stack;
  48.                 }
  49.                 if (data.level !== "info") {
  50.                     return colorize(data.level, finalResult);
  51.                 } else {
  52.                     return finalResult;
  53.                 }
  54.             }
  55.         }),
  56.         new winston.transports.File({
  57.             name: "debug",
  58.             level: "debug",
  59.             filename: "./logs/debug-level.txt",
  60.             handleExceptions: true,
  61.             json: false,
  62.             maxsize: 5242880, //5MB
  63.             maxFiles: 100,
  64.             timestamp: TSFORMAT,
  65.             prettyPrint: true,
  66.             colorize: "all",
  67.             formatter: (data) => {
  68.                 let finalResult = "";
  69.                 finalResult += `[${data.timestamp()} - ${data.level.toUpperCase()}]: ${data.message}`;
  70.                 if (data.meta && Object.keys(data.meta).length) {
  71.                     finalResult += data.meta.message + "\n";
  72.                     finalResult += data.meta.stack;
  73.                 }
  74.                 if (data.level !== "info") {
  75.                     return colorize(data.level, finalResult);
  76.                 } else {
  77.                     return finalResult;
  78.                 }
  79.             }
  80.         })
  81.     ];
  82. winston.addColors({
  83.     "debug": "green",
  84. });
  85. const logger = new winston.Logger({
  86.     transports: transports,
  87.     exitOnError: false
  88. });
  89.  
  90. const formatLogArg = (args) => {
  91.     args = Array.prototype.slice.call(args);
  92.     const stackInfo = getStackInfo(1);
  93.     if (stackInfo) {
  94.         const callee = `[${stackInfo.relativePath}:${stackInfo.line}]`;
  95.         if (typeof (args[0]) === "string") {
  96.             args[0] = `${callee} ${args[0]}`;
  97.         } else {
  98.             args.unshift(callee);
  99.         }
  100.     }
  101.     //Pushing an empty meta object this it's considered a meta
  102.     args.push({});
  103.     return args;
  104. };
  105.  
  106. const getStackInfo = (stackIndex) => {
  107.     // get call stack, and analyze it
  108.     // get all file, method, and line numbers
  109.     const stackList = (new Error()).stack.split("\n").slice(3);
  110.  
  111.     // stack trace format:
  112.     // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
  113.     // do not remove the regex expresses to outside of this method (due to a BUG in node.js)
  114.     const stackReg = /at\s+(.*)\s+\((.*):(\d*):(\d*)\)/gi;
  115.     const stackReg2 = /at\s+()(.*):(\d*):(\d*)/gi;
  116.     const s = stackList[stackIndex] || stackList[0];
  117.     const sp = stackReg.exec(s) || stackReg2.exec(s);
  118.  
  119.     if (sp && sp.length === 5) {
  120.         return {
  121.             method: sp[1],
  122.             relativePath: path.relative(rootDir, sp[2]),
  123.             line: sp[3],
  124.             pos: sp[4],
  125.             file: path.basename(sp[2]),
  126.             stack: stackList.join("\n")
  127.         };
  128.     }
  129. };
  130.  
  131. module.exports.stream = {
  132.     write: (message) => {
  133.         logger.info(message);
  134.     }
  135. };
  136. module.exports.debug = module.exports.log = function() {
  137.     logger.debug.apply(logger, formatLogArg(arguments));
  138. };
  139. module.exports.info = function() {
  140.     logger.info.apply(logger, formatLogArg(arguments));
  141. };
  142. module.exports.warn = function() {
  143.     logger.warn.apply(logger, formatLogArg(arguments));
  144. };
  145. module.exports.error = function() {
  146.     logger.error.apply(logger, formatLogArg(arguments));
  147. };
  148. module.exports.verbose = function() {
  149.     logger.verbose.apply(logger, formatLogArg(arguments));
  150. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement