elastic / elastic/apm-agent-nodejs

Save built-in JSON object when agent start to allow instrumenting JSON.stringify

Open
#2,851 1 comment 0 reactions 1 assignee Claimed by @trentm View on GitHub
agent-nodejs community question
Dominant language
JavaScript
Stars
594
Forks
244
Avg merge
1d 8h
Merged PRs (30d)
16

Description

**Is your feature request related to a problem? Please describe.**

My team is experimenting with APM and one of the important things we want to instrument is our calls to `JSON.stringify`. My first try was to override the `JSON.stringify()` function like this:

```typescript
const defaultStringify = JSON.stringify;
JSON.stringify = (...args: any): any => {
const span = startSpan('stringify', 'JSON');
try {
const result = defaultStringify.apply(null, args as any);
span.end('success');
return result;
} catch (error) {
span.end('failure');
throw error;
}
};
```
However when starting the application I get a `max call stack exceeded` error.
My hypothesis is that it comes from the fact that the agent uses `JSON.stringify()` in the `getContextFromRequest()` function.

**Describe the solution you'd like**

I would like to open a PR where I would save the functions of the `JSON` object when the agent starts so that we can override the object and the agent would keep using the default function.

**Describe alternatives you've considered**

For now I'm working around this issue by creating a dedicated module which exposes an instrumented function that we use instead of the built-in `JSON.stringify`

```typescript
export const stringify = (value: any, replacer?: any, space?: number): string => {
const span = apm.startSpan('JSON.stringify', 'JSON');
try {
const result = JSON.stringify(value, replacer, space);
span.end('success');
return result;
} catch (error) {
span.end('failure');
throw error;
}
};
```

And I'm coupling that with a custom eslint rule to make sure everyone in the team uses this function and not the default one.

**Additional context**

I am willing to create the PR on my side but I first wanted to check with you if that would be an acceptable solution.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.