programing

Node.js에서 스택 트레이스를 인쇄하는 방법

goodjava 2022. 12. 30. 17:05

Node.js에서 스택 트레이스를 인쇄하는 방법

Node.js에서 스택 트레이스를 인쇄하는 방법을 아는 사람이 있습니까?

조금도Error오브젝트에는 다음이 있습니다.stack구성원을 트랩합니다.

var stack = new Error().stack
console.log( stack )

또는 더 간단하게:

console.trace("Here I am!")

이를 위한 전용 기능이 콘솔에 있습니다.

console.trace()

이미 응답한 바와 같이 trace 명령어를 사용할 수 있습니다.

console.trace("I am here");

, 예외의 스택트레이스를 기록하는 방법을 검색한 경우에는 예외 오브젝트를 로그에 기록하기만 하면 됩니다.

try {  
  // if something unexpected
  throw new Error("Something unexpected has occurred.");     

} catch (e) {
  console.error(e);
}

로그에 기록됩니다.

오류: 예기치 않은 문제가 발생했습니다.
메인 (c:\Users\Me\Documents\MyApp\js:9:15)
오브젝트에 있습니다.(c:\Users\Me\Documents\MyApp.js:17:1)
모듈로 이동합니다._filename (802.180:460:26)
오브젝트에 있습니다.Module._확장..js (802.124:478:10)
Module.load (module.js:355:32)
기능하고 있습니다.Module._load (module.js:310:12)
기능하고 있습니다.Module.runMain (module.js:501:10)
기동 시(node.disc:disc:16)
at node.disc:814:3


Node.js 버전이 6.0.0보다 작을 경우 Exception 개체를 로깅하는 것만으로는 충분하지 않습니다.이 경우는, 다음의 인쇄만 실시합니다.

[오류: 예기치 않은 일이 발생했습니다]

노드 버전< 6 의 경우는, 다음과 같이 입력합니다.console.error(e.stack)대신console.error(e)현재 노드 버전과 마찬가지로 오류 메시지와 전체 스택을 출력합니다.


주의: 예외가 다음과 같은 문자열로 생성된 경우throw "myException", 스택 트레이스와 로깅을 취득할 수 없습니다.e.stack수율이 정의되지 않았습니다.

안전을 위해 다음을 사용할 수 있습니다.

console.error(e.stack || e);

오래된 Node.js 버전과 새로운 Node.js 버전에서도 동작합니다.

스택 트레이스를 인쇄하려면Error보다 읽기 쉬운 방법으로 콘솔에 표시:

console.log(ex, ex.stack.split("\n"));

결과 예:

[Error] [ 'Error',
  '    at repl:1:7',
  '    at REPLServer.self.eval (repl.js:110:21)',
  '    at Interface.<anonymous> (repl.js:239:12)',
  '    at Interface.EventEmitter.emit (events.js:95:17)',
  '    at Interface._onLine (readline.js:202:10)',
  '    at Interface._line (readline.js:531:8)',
  '    at Interface._ttyWrite (readline.js:760:14)',
  '    at ReadStream.onkeypress (readline.js:99:10)',
  '    at ReadStream.EventEmitter.emit (events.js:98:17)',
  '    at emitKey (readline.js:1095:12)' ]

@syslogs의 답변은 맞지만 보다 구체적이고 명확한 오류 스택이 필요한 경우 다음 기능을 사용할 수 있습니다.

function getCleanerStack() {
   var err = new Error();
   Error.captureStackTrace(err, getCleanerStack);
    
   return err.stack;
}

이 함수는 다음에서 직접 영감을 얻습니다.console.traceNodeJS에서 기능합니다.

소스 코드:최신 버전 또는 이전 버전.

v15.12.0에서는 이를 위한 다양한 방법이 있습니다.

1. console.trace(anything)
2. Error.captureStackTrace(Object)
3. console.log(new Error().stack)
4. Try Catch - Use console.log(e), where `e` is catched by catch block

또는 Javascript 코드에서 stacktracejs를 사용하는 것이 좋습니다.

Error.captureStackTrace(targetObject[, constructorOpt])를 시험합니다.

