diff --git a/docs/readme.md b/docs/readme.md index e498dadc..b57d6ea5 100644 --- a/docs/readme.md +++ b/docs/readme.md @@ -86,11 +86,15 @@ As an example, we can implement a custom logger: const createClient = require('hafas-client') const dbProfile = require('hafas-client/p/db') -const logRequest = (ctx, fetchRequest) => { +const logRequest = (ctx, fetchRequest, requestId) => { // ctx looks just like with the other profile.* hooks: const {profile, opt} = ctx - console.debug(fetchRequest.headers, fetchRequest.body + '') + console.debug(requestId, fetchRequest.headers, fetchRequest.body + '') +} + +const logResponse = (ctx, fetchResponse, body, requestId) => { + console.debug(requestId, fetchResponse.headers, body + '') } // create a client with Deutsche Bahn profile that debug-logs @@ -103,7 +107,7 @@ const client = createClient({ ```js // logRequest output: -{ +'29d0e3' { accept: 'application/json', 'accept-encoding': 'gzip, br, deflate', 'content-type': 'application/json', @@ -111,7 +115,7 @@ const client = createClient({ 'user-agent': 'hafas842c51-clie842c51nt debug C842c51LI' } {"lang":"de","svcReqL":[{"cfg":{"polyEnc":"GPA"},"meth":"LocMatch",… // logResponse output: -{ +'29d0e3' { 'content-encoding': 'gzip', 'content-length': '1010', 'content-type': 'application/json; charset=utf-8', diff --git a/lib/default-profile.js b/lib/default-profile.js index 973545cd..f4cd7406 100644 --- a/lib/default-profile.js +++ b/lib/default-profile.js @@ -49,10 +49,10 @@ const filters = require('../format/filters') const DEBUG = /(^|,)hafas-client(,|$)/.test(process.env.DEBUG || '') const logRequest = DEBUG - ? (_, req) => console.error(req.body + '') + ? (_, req, reqId) => console.error(req.body + '') : () => {} const logResponse = DEBUG - ? (_, res, body) => console.error(body) + ? (_, res, body, reqId) => console.error(body) : () => {} const id = (ctx, x) => x diff --git a/lib/request.js b/lib/request.js index edc8203b..5faf6293 100644 --- a/lib/request.js +++ b/lib/request.js @@ -123,9 +123,10 @@ const request = (ctx, userAgent, reqData) => { } } + const reqId = randomBytes(3).toString('hex') const url = profile.endpoint + '?' + stringify(req.query) const fetchReq = new Request(url, req) - profile.logRequest(ctx, fetchReq) + profile.logRequest(ctx, fetchReq, reqId) // Async stack traces are not supported everywhere yet, so we create our own. const err = new Error() @@ -154,7 +155,7 @@ const request = (ctx, userAgent, reqData) => { return res.text() .then((body) => { - profile.logResponse(ctx, res, body) + profile.logResponse(ctx, res, body, reqId) const b = JSON.parse(body) if (b.err && b.err !== 'OK') {