【问题标题】:How to get filename, function, line, and column from Error for EntryLog.SourceLocation如何从 EntryLog.SourceLocation 的错误中获取文件名、函数、行和列
【发布时间】:2022-02-10 19:22:53
【问题描述】:

我正在使用 winston 记录器和 EntryLog 规范进行记录,我想从 new Error().stack 获取这些数据:

{
  file: "index.js",
  function: "getData",
  line: 20,
  column: 50
}

【问题讨论】:

    标签: javascript node.js express logging winston


    【解决方案1】:

    我想通了:

    /**
     * Parses and returns info about the call stack.
     */
    function getSouceLocation(error) {
      // get call stack, and analyze it and 
      // remove unnecessary stacktrace [node_modules, <anonymous>]
      // get all file, method, and line numbers
      const stacklist = error.stack
        .replace(/^.*[\\/]node_modules[\\/].*$|^.((?!at).)*$|^.*<anonymous>.*$|^.*internal\/timers.js.*$/gm, "")
        .replace(/\n+/g, "\n").split("\n")
        .filter((item, index, array) => {
          if (!!item) {
            return index === array.indexOf(item);
          }
        });
    
      // stack trace format:
      // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
      // do not remove the regex expresses to outside of this method (due to a BUG in node.js)
      var stackReg = /at\s+(.*)\s+\((.*):(\d*):(\d*)\)/gi
      var stackReg2 = /at\s+()(.*):(\d*):(\d*)/gi
    
      const sources = []
      stacklist.forEach((item) => {
        var sp = stackReg.exec(item) || stackReg2.exec(item)
        if (sp && sp.length === 5) {
          sources.push(
            {
              function: sp[1],
              file: path.relative(PROJECT_ROOT, sp[2]),
              line: sp[3],
              column: sp[4],
            }
          )
        }
      });
      const stack = stacklist.join('\n');
      return { sources, stack };
    }
    

    结果:

    "sourceLocation": {
        "sources": [
          {
            "column": "36",
            "file": "src\\app\\controllers\\informasi\\panduan\\panduan-search.js",
            "function": "module.exports",
            "line": "11"
          },
          {
            "column": "7",
            "file": "src\\utils\\callback.js",
            "function": "",
            "line": "18"
          }
        ],
        "stack": "SequelizeDatabaseError: column a.nourutt does not exist\n    at module.exports (D:\\GOLANG\\gocode\\src\\github.com\\oss-rba\\back-portal\\src\\app\\controllers\\informasi\\panduan\\panduan-search.js:11:36)\n    at D:\\GOLANG\\gocode\\src\\github.com\\oss-rba\\back-portal\\src\\utils\\callback.js:18:7"
      },
    

    来源:winston logger with filename:linenumber

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多