const myObj = {};
function c() {
  // pass
}

function b() {
    Error.captureStackTrace(myObj)
    c()
} 

function a() {
    b()
}

a()

console.log(myObj.stack)

함수a그리고.b에러 스택에 캡처되어 저장됩니다.myObj.

완전한 스택 트레이스를 nodejs로 인쇄하는 것은 불가능하며, "부분" 스택 트레이스를 인쇄하기만 하면 됩니다.코드에서 어디에서 예외가 발생했는지 알 수 없습니다.그게 바로 라이언 달이 이 유튜브 비디오에서 설명한 것이다.http://youtu.be/jo_B4LTHi3I (정확하게는 56:30분)를 참조해 주세요.도움이 되었으면 좋겠다

만약 누군가가 여전히 나처럼 이것을 찾고 있다면, 우리가 사용할 수 있는 "스택 트레이스"라는 모듈이 있습니다.정말 인기가 많아요.NPM 링크

그럼 흔적을 따라 걸어봐

  var stackTrace = require('stack-trace');
  .
  .
  .
  var trace = stackTrace.get();
  trace.map(function (item){ 
    console.log(new Date().toUTCString() + ' : ' +  item.toString() );  
  });

또는 트레이스를 인쇄하기만 하면 됩니다.

var stackTrace = require('stack-trace');
.
.
.
var trace = stackTrace.get();
trace.toString();

함수 호출자 세부 정보 가져오기:

/**
 * @typedef {Object} TCallerInfo
 * @property {() => string} toString
 * @property {string} str Caller error stack line.
 * @property {string} file Caller file path.
 * @property {number} line Caller line.
 * @property {number} col Caller column.
 * @property {Error} error Caller error stack instance.
 */

/**
 * @returns {TCallerInfo | null}
 */
function getCallerLine() {
  const err = new Error();
  const stack = err.stack || '';
  const callerLine = stack.split(/\n\s*at\s+/g);

  if (callerLine.length >= 2) {
    const str = callerLine[3];
    const [file, line, col] = str
      .replace(/^\s*at\s+/, '')
      .replace(/^(.*):(\d+):(\d+)$/, '$1|$2|$3')
      .split(/\|/g);

    const o = {
      toString: () => str,

      get str() {
        return str;
      },

      get file() {
        return file;
      },

      get line() {
        return parseInt(line);
      },

      get col() {
        return parseInt(col);
      },

      get error() {
        return err;
      },
    };

    return o;
  } else {
    return null;
  }
}

사용방법:

function foo() {
  console.info(getCallerLine());
}

foo(); // Prints this line as Caller Line details.

오류의 스택트레이스만 기록할 경우(에러 메시지는 기록하지 않음) 노드6 이후로는 스택트레이스 내에 에러명과 메시지가 자동으로 포함되어 커스텀에러 처리를 실행하는 것이 귀찮습니다.

console.log(error.stack.replace(error.message, ''))

이 회피책에서는 에러명과 스택트레이스만을 로그에 기록합니다(예를 들어 에러 메시지를 포맷하여 코드의 다른 장소에 표시할 수 있습니다).

위의 예에서는 스택트레이스 뒤에 에러명만 출력됩니다.다음은 예를 제시하겠습니다.

Error: 
    at /Users/cfisher/Git/squashed/execProcess.js:6:17
    at ChildProcess.exithandler (child_process.js:213:5)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Socket.<anonymous> (internal/child_process.js:334:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at Pipe._handle.close [as _onclose] (net.js:498:12)

대신:

Error: Error: Command failed: sh ./commands/getBranchCommitCount.sh HEAD
git: 'rev-lists' is not a git command. See 'git --help'.

Did you mean this?
        rev-list

    at /Users/cfisher/Git/squashed/execProcess.js:6:17
    at ChildProcess.exithandler (child_process.js:213:5)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Socket.<anonymous> (internal/child_process.js:334:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at Pipe._handle.close [as _onclose] (net.js:498:12)

node-stack-module은 파워풀모듈로 콜스택을 추적할 수 있습니다.

언급URL : https://stackoverflow.com/questions/2923858/how-to-print-a-stack-trace-in-node-js