Last active
June 7, 2021 00:09
-
-
Save matchu/2d7406cb7ff6e64bc24127f1ef01f017 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// HACK: Use Node's testing APIs to be able to log custom trace | |
// events. I… genuinely didn't find a better way to do | |
// local nodejs custom tracing?? | |
// | |
// To enable tracing, run this with: | |
// node --expose-internals --trace-event-categories app | |
// | |
// Without that, the require will throw an error, so the trace | |
// functions will be no-ops! | |
let trace; | |
let withTrace; | |
try { | |
const { internalBinding } = require("internal/test/binding"); | |
const rawTrace = internalBinding("trace_events").trace; | |
// `trace` lets you wrap an async block with start/end trace events! | |
// Like: `await trace("fetchThatOneWebpage", {url}, () => fetch(url))` | |
let nextTraceId = 0; | |
trace = async (eventName, traceArgs, fn) => { | |
let traceId = nextTraceId++; | |
rawTrace("b".charCodeAt(0), "app", eventName, traceId, traceArgs); | |
try { | |
return await fn(); | |
} finally { | |
rawTrace("e".charCodeAt(0), "app", eventName, traceId, traceArgs); | |
} | |
}; | |
// `withTrace` lets you wrap an async function with start/end trace | |
// events for every time you call it! First parameter is the function, | |
// second parameter is a function to transform the arguments into an | |
// object of safe, serializable arguments to log with the trace. | |
withTrace = | |
(fn, getTraceArgsFromFnArgs, name = null) => | |
(...args) => | |
trace(name || fn.name, getTraceArgsFromFnArgs(...args), () => | |
fn(...args) | |
); | |
} catch (e) { | |
trace = (_, __, fn) => fn(); | |
withTrace = (fn) => fn; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment