Last active
December 2, 2024 03:18
-
-
Save jmorrell/76a9ee631370e073d6e2616dc1f67feb to your computer and use it in GitHub Desktop.
Logging
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
class Log { | |
constructor(name, attributes = new Map()) { | |
this.startTime = new Date().getTime(); | |
this.startTimestampMs = performance.now(); | |
this.name = name; | |
this.attributes = attributes; | |
} | |
setAttributes(keyValues) { | |
for (let [key, value] of Object.entries(keyValues)) { | |
this.attributes.set(key, value); | |
} | |
} | |
end() { | |
this.elapsedMs = performance.now() - this.startTimestampMs; | |
} | |
} | |
async function middleware(c, next) { | |
// create a log entry before at the beginning of the request | |
let log = new Log(`${c.req.method} ${c.req.path}`); | |
// store information about the request, the more the better | |
// this is just as an example | |
log.setAttributes({ | |
"http.request.method": c.req.method, | |
"http.request.path": c.req.path, | |
}); | |
// make this available somehow during the request to the rest | |
// of your code. For bonus points in Node use AsyncLocalStorage. | |
// Have your handlers annotate lots of things: auth, user, route | |
// feature flags. | |
c.log = log; | |
// Execute the request as normal | |
await next(); | |
// pull any more info about the response | |
log.setAttributes({ | |
"http.response.status_code": c.res.status, | |
}); | |
// end the log | |
log.end(); | |
// Turn it all to JSON and send it to an exporter function. Have it | |
// periodically send off batched data to Honeycomb's events API. If | |
// this is too much data have it send only a percentage of the logs | |
// and drop the rest. | |
exporter.export(log); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment