profile.log{Request,Response}: pass in random request ID 📝

This commit is contained in:
Jannis R 2022-10-07 01:29:36 +02:00
parent 4189ce437b
commit 7ccffa5e51
No known key found for this signature in database
GPG key ID: 0FE83946296A88A5
3 changed files with 13 additions and 8 deletions

View file

@ -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',

View file

@ -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

View file

@ -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') {