TomFrost / Bristol

Insanely configurable logging for Node.js
MIT License
113 stars 19 forks source link

Wrong origin when wrapping Bristol #29

Closed MarkHerhold closed 7 years ago

MarkHerhold commented 7 years ago

I am wrapping Bristol and applying arguments every time log() is called. This adds a line to the stack trace, which Bristol picks up and uses as the origin.

Problem

    at Logger.log (/files/logger-wrapper/index.js:17:28) <-- my wrapper
    at Logger.(anonymous function) [as debug] (/stuff/bristol/src/Bristol.js:202:20) <-- bristol logger
    at /stuff/app.js:162:12 <-- thing that actually calls the log() function

Proposal

Make _getOrigin() look for its own file name and use the line after that.

  _getOrigin() {
    Error.prepareStackTrace = arrayPrepareStackTrace
    const stack = (new Error()).stack
    let origin = null
    for (let i = 1; i < stack.length; i++) {
      const file = stack[i].getFileName()
      // find this file, 'Bristol.js', then use the next line in the stack
      if (file === __filename) {
        origin = {
          file: stack[i + 1].getFileName(),
          line: stack[i + 1].getLineNumber().toString()
        }
        break
      }
    }
    Error.prepareStackTrace = originalPrepareStackTrace
    return origin
  }

Let me know if you agree with this approach and if you want it turned into a PR. Thanks @TomFrost !

TomFrost commented 7 years ago

That sounds like a great solution! I'd absolutely approve that PR.