Skip to content

Instantly share code, notes, and snippets.

@j-f1
Last active May 7, 2017 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j-f1/5fc3718ee5a088e81aae66703b00c5e0 to your computer and use it in GitHub Desktop.
Save j-f1/5fc3718ee5a088e81aae66703b00c5e0 to your computer and use it in GitHub Desktop.
Add Bunyan source metadata at compile-time without the performance hit

AST Explorer In:

log.info('hi')
log.info(test)
app.get('test', function () { log.info({ req, res }, 'hi') })

Out:

log.info({
  src: {
    file: "unknown",
    line: 1
  }
}, 'hi')
log.info({
  src: {
    file: "unknown",
    line: 2
  }
}, test)
app.get('test', function () { log.info({
  src: {
    file: "unknown",
    line: 3
  },

  req,
  res
}, 'hi') })
export default function (babel) {
const { types: t } = babel;
return {
visitor: {
CallExpression(path) {
if (!t.isMemberExpression(path.node.callee)
|| path.node.callee.object.name !== 'log') {
return
}
if (!t.isObjectExpression(path.node.arguments[0])) {
path.node.arguments.unshift(t.objectExpression([]))
}
const file = t.objectProperty(
t.identifier('file'),
t.stringLiteral(this.file.opts.filename)
)
const line = t.objectProperty(
t.identifier('line'),
t.numericLiteral(path.node.loc.start.line)
)
path.node.arguments[0].properties.unshift(t.objectProperty(
t.identifier('src'),
t.objectExpression([
file,
line,
])
))
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment