How do I add request body as span attributes using the instrumentation-http? #3446
-
Helloo 👋 I am trying to trace some http requests my application is sending and was wondering what is the prefered way to add the request body to the trace, I can't seem to find the http request body in any of the options functions. I can the the ClientReqest object from the requestHook function but cannot get the body from that, am I doing this wrong?
|
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 5 replies
-
Hmm I've never really thought about getting the outgoing body from a ClientRequest object. It may not be possible or easy. The request object itself doesn't save the outgoing request body and the My quick search seems to indicate it is not possible. If it is possible, requestHook is likely the right place to be hooking. It may depend on undocumented internals in order to access it if it is possible at all. We do not intercept the body at all so I don't think there is any place we would be interfering with normal operation there. |
Beta Was this translation helpful? Give feedback.
-
@Ankcorn I was looking to something similar. Tried quite a lot by adding listeners to data, end events in responseHook but it did not work. Eventually managed to do it by patching the send method of response object from express in the otel/instrumentation-express package. |
Beta Was this translation helpful? Give feedback.
-
I've managed to get the request body by using the new HttpInstrumentation({
requestHook: (span, request: ClientRequest) => {
const requestBodyChunks = [];
const oldWrite = request.write.bind(request);
request.write = (data: any) => {
requestBodyChunks.push(decodeURIComponent(data.toString()));
return oldWrite(data);
};
const oldEnd = request.end.bind(request);
request.end = (data: any) => {
if (data) {
requestBodyChunks.push(decodeURIComponent(data.toString()));
}
console.log('request body:', requestBodyChunks.join());
return oldEnd(data);
};
},
}) |
Beta Was this translation helpful? Give feedback.
-
The solution here no longer works - I can't attach the data to the span because the span is no longer active, I will take a look to see if we can find another way It's been a good run. Thanks @eliasfeijo |
Beta Was this translation helpful? Give feedback.
I've managed to get the request body by using the
requestHook
and overwriting thewrite
andend
request methods: