Last active
November 28, 2022 20:25
-
-
Save faceslog/05c833fea23b9982cdee88428e5019b8 to your computer and use it in GitHub Desktop.
Nodejs Middleware to Log HTTP API-Requests when working with an API without any doc :kappa:
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
const http = require("http"); | |
const server = http.createServer((request, response) => { | |
const requestStart = Date.now(); | |
let errorMessage = null; | |
let body = []; | |
request.on("data", chunk => { | |
body.push(chunk); | |
}); | |
request.on("end", () => { | |
body = Buffer.concat(body); | |
body = body.toString(); | |
}); | |
request.on("error", error => { | |
errorMessage = error.message; | |
}); | |
response.on("finish", () => { | |
const { rawHeaders, httpVersion, method, socket, url } = request; | |
const { remoteAddress, remoteFamily } = socket; | |
console.log( | |
JSON.stringify({ | |
timestamp: Date.now(), | |
processingTime: Date.now() - requestStart, | |
rawHeaders, | |
body, | |
errorMessage, | |
httpVersion, | |
method, | |
remoteAddress, | |
remoteFamily, | |
url | |
}) | |
); | |
}); | |
process(request, response); | |
}); | |
const process = (request, response) => { | |
setTimeout(() => { | |
response.end(); | |
}, 100); | |
}; | |
server.listen(8888); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment