We are going to design a component telemetry system that collects and reports:
- Render cost: the time (in milliseconds) taken to render the component.
- Usage context: information about where and how the component is used (e.g., parent component, props, user interaction).
- Defect density: the number of defects (bugs) per unit of code (e.g., per 1000 lines of code) or per component instance.
We assume we are in a React-like environment (since we are talking about components), but the principles can be adapted.
Steps:
-
Render Cost Measurement:
- We can use React's built-in Profiler or a similar mechanism to measure the time taken to render.
- We'll create a Higher-Order Component (HOC) or a wrapper that uses the Profiler API to measure the render time of the wrapped component.
-
Usage Context:
- We can capture the component's props and state (or a subset) and also the parent component's name.
- We might also want to capture user interactions that led to the render (e.g., which event triggered the update).
-
Defect Density:
- This is more of a metric that is computed over time and across the codebase. We might not be able to compute it in real-time for a single component instance.
- However, we can track errors (exceptions) that occur in the component and then relate that to the number of component instances or the amount of code.
-
Reporting:
- We need to send this telemetry to a backend service. We can batch the reports to avoid sending too many requests.
-
Privacy and Performance:
- We must be cautious about the amount of data we collect and send. We should avoid collecting PII.
- The telemetry system itself should not add significant overhead.
Implementation Plan:
We'll create:
- A
TelemetryContext to hold configuration (like whether telemetry is enabled, the endpoint, etc.)
- A
withTelemetry HOC that wraps components and collects the three metrics.
However, note that measuring render cost with React Profiler requires wrapping the component tree. We can use the Profiler component from React.
Alternatively, we can create a custom hook that uses the Profiler and also collects context and defects.
Let's break it down:
Render Cost:
We can use the Profiler component to measure the render time of a component. The Profiler allows us to define a callback that will be called with the id, phase, and actualDuration (time spent rendering the committed update).
Usage Context:
We can collect:
- The component's display name (or name)
- The parent's display name (if available)
- A snapshot of the props (we should avoid sending large objects or sensitive data)
- Maybe a hash of the props to track variations.
Defect Density:
We can track:
- The number of errors (caught by an error boundary) that occur in the component.
- The number of times the component is mounted (or rendered) to compute a ratio.
However, note that defect density is usually defined as defects per lines of code. We can approximate by:
- Total errors in the component / total renders (or total unique users, etc.)
But we might not have the lines of code at runtime. We can precompute the lines of code for each component and send that as a static metric.
Steps for the HOC:
- We'll create a HOC that wraps the component and uses the Profiler to measure render time.
- We'll also attach an error boundary to catch errors and count them.
- We'll collect the context (parent name, props) in the Profiler callback.
However, note that the Profiler callback is called on every render (commit phase). We might not want to send a report for every render. We can batch and send periodically or when certain conditions are met.
Let's design a batched reporter:
- We'll have an in-memory queue of reports.
- We'll send the reports in batches (e.g., every 5 minutes or when the queue reaches 50 reports).
But note: we want to track per component instance? Or per component type?
We are measuring at the component type level (because we are wrapping a component). But the usage context might vary per instance (props).
We can aggregate by component type and by a hash of the props (or by a subset of props) to see which prop combinations cause issues.
However, that could lead to a lot of different reports. We might want to only track a sample of renders (e.g., 1% of renders) to reduce overhead.
Alternatively, we can send the telemetry for every render but with a low priority (using navigator.sendBeacon or background fetch) and hope it doesn't block.
But we must be cautious: if the component renders very frequently, we could flood the network.
Let's consider:
- We'll send the telemetry only for a sample of renders (configurable, e.g., 1%).
- We'll also send error reports immediately (because errors are critical).
Implementation:
We'll create:
class TelemetryReporter {
constructor(config) {
this.config = config;
this.queue = [];
this.sampleRate = config.sampleRate || 0.01; // 1% by default
this.endpoint = config.endpoint;
}
report(componentName, renderTime, context, defectCount) {
// We'll decide whether to report based on sampleRate
if (Math.random() < this.sampleRate) {
this.queue.push({
componentName,
renderTime,
context,
defectCount,
timestamp: Date.now()
});
this.flushIfNeeded();
}
}
flushIfNeeded() {
if (this.queue.length >= this.config.batchSize ||
(this.lastFlush && Date.now() - this.lastFlush > this.config.flushInterval)) {
this.flush();
}
}
flush() {
if (this.queue.length === 0) return;
const data = this.queue.splice(0);
// Send to endpoint
navigator.sendBeacon(this.endpoint, JSON.stringify(data));
this.lastFlush = Date.now();
}
}
But note: we are in a React component, so we might not have navigator in server-side. We should check for that.
Alternatively, we can use a more robust batching mechanism that works in both client and server.
However, telemetry is usually client-side. We assume we are in the browser.
Now, the HOC:
function withTelemetry(WrappedComponent, telemetryReporter) {
return function(props) {
const [renderCount, setRenderCount] = useState(0);
const errorCountRef = useRef(0);
const parentName = useComponentContext(); // We need a way to get the parent's display name.
// We'll use the Profiler
const onRender = useCallback((id, phase, actualDuration) => {
// We are only interested in the "commit" phase for the actual render time.
if (phase === 'commit') {
const context = {
parent: parentName,
props: props, // We should filter sensitive props? We don't have a way to know which are sensitive.
renderCount: renderCount
};
telemetryReporter.report(WrappedComponent.displayName || WrappedComponent.name, actualDuration, context, errorCountRef.current);
}
}, [parentName, props, renderCount, telemetryReporter]);
// We'll reset the error count after reporting? Or keep accumulating until the next report?
// We are reporting the current error count (which is the total errors in this instance so far) but then we might report the same error multiple times.
// Alternatively, we can report the error count at the time of the render and then reset? But then we lose the history.
// For defects, we might want to report the total errors that occurred in this component instance (across renders) and then reset the count for the next batch?
// But note: the same error might occur in multiple renders. We are counting the number of error events, not unique errors.
// We'll do: on each render, we report the current error count (which is the number of errors since the last report) and then reset the error count.
// How do we track errors? We can use an error boundary.
const onError = useCallback((error, errorInfo) => {
errorCountRef.current += 1;
// We might want to report the error immediately? But we are already counting it and will report in the next render.
// Alternatively, we can have a separate immediate report for errors.
}, []);
// We'll create an error boundary class component
class ErrorBoundary extends React.Component {
componentDidCatch(error, errorInfo) {
onError(error, errorInfo);
}
render() {
return this.props.children;
}
}
// We'll increment renderCount on every render
useEffect(() => {
setRenderCount(prev => prev + 1);
});
return (
<Profiler id={WrappedComponent.displayName || WrappedComponent.name} onRender={onRender}>
<ErrorBoundary>
<WrappedComponent {...props} />
</ErrorBoundary>
</Profiler>
);
}
}
However, the above has a problem: the onRender callback is called after the component has rendered, but we are using renderCount which is updated asynchronously in an effect. So the renderCount in the onRender might be off by one.
We can use a ref for renderCount and update it in the onRender? But then we are updating state in the onRender which might cause a re-render.
Alternatively, we can use the useLayoutEffect to update the renderCount before the Profiler reports? But the Profiler's onRender is called after the commit, so after layout effects.
Let's restructure:
const renderCountRef = useRef(0);
renderCountRef.current += 1;
Then in onRender, we can use renderCountRef.current.
But note: the onRender is called after the render, so the renderCountRef.current will be the current render's count.
However, we are also using the same renderCount in the context. We can use the ref for the context too.
Alternatively, we can compute the context without relying on state that updates asynchronously.
We can change:
const onRender = useCallback((id, phase, actualDuration) => {
if (phase === 'commit') {
const context = {
parent: parentName,
props: props,
renderCount: renderCountRef.current
};
telemetryReporter.report(WrappedComponent.displayName || WrappedComponent.name, actualDuration, context, errorCountRef.current);
// Reset error count after reporting? We want to report the errors that occurred during this render cycle?
// But note: the error boundary catches errors during rendering, and we are reporting after the render. So the errors that occurred in this render are already counted.
// We reset the error count so that the next report only includes new errors.
errorCountRef.current = 0;
}
}, [parentName, props, telemetryReporter]);
But wait: the errorCountRef.current might include errors from previous renders that we haven't reported? We are resetting after every render. That means we are reporting the errors that occurred in the current render (since the last report) and then resetting.
However, the Profiler's onRender is called after every commit (which includes the initial render and updates). So we are reporting on every render (but sampled) and resetting the error count each time.
This seems okay.
But note: if we have multiple errors in one render, we count them and then reset. So the defectCount in the report is the number of errors in that render.
Alternatively, we might want to track the total errors over the lifetime of the component? Then we wouldn't reset.
Let's think: defect density is usually over the entire life of the component. But we are also sampling renders. We are reporting the error count per render (if we reset) and then the receiver can aggregate.
We can do either:
Option 1: Report the cumulative error count (so we don't reset) and then the receiver can compute the delta between reports? But we are sampling, so we might not get every render.
Option 2: Report the errors that occurred in the current render (and reset). Then we are reporting the number of errors per render (sampled). The receiver can average over samples.
Since we are sampling, we are only getting a fraction of renders. So we want each report to be independent.
I think Option 2 is better: each report is for one render (sampled) and we report the number of errors in that render.
But note: if an error occurs, it might break the component and prevent further renders. So we might not get a report for the next render.
We are using an error boundary, so the component will still render (the error boundary catches and displays a fallback). So we will get a render after the error (with the error boundary showing). But the error is counted in the render that threw.
So we are counting the error in the render that threw, and then the next render (with the error boundary) will not throw, so no error.
This is acceptable.
However, we are resetting the error count after every render, so if we have multiple errors in the same render (unlikely because the first error would break the render) but possible if multiple components throw? Actually, the error boundary catches errors in its children. So if multiple children throw, we might get multiple errors? But the error boundary's componentDidCatch is called once with the first error? Actually, in React, if multiple errors occur, React will report the first one and then ignore the rest? Not sure.
We might want to use a global error handler for uncaught errors? But we are using an error boundary for this component.
Let's stick with the error boundary and reset after each render.
Now, the parentName:
We need a way to get the parent's display name. We can use a context that provides the parent's display name.
We'll create a ComponentContext that provides the current component's display name to its children.
We'll wrap the entire app with a TelemetryProvider that sets the initial context (maybe the root component name) and then each wrapped component will update the context for its children.
But note: we are wrapping the component with withTelemetry, so we can set the context in the wrapper.
Alternatively, we can use React's useContext to get the parent's name from a context that is set by the parent.
We can do:
const ComponentContext = React.createContext(null);
In the HOC:
const parentName = useContext(ComponentContext);
Then we set the context for the children:
return (
<ComponentContext.Provider value={WrappedComponent.displayName || WrappedComponent.name}>
... the Profiler and ErrorBoundary and WrappedComponent ...
</ComponentContext.Provider>
)
But note: the parentName we are capturing is the parent of the wrapped component, which is set by the parent's context. So we are getting the parent's display name from the context that the parent set.
However, the parent might not be wrapped with our HOC. We can set the context only if the parent is using our system? We can set the context in our HOC, so only components wrapped with our HOC will have the context set.
This means that if a component is not wrapped, its children won't have the parentName? Then we can set the context in the HOC only.
But what about the root? We can set the root component name in the TelemetryProvider.
We'll assume that the entire app is wrapped in a TelemetryProvider that sets the initial context (maybe the root component name).
Alternatively, we can set the context in the HOC without a provider at the root? Then the root component's children won't have a parentName? We can set the parentName to 'root' for the root component.
Let's change:
In the HOC, we set the context value to the current component's name. Then the parentName for the children will be this component's name.
But we want the parentName of the current component. So we are getting the parentName from the context set by the parent HOC.
So the root component will have parentName = null (or whatever the initial context value is). We can set the initial context to 'root' or an empty string.
We'll let the user set the initial context value in the TelemetryProvider.
Now, the props:
We are sending the entire props object. We must be cautious because props might contain large objects or sensitive data.
We can let the user specify a way to sanitize the props. We can pass a getPropsSnapshot function in the config that returns a safe representation of the props.
We'll change the HOC to accept an optional getPropsSnapshot prop (or via the telemetryReporter config).
We'll adjust the context to use the snapshot:
const context = {
parent: parentName,
props: getPropsSnapshot ? getPropsSnapshot(props) : props,
renderCount: renderCountRef.current
};
Similarly, we might want to avoid sending the entire component name? But the component name is usually small.
Now, the defectCount: we are resetting the errorCountRef to 0 after reporting. But we are reporting the errorCountRef.current (which is the number of errors in this render) and then resetting.
But note: the errorCountRef.current might have been incremented by the error boundary during the render. We are reporting after the render, so we have the count for this render.
We reset so that the next report only includes new errors.
However, if we sample out (i.e., we don't report this render because of sampling) then we reset the error count and lose that error? That's a problem.
We should only reset the error count if we actually report? Or we should not reset and report the cumulative errors? But then we would double count errors if we report multiple times for the same error.
Let's think: an error occurs in a render. We increment the errorCountRef. Then we report (if sampled) and then reset. But if we don't report (because of sampling) we don't reset, so the error count carries over to the next render.
Then in the next render (if sampled) we report the total errors so far (which includes the previous error) and then reset.
But note: the same error might occur again in a later render? Then we would count it again.
We are counting the number of error events, not unique errors. So if the same error occurs twice, we count two.
That might be acceptable: we want to know how many times errors occur.
But if we don't report the first time (because of sampling) and then reset after the second report, we lose the first error? Actually, no:
Render 1: error occurs -> errorCount=1, not reported (sampled out) -> errorCount=1
Render 2: no error -> errorCount=1, reported (sampled in) -> we report 1, then reset to 0.
So we reported one error, but it occurred in render 1. That's okay because we are sampling and we don't know when the error occurred exactly? But we are reporting in render 2 that there was 1 error (that occurred since the last report). But the last report was never sent? We reset the errorCount only when we report.
We reset after reporting, so the errorCount becomes 0 after render 2.
But what if the error in render 1 was the only error and then we never get another error? We would never report it if we skip render 1 and then reset in render 2? Actually, we reset in render 2 because we reported. But we reported the error that occurred in render 1 (because it was still in the count). So we reported it, but in the context of render 2.
This might be acceptable because we are sampling and we don't have perfect information.
Alternatively, we can report errors immediately (when they occur) and then also track them in the render? But that would be two reports for the same error.
We can change the error boundary to report the error immediately (with a different type of report) and not count it in the render report? But then we lose the context of which render caused the error.
We want to know the context (props, parent) of the render that caused the error. So we should report the error in the same context as the render.
Therefore, we should not reset the error count until we have reported it (and we are reporting the error count that includes errors from previous unreported renders).
But note: if we have multiple errors in multiple renders and we sample out for a long time, the error count will grow and then when we finally sample in, we report a large number. That might be acceptable.
We can change the reset to happen only when we report? But we are already doing that: we reset after reporting.
However, we are reporting the current errorCount (which includes all errors since the last reset) and then reset. So we are effectively reporting the number of errors that occurred in the interval (since the last report). This is good.
But if we never report (because sampleRate is 0) then we never reset and the errorCount will keep growing? That's a problem.
We can have a maximum error count? Or we can reset after a certain time? But we are not reporting so we don't care? Actually, we do care because we are holding a number that might become very large.
We can reset the errorCount if it exceeds a threshold (like 1000) and we haven't reported? But then we lose counts.
Alternatively, we can report immediately when an error occurs (bypassing the sample) because errors are critical. We can have a separate high-priority channel for errors.
Let's do:
We'll have two types of reports:
- Render reports (with render time and context) that are sampled.
- Error reports that are sent immediately (and also counted in the render reports?).
But we don't want to double count. We can:
- In the error boundary, we send an immediate error report (with the error info and the current context) and also increment the errorCountRef so that the next render report (if sampled) will include this error.
But then we are reporting the same error twice? We can avoid by not including the error in the render report if we already reported it immediately? But we don't know if the immediate report was sent? We don't have a way to mark an error as reported.
Alternatively, we can only report errors in the render reports (sampled) and not have immediate error reports. But then critical errors might be missed if we sample out.
We can set the sampleRate for error reports to 1 (always) and for normal renders to the configured sample rate.
We can adjust the telemetryReporter to have two methods: reportRender and reportError. And in the HOC, we call reportError immediately when an error occurs, and then in the onRender we call reportRender (which is sampled).
But then the same error might be reported in both? Because the error occurs in a render, and then the onRender is called. We can avoid by not counting the error in the render report if we already reported it? But we don't have a way to know which errors have been reported.
We can change the error boundary to set a flag that the error has been reported? But if the same error occurs again in a different render, we want to report again.
Alternatively, we can change the errorCountRef to be an object that maps error messages to a count? Then we can report the count of each error? That's more complex.
Given the complexity, and since we are already sampling, we might accept that some errors are missed (if the render that caused them is not sampled) but we are also sending immediate error reports? Let's not do immediate error reports.
We'll stick with:
- Errors are counted in the errorCountRef.
- In the onRender, if sampled, we report the current errorCount (which includes all errors since the last report) and then reset.
This way, we are guaranteed to eventually report an error (unless the component stops rendering after an error? But the error boundary will cause a re-render with the fallback, so we will get a render after the error).
But if the component unmounts after an error (because of a redirect or something) then we might not get a render to report the error? We can use a cleanup in the error boundary to report the error if the component unmounts? But we don't have the context in the error boundary.
We can store the error count in a ref that is not reset until the component unmounts? But then we might never report if the component unmounts without another render.
We can change the error boundary to report immediately when an error occurs (without sampling) and then also increment the errorCountRef so that the next render (if any) will include it? But then we are reporting twice.
Alternatively, we can have a separate error reporting mechanism that doesn't rely on the onRender. We can send the error immediately (with context) and then also increment a counter for the render report? But then we are double counting.
We can decide that error reports are separate and don't affect the render report's defectCount. Then the defectCount in the render report is only for errors that occurred during that render and were caught by the error boundary? But note: the error boundary catches errors during rendering, so we are already counting them in the errorCountRef.
Let's keep it simple:
We are going to report errors only via the render reports (sampled). We accept that we might miss some errors if the component unmounts after an error and before the next render (which might not happen because the error boundary causes a re-render). Also, if the component is removed from the tree (unmounts) after an error, we might not get a render? Actually, the error boundary will still be in the tree and will render the fallback. So we will get a render.
So we are safe.
Now, let's code the HOC with:
- A ref for errorCount.
- A ref for renderCount (or we can use state for renderCount? We don't need to trigger a re-render, so ref is fine).
- We'll use the Profiler and ErrorBoundary.
But note: the Profiler's onRender is called after the component has committed. At that point, we can read the errorCountRef (which was set by the error boundary during the render).
We'll do:
const errorCountRef = useRef(0);
const renderCountRef = useRef(0);
const onError = useCallback((error, errorInfo) => {
errorCountRef.current += 1;
}, []);
const onRender = useCallback((id, phase, actualDuration) => {
if (phase === 'commit') {
renderCountRef.current += 1;
const context = {
parent: parentName,
props: getPropsSnapshot ? getPropsSnapshot(props) : props,
renderCount: renderCountRef.current
};
telemetryReporter.reportRender(
WrappedComponent.displayName || WrappedComponent.name,
actualDuration,
context,
errorCountRef.current
);
// Reset error count after reporting
errorCountRef.current = 0;
}
}, [parentName, props, getPropsSnapshot, telemetryReporter]);
But wait: we are incrementing renderCountRef in the onRender? Then the renderCount in the context will be the current render's count.
However, the onRender is called after the render, so the renderCountRef.current is the number of renders so far (including this one). That's what we want.
But note: the initial render will have renderCount=1.
Now, the ErrorBoundary:
We'll create a class component that uses the onError callback.
We have to be cautious: the ErrorBoundary will catch errors in its children (the WrappedComponent). But what about errors in the WrappedComponent's children? They will be caught by the ErrorBoundary of the WrappedComponent? If the WrappedComponent has its own error boundary, then the error might be caught there and not reach our ErrorBoundary.
We want to catch errors in the entire subtree of the WrappedComponent? We can only catch errors in the WrappedComponent and its children if we are the closest error boundary.
We are wrapping the WrappedComponent with our ErrorBoundary, so we will catch errors in the WrappedComponent and its children (unless they have their own error boundary that catches and handles the error).
That's acceptable: we want to track errors that are not caught by a closer error boundary.
Now, the TelemetryReporter:
We'll design it to batch reports and send them.
We'll have:
class TelemetryReporter {
constructor(config) {
this.config = {
endpoint: '/telemetry',
sampleRate: 0.01,
batchSize: 50,
flushInterval: 300000, // 5 minutes
...config
};
this.queue = [];
this.lastFlush = 0;
}
reportRender(componentName, renderTime, context, defectCount) {
if (Math.random() < this.config.sampleRate) {
this.queue.push({
type: 'render',
componentName,
renderTime,
context,
defectCount,
timestamp: Date.now()
});
this.flushIfNeeded();
}
}
flushIfNeeded() {
if (this.queue.length >= this.config.batchSize ||
(this.lastFlush && Date.now() - this.lastFlush > this.config.flushInterval)) {
this.flush();
}
}
flush() {
if (this.queue.length === 0) return;
const data = this.queue.splice(0);
if (typeof navigator !== 'undefined' && navigator.sendBeacon) {
navigator.sendBeacon(this.config.endpoint, JSON.stringify(data));
} else {
// Fallback to fetch
fetch(this.config.endpoint, {
method: 'POST',
body: JSON.stringify(data),
keepalive: true
}).catch(() => { /* ignore */ });
}
this.lastFlush = Date.now();
}
}
We can also add a reportError method that is not sampled? But we decided not to.
Now, we need a way to provide the telemetryReporter to the HOC. We can use React context for the telemetryReporter.
We'll create a TelemetryContext that provides the reporter.
Then in the HOC, we can get the reporter from the context.
But note: the HOC is used to wrap components, and we might have multiple reporters? We'll have one reporter per app.
We'll create:
const TelemetryContext = React.createContext(null);
const TelemetryProvider = ({ children, config }) => {
const reporter = useMemo(() => new TelemetryReporter(config), [config]);
return (
<TelemetryContext.Provider value={reporter}>
{children}
</TelemetryContext.Provider>
);
};
Then in the HOC:
const telemetryReporter = useContext(TelemetryContext);
if (!telemetryReporter) {
// We can warn or just return the component without telemetry.
return <WrappedComponent {...props} />;
}
Now, the parentName:
We are using a separate context for the parentName? We can use the same TelemetryContext for the reporter and the parentName? Or we can have two contexts.
We'll create a ComponentContext for the parentName.
const ComponentContext = React.createContext(null);
Then in the HOC, we set:
return (
<ComponentContext.Provider value={WrappedComponent.displayName || WrappedComponent.name}>
<Profiler ...>
<ErrorBoundary ...>
<WrappedComponent {...props} />
</ComponentContext.Provider>
);
And the parentName is from useContext(ComponentContext).
But note: the parentName will be the name of the parent component that is wrapped with our HOC. If the parent is not wrapped, then the parentName will be whatever the parent set in the ComponentContext? We are setting the context only in our HOC. So if the parent is not wrapped, then the context will be the value set by the grandparent that is wrapped? Or the initial value.
We want the parentName to be the immediate parent's name, even if the parent is not wrapped? We can't get that without wrapping the parent.
So we are only tracking the parent if the parent is also wrapped with our HOC.
That's acceptable: we are building a system for our own components that we wrap.
Now, we have to be cautious: the HOC might be used multiple times on the same component? We can handle that by using the displayName of the wrapped component (which might be the HOC's name). We can set the displayName of the wrapper to include the wrapped component's name.
We can do:
const withTelemetry = (WrappedComponent, options) => {
const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component';
function Wrapper(props) {
// ... our implementation ...
}
Wrapper.displayName = withTelemetry(${wrappedComponentName});
return Wrapper;
};
But then the Profiler id and the context value we set will be the wrapper's displayName? We want the original component's name? We can use the original component's displayName.
In the Profiler id, we are using WrappedComponent.displayName. That's the original component.
But in the context we set for children, we are setting the wrapper's displayName? Actually, we are setting the wrapper's displayName (which is withTelemetry(Original)). That might be confusing.
We can set the context value to the original component's name? But then the child will see the parent as the original component, but the parent is actually the wrapper.
We want the parentName to be the component that is wrapping the current component? That is the wrapper. But the wrapper is not a business component.
Alternatively, we can set the context to the original component's name? Then the hierarchy will be of the original components, ignoring the HOC wrappers.
We can do:
const parentName = useContext(ComponentContext); // This is the parent's original component name (if the parent is wrapped) or null.
Then we set the context for our children to the original component's name (WrappedComponent.displayName).
So the context value is the original component's name.
But note: if we wrap a component multiple times, the inner wrapper will set the context to the original component's name? Then the outer wrapper will see the inner wrapper's context? The inner wrapper sets the context to the original component's name, so the outer wrapper will see that as the parent's original component name? That might be what we want.
Example:
OriginalComponent -> wrapped withTelemetry (Wrapper1) -> wrapped withTelemetry (Wrapper2)
Wrapper2's parentName (from context) will be the context set by Wrapper1? Wrapper1 sets the context to OriginalComponent. So Wrapper2 will see OriginalComponent as parent.
Then Wrapper2 sets the context to OriginalComponent (again) for its children.
That's acceptable.
But if we want to know the wrapper chain? We don't.
So we are tracking the original component hierarchy.
Now, we have to be cautious about the getPropsSnapshot function. We don't want to send the entire props if they are large. We can let the user define a function that returns a safe representation.
We can pass an option to the HOC:
withTelemetry(WrappedComponent, { getPropsSnapshot })
Then in the HOC, we use that.
We'll adjust the HOC to accept an options object.
Now, let's write the code:
We'll create:
- TelemetryContext (for the reporter)
- ComponentContext (for the parentName)
- TelemetryProvider
- withTelemetry HOC
We'll also create a hook for using the telemetry reporter without the HOC? Maybe not needed.
Let's code accordingly.
However, note: the HOC will wrap the component with two context providers (ComponentContext) and the Profiler and ErrorBoundary. We must be cautious about the React tree.
We'll also make sure that the HOC does not break the component's displayName and ref forwarding.
We'll forward refs:
const withTelemetry = (WrappedComponent, options) => {
const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component';
const Wrapper = React.forwardRef((props, ref) => {
// ... same as before, but pass the ref to WrappedComponent.
});
Wrapper.displayName = withTelemetry(${wrappedComponentName});
return Wrapper;
};
But note: the Profiler and ErrorBoundary might interfere with ref? We should forward the ref to the WrappedComponent.
We'll do:
const Wrapper = React.forwardRef((props, ref) => {
// ... same as before, but in the return:
return (
<ComponentContext.Provider value={wrappedComponentName}>
<WrappedComponent {...props} ref={ref} />
</ComponentContext.Provider>
);
});
Now, we have to handle the fact that the WrappedComponent might not accept a ref? We are forwarding the ref, so if the WrappedComponent is a function component, we must use React.forwardRef in the WrappedComponent? Or we can use a cloneElement? But we are using forwardRef in our wrapper, so the WrappedComponent must be able to accept a ref.
If the WrappedComponent is a function component and does not use forwardRef, then the ref will be null. That's acceptable.
Now, let's put it all together.
We'll create a file telemetry.js:
We'll define:
- ComponentContext
- TelemetryContext
- TelemetryReporter class
- TelemetryProvider
- withTelemetry
We'll also export the contexts for advanced use.
We must be cautious: the telemetry system should be optional. We don't want to add overhead if the user doesn't want telemetry.
We can conditionally create the reporter and wrap the components only if the config is provided.
But the HOC will always wrap the component. We can make the HOC a no-op if there's no reporter? We can check the context.
We'll do:
const withTelemetry = (WrappedComponent, options) => {
const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component';
const Wrapper = React.forwardRef((props, ref) => {
const telemetryReporter = useContext(TelemetryContext);
const parentName = useContext(ComponentContext);
// If there's no telemetryReporter, we don't do any telemetry.
if (!telemetryReporter) {
return <WrappedComponent {...props} ref={ref} />;
}
// ... rest of the implementation ...
});
Wrapper.displayName = `withTelemetry(${wrappedComponentName})`;
return Wrapper;
};
Now, we have to handle the options for getPropsSnapshot.
We'll pass the options to the HOC and use them in the onRender.
We'll adjust:
const { getPropsSnapshot } = options || {};
And then in onRender:
const context = {
parent: parentName,
props: getPropsSnapshot ? getPropsSnapshot(props) : props,
renderCount: renderCountRef.current
};
But note: the props might change between renders. We are capturing the props of the current render.
We are also capturing the parentName (which is the parent's original component name) and the renderCount.
Now, the errorCountRef: we are resetting after reporting. But what if we don't report (because of sampling)? Then we don't reset and the errorCount accumulates until the next report.
That's acceptable.
We must also consider that the component might be used in a server environment (SSR). We should not try to use navigator or sendBeacon on the server.
We can check for typeof navigator !== 'undefined' in the TelemetryReporter.flush.
Also, we don't want to run telemetry in SSR? We can conditionally create the TelemetryReporter only on the client.
We can have a flag in the config: enabled (default true) and then in the TelemetryProvider, we can create the reporter only if enabled and if we are in the browser.
But the HOC will still wrap the component and set up the Profiler and ErrorBoundary, which might have performance implications in SSR.
We can conditionally wrap only on the client? We can check typeof window !== 'undefined' in the HOC? But then the server and client would have different component trees? That might break React's hydration.
We want the same component tree on server and client. So we should wrap in both, but the telemetryReporter might be null on the server (because we don't create it on the server). Then the HOC will be a no-op on the server.
We can do:
In the TelemetryProvider, we only create the reporter if enabled and if we are in the browser.
But the provider itself can be used on the server and client. We can pass a config that has enabled: false for the server.
Alternatively, we can have the TelemetryProvider conditionally set the reporter context value:
const TelemetryProvider = ({ children, config }) => {
const [reporter, setReporter] = useState(null);
useEffect(() => {
if (config && config.enabled !== false && typeof window !== 'undefined') {
setReporter(new TelemetryReporter(config));
}
}, [config]);
return (
<TelemetryContext.Provider value={reporter}>
{children}
</TelemetryContext.Provider>
);
};
Then on the server, reporter is null, so the HOC becomes a no-op.
But note: the first render on the client will have reporter=null (because useEffect runs after mount) and then the HOC will not wrap? But we want the same tree on server and client. We want the HOC to wrap on both, but on the client we want to enable telemetry.
We can create the reporter during render? But that would create a new reporter on every render. We can use useMemo with empty deps? But the config might change.
We can do:
const TelemetryProvider = ({ children, config }) => {
const reporter = useMemo(() => {
if (config && config.enabled !== false && typeof window !== 'undefined') {
return new TelemetryReporter(config);
}
return null;
}, [config]);
return (
<TelemetryContext.Provider value={reporter}>
{children}
</TelemetryContext.Provider>
);
};
But note: window is not available during SSR. We can check for typeof window !== 'undefined' in the useMemo? That will throw during SSR? Actually, in SSR, window is not defined, but we are in a useMemo which runs during render. So we must check for typeof window !== 'undefined' only on the client.
We can do:
const reporter = useMemo(() => {
if (typeof window === 'undefined') {
return null;
}
if (config && config.enabled !== false) {
return new TelemetryReporter(config);
}
return null;
}, [config]);
This way, on the server, we return null. On the client, we create the reporter.
But note: the config might change, and we want to recreate the reporter? We can decide to not change the reporter after mount. We can use an empty dependency array? But then the config is fixed at the first render.
We can let the user change the config and we recreate the reporter? That might be acceptable.
Now, the HOC will get the reporter from context. On the server, it's null, so it returns the component without telemetry. On the client, it's the reporter.
This will cause a mismatch between server and client? The server rendered without the telemetry wrapper (because the provider gave null) and the client will render with the telemetry wrapper? Actually, the provider on the server will also run the useMemo and return null. So the server will also have null. Then the HOC will be a no-op on both. Then on the client, after the provider runs, the reporter is created and the HOC will wrap? But the HOC is already wrapped in the tree. We are conditionally wrapping inside the HOC based on the reporter being null or not.
The tree structure will be the same: the HOC will be in the tree on both server and client, but on the server it will return the component without the Profiler and ErrorBoundary, and on the client it will return with the Profiler and ErrorBoundary? That will break hydration because the server rendered without the Profiler and ErrorBoundary and the client expects them.
We need the same tree on server and client. Therefore, we must conditionally include the Profiler and ErrorBoundary only on the client? But then the server and client trees differ.
We can do:
In the HOC, we always include the Profiler and ErrorBoundary? But then on the server, we are including them and the reporter is null, so we are not reporting, but we are wrapping. That's acceptable because the Profiler and ErrorBoundary don't affect the rendered output? The Profiler doesn't render anything, and the ErrorBoundary renders its children or the fallback. We are not changing the rendered output, so server and client will match.
But the ErrorBoundary might catch errors on the server? That's okay, we just ignore because we don't have a reporter.
So we change the HOC to:
const Wrapper = React.forwardRef((props, ref) => {
const telemetryReporter = useContext(TelemetryContext);
const parentName = useContext(ComponentContext);
// We'll set up the refs and callbacks regardless of the reporter, but only call the reporter if it exists.
// ... same as before, but in onRender and onError, we check if telemetryReporter exists.
const onRender = useCallback((id, phase, actualDuration) => {
if (phase === 'commit' && telemetryReporter) {
// ... report
}
}, [parentName, props, getPropsSnapshot, telemetryReporter]);
const onError = useCallback((error, errorInfo) => {
if (telemetryReporter) {
errorCountRef.current += 1;
}
}, [telemetryReporter]);
return (
<ComponentContext.Provider value={wrappedComponentName}>
<Profiler id={wrappedComponentName} onRender={onRender}>
<ErrorBoundary onError={onError}>
<WrappedComponent {...props} ref={ref} />
</ErrorBoundary>
</Profiler>
</ComponentContext.Provider>
);
});
But note: the ErrorBoundary will catch errors even if telemetryReporter is null? We are incrementing the errorCountRef only if telemetryReporter exists. But the ErrorBoundary will still catch and prevent the error from crashing the app. That's acceptable.
However, we are setting the ComponentContext provider even if there's no telemetryReporter? That's okay because we want the parentName for children that might have telemetry.
So the tree structure is the same on server and client: we always wrap with ComponentContext, Profiler, and ErrorBoundary. The only difference is whether we report or not.
This should be safe for SSR.
Now, we have to handle the case where the WrappedComponent is already an error boundary? Then our ErrorBoundary will catch errors that the WrappedComponent's error boundary might catch? We are wrapping the WrappedComponent, so if the WrappedComponent has an error boundary, it will catch errors in its children, and then our ErrorBoundary will catch errors in the WrappedComponent itself? Actually, the ErrorBoundary we are adding will catch errors in the WrappedComponent and its children (unless the WrappedComponent has an error boundary that catches first). So we might be double wrapping? That's okay, but we might catch the same error twice? We are catching in our ErrorBoundary only if the error propagates up. If the WrappedComponent has an error boundary that catches the error, then our ErrorBoundary won't see it.
That's acceptable: we only want to track errors that are not caught by a closer error boundary.
Now, we must also consider that the Profiler will measure the time of the WrappedComponent and its children (including the ErrorBoundary and the children of the ErrorBoundary). But note: the ErrorBoundary might render a fallback, so the render time will include that.
That's acceptable because we are measuring the entire subtree.
Now, let's write the code.
We'll create the file:
telemetry.js:
We'll use React and ReactDOM (for the Profiler? Actually, Profiler is in React).
We'll assume React version that has Profiler.
Code:
We'll create the contexts, the TelemetryReporter class, the TelemetryProvider, and the withTelemetry HOC.
We'll also export the contexts for manual use if needed.
Let's code accordingly.
Note: We are using React.forwardRef and React.useCallback, etc.
We'll also provide a way to disable telemetry for specific components? We can do that by not wrapping them.
Now, we must also consider that the telemetryReporter might be changed (if the config changes) and we want to use the latest reporter. We are using the reporter from context, so if the provider changes the reporter, the HOC will use the new one.
But we are using useCallback with telemetryReporter in the deps, so the callbacks will update.
However, the errorCountRef and renderCountRef are per component instance, so they are not reset when the reporter changes. That's acceptable.
Let's code.
We'll also add a way to manually report from the component (without the HOC) by using a hook.
We can create:
const useTelemetry = () => {
const reporter = useContext(TelemetryContext);
return {
reportRender: (componentName, renderTime, context, defectCount) => {
if (reporter) {
reporter.reportRender(componentName, renderTime, context, defectCount);
}
},
// maybe reportError? But we don't have that.
};
};
But we don't need that for now.
Let's write the code.
We'll also add a way to set the parentName manually? We are using the context, so if a component is not wrapped with our HOC, it won't set the context. We can provide a hook to set the parentName? But the parentName is set by the HOC.
We'll leave it as is.
Now, the complete code:
Note: We are using React 18? The Profiler is available.
We'll write the code in a way that works with React 16.9+ (when Profiler was introduced).
Let's code.
I'll design a comprehensive component telemetry system that monitors three key metrics: Render Cost, Usage Context, and Defect Density. Here's a production-ready implementation:
Architecture Overview
// types/telemetry.ts
export interface RenderMetrics {
componentName: string;
renderDurationMs: number;
commitDurationMs: number;
interactionCount: number;
timestamp: number;
buildId?: string;
}
export interface UsageContext {
componentName: string;
parentComponent: string;
propsSnapshot: Record<string, any>;
route?: string;
userId?: string;
sessionId: string;
featureFlags: string[];
deviceInfo: {
platform: string;
screenSize: string;
connectionType?: string;
};
viewport: {
width: number;
height: number;
};
}
export interface DefectMetrics {
componentName: string;
errorCount: number;
errorTypes: string[];
stackTraces: string[];
severity: 'low' | 'medium' | 'high' | 'critical';
lastOccurrence: number;
totalInstances: number;
defectDensity: number; // errors per 1000 renders
}
export interface TelemetryReport {
sessionId: string;
batchId: string;
metrics: {
renders: RenderMetrics[];
defects: DefectMetrics[];
usage: UsageContext[];
};
metadata: {
appVersion: string;
environment: 'development' | 'staging' | 'production';
bundleSize: number;
};
}
1. Render Cost Monitor
// utils/renderMonitor.tsx
import { Profiler, ProfilerOnRenderCallback } from 'react';
import { performance } from 'perf_hooks';
class RenderMonitor {
private static instance: RenderMonitor;
private renderTimes: Map<string, number[]> = new Map();
private commitTimes: Map<string, number[]> = new Map();
private interactionCounts: Map<string, number> = new Map();
private constructor() {}
static getInstance(): RenderMonitor {
if (!RenderMonitor.instance) {
RenderMonitor.instance = new RenderMonitor();
}
return RenderMonitor.instance;
}
createProfilerCallback(
componentName: string,
onMetricsUpdate?: (metrics: RenderMetrics) => void
): ProfilerOnRenderCallback {
return (id, phase, actualDuration, baseDuration, startTime, commitTime) => {
if (phase === 'mount' || phase === 'update') {
const renderTime = actualDuration;
const commitTimeMs = commitTime ? performance.now() - commitTime : 0;
// Store metrics
this.recordRender(componentName, renderTime, commitTimeMs);
// Track interactions if this is an update
if (phase === 'update') {
const interactions = this.interactionCounts.get(componentName) || 0;
this.interactionCounts.set(componentName, interactions + 1);
}
const metrics: RenderMetrics = {
componentName,
renderDurationMs: renderTime,
commitDurationMs: commitTimeMs,
interactionCount: this.interactionCounts.get(componentName) || 0,
timestamp: Date.now(),
};
onMetricsUpdate?.(metrics);
}
};
}
private recordRender(componentName: string, renderTime: number, commitTime: number) {
// Keep last 100 renders for rolling average
const renders = this.renderTimes.get(componentName) || [];
renders.push(renderTime);
if (renders.length > 100) renders.shift();
this.renderTimes.set(componentName, renders);
const commits = this.commitTimes.get(componentName) || [];
commits.push(commitTime);
if (commits.length > 100) commits.shift();
this.commitTimes.set(componentName, commits);
}
getAverageRenderTime(componentName: string): number {
const renders = this.renderTimes.get(componentName) || [];
return renders.length ? renders.reduce((a, b) => a + b, 0) / renders.length : 0;
}
getAverageCommitTime(componentName: string): number {
const commits = this.commitTimes.get(componentName) || [];
return commits.length ? commits.reduce((a, b) => a + b, 0) / commits.length : 0;
}
resetMetrics(componentName?: string) {
if (componentName) {
this.renderTimes.delete(componentName);
this.commitTimes.delete(componentName);
this.interactionCounts.delete(componentName);
} else {
this.renderTimes.clear();
this.commitTimes.clear();
this.interactionCounts.clear();
}
}
}
export const renderMonitor = RenderMonitor.getInstance();
// HOC for automatic monitoring
export function withRenderMonitoring<P extends object>(
WrappedComponent: React.ComponentType<P>,
componentName?: string
) {
const displayName = componentName || WrappedComponent.displayName || WrappedComponent.name || 'Anonymous';
return React.forwardRef<any, P>((props, ref) => {
const [metricsHistory, setMetricsHistory] = React.useState<RenderMetrics[]>([]);
const onRender = React.useCallback(
renderMonitor.createProfilerCallback(displayName, (metrics) => {
setMetricsHistory(prev => [...prev.slice(-9), metrics]); // Keep last 10
}),
[displayName]
);
return (
<Profiler id={displayName} onRender={onRender}>
<WrappedComponent {...props} ref={ref} />
</Profiler>
);
});
}
2. Usage Context Collector
// utils/contextCollector.ts
import { useLocation, useParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
class UsageContextCollector {
private static instance: UsageContextCollector;
private usageData: Map<string, UsageContext[]> = new Map();
private sessionId: string;
private userId?: string;
private constructor() {
this.sessionId = this.generateSessionId();
}
static getInstance(): UsageContextCollector {
if (!UsageContextCollector.instance) {
UsageContextCollector.instance = new UsageContextCollector();
}
return UsageContextCollector.instance;
}
setUserId(userId: string) {
this.userId = userId;
}
generateSessionId(): string {
return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}
getSessionId(): string {
return this.sessionId;
}
captureContext(
componentName: string,
parentComponent: string,
props: Record<string, any>,
extra?: Partial<UsageContext>
): UsageContext {
const context: UsageContext = {
componentName,
parentComponent,
propsSnapshot: this.sanitizeProps(props),
sessionId: this.sessionId,
featureFlags: this.getFeatureFlags(),
deviceInfo: this.getDeviceInfo(),
viewport: this.getViewport(),
...extra,
};
if (this.userId) context.userId = this.userId;
// Store for analysis
const existing = this.usageData.get(componentName) || [];
existing.push(context);
// Keep last 1000 contexts per component
if (existing.length > 1000) existing.shift();
this.usageData.set(componentName, existing);
return context;
}
private sanitizeProps(props: Record<string, any>): Record<string, any> {
const sanitized: Record<string, any> = {};
const sensitiveKeys = ['password', 'token', 'secret', 'key', 'auth'];
Object.entries(props).forEach(([key, value]) => {
if (sensitiveKeys.some(sk => key.toLowerCase().includes(sk))) {
sanitized[key] = '***REDACTED***';
} else if (typeof value === 'object' && value !== null) {
sanitized[key] = this.sanitizeProps(value as Record<string, any>);
} else {
sanitized[key] = value;
}
});
return sanitized;
}
private getFeatureFlags(): string[] {
// Integrate with your feature flag system
return process.env.FEATURE_FLAGS?.split(',') || [];
}
private getDeviceInfo() {
return {
platform: navigator.platform,
screenSize: `${window.screen.width}x${window.screen.height}`,
connectionType: (navigator as any).connection?.effectiveType,
};
}
private getViewport() {
return {
width: window.innerWidth,
height: window.innerHeight,
};
}
getUsageStats(componentName?: string): UsageContext[] {
if (componentName) {
return this.usageData.get(componentName) || [];
}
return Array.from(this.usageData.values()).flat();
}
clearData() {
this.usageData.clear();
this.sessionId = this.generateSessionId();
}
}
export const usageCollector = UsageContextCollector.getInstance();
// React hook for component usage
export function useComponentUsage(componentName: string, parentComponent: string) {
const location = useLocation();
const params = useParams();
const query = useQuery(); // If using TanStack Query
const props = React.useRef<any>({}); // Will be populated by wrapper
React.useEffect(() => {
const context = usageCollector.captureContext(componentName, parentComponent, props.current, {
route: location.pathname,
});
// Send to telemetry service (debounced)
debouncedSendUsage(context);
}, [location.pathname, componentName, parentComponent]);
// Helper to capture props
const captureProps = (newProps: any) => {
props.current = newProps;
};
return { captureProps };
}
3. Defect Density Calculator
// utils/defectTracker.ts
interface ErrorRecord {
error: Error;
componentName: string;
timestamp: number;
stack?: string;
userId?: string;
context?: UsageContext;
}
class DefectTracker {
private static instance: DefectTracker;
private errors: Map<string, ErrorRecord[]> = new Map();
private componentRenderCounts: Map<string, number> = new Map();
private errorRateWindow: Map<string, number[]> = new Map(); // For rolling error rate
private constructor() {}
static getInstance(): DefectTracker {
if (!DefectTracker.instance) {
DefectTracker.instance = new DefectTracker();
}
return DefectTracker.instance;
}
recordRender(componentName: string) {
const count = this.componentRenderCounts.get(componentName) || 0;
this.componentRenderCounts.set(componentName, count + 1);
}
recordError(
error: Error,
componentName: string,
context?: UsageContext,
userId?: string
) {
const record: ErrorRecord = {
error,
componentName,
timestamp: Date.now(),
stack: error.stack,
userId,
context,
};
const errors = this.errors.get(componentName) || [];
errors.push(record);
// Keep last 100 errors per component
if (errors.length > 100) errors.shift();
this.errors.set(componentName, errors);
// Update error rate window (last 1000 renders)
const rates = this.errorRateWindow.get(componentName) || [];
rates.push(1);
if (rates.length > 1000) rates.shift();
this.errorRateWindow.set(componentName, rates);
}
getDefectMetrics(componentName: string): DefectMetrics {
const errors = this.errors.get(componentName) || [];
const renderCount = this.componentRenderCounts.get(componentName) || 1;
// Group errors by type
const errorCounts = new Map<string, number>();
const errorTypes: string[] = [];
const stacks: string[] = [];
errors.forEach(err => {
const type = err.error.constructor.name;
if (!errorCounts.has(type)) {
errorCounts.set(type, 0);
errorTypes.push(type);
}
errorCounts.set(type, (errorCounts.get(type) || 0) + 1);
if (err.stack && !stacks.includes(err.stack)) {
stacks.push(err.stack);
}
});
// Calculate defect density (errors per 1000 renders)
const defectDensity = (errors.length / renderCount) * 1000;
// Determine severity based on density and frequency
let severity: DefectMetrics['severity'] = 'low';
if (defectDensity > 10) severity = 'critical';
else if (defectDensity > 5) severity = 'high';
else if (defectDensity > 2) severity = 'medium';
// Check recent error rate (last 1000 renders)
const recentRates = this.errorRateWindow.get(componentName) || [];
const recentErrorCount = recentRates.filter(r => r === 1).length;
const recentErrorRate = (recentErrorCount / recentRates.length) * 100;
// Increase severity if recent error rate is high
if (recentErrorRate > 5 && severity !== 'critical') {
severity = 'high';
}
return {
componentName,
errorCount: errors.length,
errorTypes,
stackTraces: stacks,
severity,
lastOccurrence: errors.length ? errors[errors.length - 1].timestamp : 0,
totalInstances: renderCount,
defectDensity,
};
}
getAllDefectMetrics(): DefectMetrics[] {
return Array.from(this.componentRenderCounts.keys()).map(componentName =>
this.getDefectMetrics(componentName)
);
}
getCriticalDefects(): DefectMetrics[] {
return this.getAllDefectMetrics().filter(m =>
m.severity === 'critical' || m.severity === 'high'
);
}
clearComponentData(componentName: string) {
this.errors.delete(componentName);
this.componentRenderCounts.delete(componentName);
this.errorRateWindow.delete(componentName);
}
}
export const defectTracker = DefectTracker.getInstance();
// Error boundary for capturing component errors
export class TelemetryErrorBoundary extends React.Component<
{ children: React.ReactNode; componentName: string },
{ hasError: boolean }
> {
constructor(props: any) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
defectTracker.recordError(
error,
this.props.componentName,
undefined, // context would be captured separately
usageCollector.getSessionId()
);
// Also send immediate error report
sendImmediateErrorReport({
componentName: this.props.componentName,
error: error.message,
stack: error.stack,
errorInfo: errorInfo.componentStack,
timestamp: Date.now(),
sessionId: usageCollector.getSessionId(),
});
}
render() {
if (this.state.hasError) {
return (
<div className="telemetry-error-fallback">
<h3>Component Error</h3>
<p>Something went wrong. The issue has been reported.</p>
</div>
);
}
return this.props.children;
}
}
4. Telemetry Service & Reporting
// services/telemetryService.ts
import { TelemetryReport, RenderMetrics, DefectMetrics, UsageContext } from '../types/telemetry';
class TelemetryService {
private static instance: TelemetryService;
private batchQueue: TelemetryReport[] = [];
private batchSize = 50;
private flushInterval = 30000; // 30 seconds
private lastFlush = 0;
private isEnabled = true;
private endpoint: string;
private constructor() {
this.endpoint = process.env.TELEMETRY_ENDPOINT || '/api/telemetry';
this.setupAutoFlush();
this.setupVisibilityChange();
}
static getInstance(): TelemetryService {
if (!TelemetryService.instance) {
TelemetryService.instance = new TelemetryService();
}
return TelemetryService.instance;
}
private setupAutoFlush() {
setInterval(() => this.flush(), this.flushInterval);
}
private setupVisibilityChange() {
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
this.flush();
}
});
}
enable() {
this.isEnabled = true;
}
disable() {
this.isEnabled = false;
this.flush(); // Send any pending data
}
async reportRender(metrics: RenderMetrics) {
if (!this.isEnabled) return;
const report = this.getOrCreateBatch();
report.metrics.renders.push(metrics);
defectTracker.recordRender(metrics.componentName);
this.maybeFlush();
}
async reportUsage(context: UsageContext) {
if (!this.isEnabled) return;
const report = this.getOrCreateBatch();
report.metrics.usage.push(context);
this.maybeFlush();
}
async reportDefects(defects: DefectMetrics[]) {
if (!this.isEnabled) return;
const report = this.getOrCreateBatch();
report.metrics.defects.push(...defects);
this.maybeFlush();
}
private getOrCreateBatch(): TelemetryReport {
const now = Date.now();
const batchId = `batch_${now}_${Math.random().toString(36).substr(2, 9)}`;
const existingBatch = this.batchQueue.find(b =>
now - b.metadata.timestamp < this.flushInterval
);
if (existingBatch) {
return existingBatch;
}
const newBatch: TelemetryReport = {
sessionId: usageCollector.getSessionId(),
batchId,
metrics: { renders: [], defects: [], usage: [] },
metadata: {
appVersion: process.env.APP_VERSION || '1.0.0',
environment: this.getEnvironment(),
bundleSize: this.getBundleSize(),
timestamp: now,
},
};
this.batchQueue.push(newBatch);
return newBatch;
}
private maybeFlush() {
const now = Date.now();
const lastBatch = this.batchQueue[this.batchQueue.length - 1];
if (
lastBatch &&
(lastBatch.metrics.renders.length >= this.batchSize ||
lastBatch.metrics.defects.length >= 10 ||
now - this.lastFlush > this.flushInterval)
) {
this.flush();
}
}
private async flush() {
if (this.batchQueue.length === 0) return;
const batches = this.batchQueue.splice(0);
this.lastFlush = Date.now();
try {
// Use sendBeacon for reliability on page unload
if (navigator.sendBeacon) {
const data = JSON.stringify(batches);
const blob = new Blob([data], { type: 'application/json' });
navigator.sendBeacon(this.endpoint, blob);
} else {
// Fallback to fetch with keepalive
await fetch(this.endpoint, {
method: 'POST',
body: JSON.stringify(batches),
headers: { 'Content-Type': 'application/json' },
keepalive: true,
});
}
console.debug(`[Telemetry] Flushed ${batches.length} batches`);
} catch (error) {
console.error('[Telemetry] Failed to send batch:', error);
// Re-queue failed batches (with exponential backoff)
this.batchQueue.unshift(...batches);
}
}
private getEnvironment(): 'development' | 'staging' | 'production' {
if (process.env.NODE_ENV === 'production') {
return process.env.REACT_APP_ENV === 'staging' ? 'staging' : 'production';
}
return 'development';
}
private getBundleSize(): number {
// Would need to be injected during build
return (window as any).__BUNDLE_SIZE__ || 0;
}
}
export const telemetryService = TelemetryService.getInstance();
// Immediate error reporting for critical errors
async function sendImmediateErrorReport(errorReport: any) {
try {
await fetch('/api/telemetry/error', {
method: 'POST',
body: JSON.stringify(errorReport),
headers: { 'Content-Type': 'application/json' },
});
} catch (e) {
console.error('Failed to send immediate error report:', e);
}
}
// Debounced usage reporting
const debouncedSendUsage = debounce((context: UsageContext) => {
telemetryService.reportUsage(context);
}, 5000);
function debounce(func: Function, wait: number) {
let timeout: NodeJS.Timeout;
return (...args: any[]) => {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
5. Integrated HOC
// components/withTelemetry.tsx
import React from 'react';
import { withRenderMonitoring } from '../utils/renderMonitor';
import { TelemetryErrorBoundary } from '../utils/defectTracker';
import { usageCollector } from '../utils/contextCollector';
import { telemetryService } from '../services/telemetryService';
import { RenderMetrics } from '../types/telemetry';
interface TelemetryOptions {
trackUsage?: boolean;
trackErrors?: boolean;
trackRenders?: boolean;
componentAlias?: string;
defismicThreshold?: number; // Error threshold for alerting
}
export function withTelemetry<P extends object>(
WrappedComponent: React.ComponentType<P>,
options: TelemetryOptions = {}
) {
const {
trackUsage = true,
trackErrors = true,
trackRenders = true,
componentAlias,
defismicThreshold = 0.1, // Alert if >0.1% defect rate
} = options;
const displayName = componentAlias ||
WrappedComponent.displayName ||
WrappedComponent.name ||
'Anonymous';
const MonitoredComponent = React.forwardRef<any, P>((props, ref) => {
const parentName = React.useContext(ParentContext) || 'root';
const [renderMetrics, setRenderMetrics] = React.useState<RenderMetrics | null>(null);
// Capture usage context
React.useEffect(() => {
if (trackUsage) {
const context = usageCollector.captureContext(
displayName,
parentName,
props as Record<string, any>
);
// Report usage with debouncing
telemetryService.reportUsage(context);
}
});
// Handle render metrics
const handleRenderMetrics = React.useCallback((metrics: RenderMetrics) => {
setRenderMetrics(metrics);
if (trackRenders) {
telemetryService.reportRender(metrics);
}
}, [trackRenders]);
// Check defect density and alert if threshold exceeded
React.useEffect(() => {
if (trackErrors) {
const metrics = defectTracker.getDefectMetrics(displayName);
if (metrics.defectDensity > defismicThreshold) {
console.warn(`[Telemetry] High defect density for ${displayName}:`, metrics);
// Could trigger alert to monitoring system
}
}
}, [displayName, defismicThreshold, trackErrors]);
const element = (
<WrappedComponent
{...props}
ref={ref}
__telemetry_metrics={renderMetrics}
/>
);
if (trackErrors) {
return (
<ParentContext.Provider value={displayName}>
<TelemetryErrorBoundary componentName={displayName}>
{trackRenders ? (
<Profiler id={displayName} onRender={handleRenderMetrics}>
{element}
</Profiler>
) : (
element
)}
</TelemetryErrorBoundary>
</ParentContext.Provider>
);
}
return (
<ParentContext.Provider value={displayName}>
{trackRenders ? (
<Profiler id={displayName} onRender={handleRenderMetrics}>
{element}
</Profiler>
) : (
element
)}
</ParentContext.Provider>
);
});
MonitoredComponent.displayName = `withTelemetry(${displayName})`;
return MonitoredComponent;
}
// Context for parent tracking
const ParentContext = React.createContext<string | null>(null);
6. Dashboard Component
// components/TelemetryDashboard.tsx
import React, { useState, useEffect } from 'react';
import {
renderMonitor,
usageCollector,
defectTracker,
TelemetryService
} from '../services/telemetryService';
export const TelemetryDashboard: React.FC = () => {
const [metrics, setMetrics] = useState<any>(null);
const [selectedComponent, setSelectedComponent] = useState<string>('');
const [timeRange, setTimeRange] = useState<'1h' | '24h' | '7d'>('24h');
useEffect(() => {
const loadMetrics = () => {
const allComponents = Array.from(
new Set([
...renderMonitor['renderTimes']?.keys() || [],
...usageCollector['usageData']?.keys() || [],
...defectTracker['componentRenderCounts']?.keys() || [],
])
);
const componentMetrics = allComponents.map(name => ({
name,
avgRenderTime: renderMonitor.getAverageRenderTime(name),
avgCommitTime: renderMonitor.getAverageCommitTime(name),
usageCount: usageCollector.getUsageStats(name).length,
defectMetrics: defectTracker.getDefectMetrics(name),
defectDensity: defectTracker.getDefectMetrics(name).defectDensity,
}));
setMetrics({
components: componentMetrics,
summary: {
totalComponents: allComponents.length,
avgRenderTime: componentMetrics.reduce((sum, c) => sum + c.avgRenderTime, 0) / componentMetrics.length,
criticalDefects: defectTracker.getCriticalDefects().length,
totalErrors: defectTracker.getAllDefectMetrics().reduce((sum, m) => sum + m.errorCount, 0),
}
});
};
loadMetrics();
const interval = setInterval(loadMetrics, 10000); // Refresh every 10s
return () => clearInterval(interval);
}, [timeRange]);
if (!metrics) return <div>Loading telemetry...</div>;
return (
<div className="telemetry-dashboard p-6 bg-gray-50 min-h-screen">
<h1 className="text-3xl font-bold mb-6">Component Telemetry Dashboard</h1>
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
<div className="bg-white p-6 rounded-lg shadow">
<h3 className="text-lg font-semibold mb-2">Total Components</h3>
<p className="text-4xl font-bold text-blue-600">{metrics.summary.totalComponents}</p>
</div>
<div className="bg-white p-6 rounded-lg shadow">
<h3 className="text-lg font-semibold mb-2">Avg Render Time</h3>
<p className="text-4xl font-bold text-green-600">
{metrics.summary.avgRenderTime.toFixed(2)}ms
</p>
</div>
<div className="bg-white p-6 rounded-lg shadow">
<h3 className="text-lg font-semibold mb-2">Critical Defects</h3>
<p className="text-4xl font-bold text-red-600">
{metrics.summary.criticalDefects}
</p>
</div>
</div>
<div className="bg-white rounded-lg shadow p-6 mb-8">
<h2 className="text-2xl font-bold mb-4">Component Performance</h2>
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="border-b">
<th className="text-left p-3">Component</th>
<th className="text-left p-3">Avg Render (ms)</th>
<th className="text-left p-3">Defect Density</th>
<th className="text-left p-3">Errors</th>
<th className="text-left p-3">Status</th>
</tr>
</thead>
<tbody>
{metrics.components.map((comp: any) => (
<tr
key={comp.name}
className="border-b hover:bg-gray-50 cursor-pointer"
onClick={() => setSelectedComponent(comp.name)}
>
<td className="p-3 font-medium">{comp.name}</td>
<td className="p-3">{comp.avgRenderTime.toFixed(2)}</td>
<td className="p-3">
<span className={`px-2 py-1 rounded ${
comp.defectDensity > 0.1 ? 'bg-red-100 text-red-800' :
comp.defectDensity > 0.05 ? 'bg-yellow-100 text-yellow-800' :
'bg-green-100 text-green-800'
}`}>
{(comp.defectDensity * 100).toFixed(3)}%
</span>
</td>
<td className="p-3">{comp.defectMetrics.errorCount}</td>
<td className="p-3">
{comp.defectMetrics.severity === 'critical' && (
<span className="px-2 py-1 bg-red-500 text-white rounded text-sm">Critical</span>
)}
{comp.defectMetrics.severity === 'high' && (
<span className="px-2 py-1 bg-orange-500 text-white rounded text-sm">High</span>
)}
{comp.defectMetrics.severity === 'medium' && (
<span className="px-2 py-1 bg-yellow-500 text-white rounded text-sm">Medium</span>
)}
{comp.defectMetrics.severity === 'low' && (
<span className="px-2 py-1 bg-green-500 text-white rounded text-sm">Low</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
{selectedComponent && (
<ComponentDetail
componentName={selectedComponent}
onClose={() => setSelectedComponent('')}
/>
)}
</div>
);
};
const ComponentDetail: React.FC<{
componentName: string;
onClose: () => void;
}> = ({ componentName, onClose }) => {
const [detail, setDetail] = useState<any>(null);
useEffect(() => {
const defectMetrics = defectTracker.getDefectMetrics(componentName);
const usage = usageCollector.getUsageStats(componentName);
const avgRender = renderMonitor.getAverageRenderTime(componentName);
const avgCommit = renderMonitor.getAverageCommitTime(componentName);
setDetail({
defectMetrics,
usage,
avgRender,
avgCommit,
usageCount: usage.length,
});
}, [componentName]);
if (!detail) return null;
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
<div className="bg-white rounded-lg max-w-4xl w-full max-h-screen overflow-y-auto p-6">
<div className="flex justify-between items-center mb-4">
<h2 className="text-2xl font-bold">{componentName} Details</h2>
<button
onClick={onClose}
className="text-gray-500 hover:text-gray-700 text-2xl"
>
×
</button>
</div>
<div className="grid grid-cols-2 gap-6 mb-6">
<div className="bg-gray-50 p-4 rounded">
<h3 className="font-semibold mb-2">Performance</h3>
<p>Avg Render: {detail.avgRender.toFixed(2)}ms</p>
<p>Avg Commit: {detail.avgCommit.toFixed(2)}ms</p>
<p>Usage Count: {detail.usageCount}</p>
</div>
<div className="bg-gray-50 p-4 rounded">
<h3 className="font-semibold mb-2">Defects</h3>
<p>Total Errors: {detail.defectMetrics.errorCount}</p>
<p>Defect Density: {(detail.defectMetrics.defectDensity * 100).toFixed(3)}%</p>
<p>Severity: {detail.defectMetrics.severity}</p>
</div>
</div>
<div className="mb-6">
<h3 className="font-semibold mb-2">Error Types</h3>
<div className="flex flex-wrap gap-2">
{detail.defectMetrics.errorTypes.map(type => (
<span key={type} className="px-3 py-1 bg-red-100 text-red-800 rounded-full text-sm">
{type}
</span>
))}
</div>
</div>
<div>
<h3 className="font-semibold mb-2">Recent Usage Contexts</h3>
<div className="space-y-2 max-h-64 overflow-y-auto">
{detail.usage.slice(-10).reverse().map((ctx: any, i: number) => (
<div key={i} className="bg-gray-50 p-3 rounded text-sm">
<p><strong>Route:</strong> {ctx.route || 'N/A'}</p>
<p><strong>Viewport:</strong> {ctx.viewport.width}x{ctx.viewport.height}</p>
<p><strong>Props:</strong> {JSON.stringify(ctx.propsSnapshot).substring(0, 100)}...</p>
</div>
))}
</div>
</div>
</div>
</div>
);
};
7. Configuration & Setup
// telemetry.config.ts
export const telemetryConfig = {
// Enable/disable telemetry
enabled: process.env.NODE_ENV === 'production',
// Sampling rate for renders (0-1)
renderSampleRate: 0.1, // 10% of renders
// Error reporting
captureErrors: true,
errorSampleRate: 1.0, // All errors
// Usage context
trackUserJourney: true,
trackProps: true,
maxPropsDepth: 2, // How deep to parse props
// Defect density
alertThreshold: 0.1, // Alert if >0.1% defect rate
minRendersForDensity: 100, // Minimum renders before calculating density
// Privacy
redactSensitiveProps: [
'password', 'token', 'secret', 'key', 'auth', 'credentials'
],
anonymizeUserId: true,
// Performance
batchSize: 50,
flushIntervalMs: 30000,
// Endpoints
endpoint: '/api/telemetry',
errorEndpoint: '/api/telemetry/errors',
};
// Initialize on app start
export function initializeTelemetry() {
if (telemetryConfig.enabled) {
// Initialize collectors
const reporter = TelemetryService.getInstance();
const collector = UsageContextCollector.getInstance();
const tracker = DefectTracker.getInstance();
// Set session
collector.getSessionId();
console.log('[Telemetry] Initialized');
// Expose for debugging
if (process.env.NODE_ENV === 'development') {
(window as any).__TELEMETRY__ = {
reporter,
collector,
tracker,
config: telemetryConfig,
};
}
}
}
8. Usage Example
// App.tsx
import React from 'react';
import { TelemetryDashboard } from './components/TelemetryDashboard';
import { withTelemetry } from './components/withTelemetry';
import { initializeTelemetry } from './telemetry.config';
// Initialize telemetry
initializeTelemetry();
// Regular component
const UserCard: React.FC<{ user: User; onClick?: () => void }> = ({ user, onClick }) => (
<div className="user-card" onClick={onClick}>
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
);
// Enhanced with telemetry
const MonitoredUserCard = withTelemetry(UserCard, {
componentAlias: 'UserCard',
defismicThreshold: 0.05, // Custom threshold
});
// Dashboard component
const App: React.FC = () => (
<div>
<nav>
<button onClick={() => telemetryService.disable()}>Disable Telemetry</button>
<button onClick={() => telemetryService.enable()}>Enable Telemetry</button>
</nav>
<MonitoredUserCard
user={{ id: 1, name: 'John', email: 'john@example.com' }}
onClick={() => console.log('clicked')}
/>
{/* Only show dashboard in development */}
{process.env.NODE_ENV === 'development' && <TelemetryDashboard />}
</div>
);
9. Backend API Example (Node.js)
// server/telemetry.js
const express = require('express');
const router = express.Router();
const { Kafka } = require('kafkajs');
// Initialize Kafka for streaming processing
const kafka = new Kafka({
clientId: 'telemetry-service',
brokers: [process.env.KAFKA_BROKERS || 'localhost:9092']
});
const producer = kafka.producer();
// Store in database (example with PostgreSQL)
const { Pool } = require('pg');
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
// Middleware to validate and sanitize
const validateTelemetry = (req, res, next) => {
const { sessionId, metrics } = req.body;
if (!sessionId || !metrics) {
return res.status(400).json({ error: 'Invalid telemetry data' });
}
next();
};
// Main telemetry endpoint
router.post('/', validateTelemetry, async (req, res) => {
try {
const { sessionId, batchId, metrics, metadata } = req.body;
// Send to Kafka for real-time processing
await producer.send({
topic: 'telemetry-raw',
messages: [{ value: JSON.stringify(req.body) }],
});
// Store in PostgreSQL for analysis
for (const render of metrics.renders || []) {
await pool.query(`
INSERT INTO render_metrics
(component_name, render_duration, commit_duration, session_id, timestamp, build_id)
VALUES ($1, $2, $3, $4, $5, $6)
`, [
render.componentName,
render.renderDurationMs,
render.commitDurationMs,
sessionId,
new Date(render.timestamp),
metadata?.buildId,
]);
}
for (const defect of metrics.defects || []) {
await pool.query(`
INSERT INTO defect_metrics
(component_name, error_count, severity, defect_density, session_id, timestamp)
VALUES ($1, $2, $3, $4, $5, $6)
`, [
defect.componentName,
defect.errorCount,
defect.severity,
defect.defectDensity,
sessionId,
new Date(),
]);
}
res.json({ status: 'received', batchId });
} catch (error) {
console.error('Telemetry processing error:', error);
res.status(500).json({ error: 'Processing failed' });
}
});
// Error endpoint (for immediate errors)
router.post('/error', async (req, res) => {
try {
const { componentName, error, stack, timestamp, sessionId } = req.body;
// Send to high-priority Kafka topic
await producer.send({
topic: 'telemetry-errors-critical',
messages: [{ value: JSON.stringify(req.body) }],
});
// Store in separate table for immediate attention
await pool.query(`
INSERT INTO critical_errors
(component_name, error_message, stack_trace, session_id, timestamp)
VALUES ($1, $2, $3, $4, $5)
`, [componentName, error, stack, sessionId, new Date(timestamp)]);
// Could trigger alert here
if (process.env.ALERT_WEBHOOK) {
await fetch(process.env.ALERT_WEBHOOK, {
method: 'POST',
body: JSON.stringify({
level: 'critical',
component: componentName,
error,
timestamp,
}),
});
}
res.json({ status: 'critical_error_received' });
} catch (error) {
console.error('Critical error processing failed:', error);
res.status(500).json({ error: 'Failed to process critical error' });
}
});
// Analytics endpoint for dashboard
router.get('/analytics', async (req, res) => {
const { component, timeRange = '24h' } = req.query;
const timeCondition = {
'1h': "timestamp > NOW() - INTERVAL '1 hour'",
'24h': "timestamp > NOW() - INTERVAL '24 hours'",
'7d': "timestamp > NOW() - INTERVAL '7 days'",
}[timeRange as string] || timeCondition['24h'];
try {
const result = await pool.query(`
SELECT
component_name,
AVG(render_duration) as avg_render_ms,
COUNT(*) as render_count,
SUM(CASE WHEN defect_density > 0.1 THEN 1 ELSE 0 END) as high_defect_instances
FROM render_metrics rm
LEFT JOIN defect_metrics dm ON rm.component_name = dm.component_name
WHERE ${timeCondition}
${component ? "AND rm.component_name = $1" : ''}
GROUP BY component_name
ORDER BY avg_render_ms DESC
LIMIT 50
`, component ? [component] : []);
res.json(result.rows);
} catch (error) {
res.status(500).json({ error: 'Analytics query failed' });
}
});
module.exports = router;
10. Database Schema (PostgreSQL)
-- Render metrics
CREATE TABLE render_metrics (
id SERIAL PRIMARY KEY,
component_name VARCHAR(255) NOT NULL,
render_duration_ms DECIMAL(10,2) NOT NULL,
commit_duration_ms DECIMAL(10,2),
session_id VARCHAR(255) NOT NULL,
build_id VARCHAR(100),
timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
INDEX idx_component_name (component_name),
INDEX idx_timestamp (timestamp)
);
-- Defect metrics
CREATE TABLE defect_metrics (
id SERIAL PRIMARY KEY,
component_name VARCHAR(255) NOT NULL,
error_count INTEGER NOT NULL,
error_types JSONB, -- Array of error types
severity VARCHAR(20) NOT NULL,
defect_density DECIMAL(10,4) NOT NULL,
session_id VARCHAR(255),
timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
INDEX idx_component_name (component_name),
INDEX idx_severity (severity),
INDEX idx_timestamp (timestamp)
);
-- Usage contexts (sampled, not every render)
CREATE TABLE usage_contexts (
id SERIAL PRIMARY KEY,
component_name VARCHAR(255) NOT NULL,
parent_component VARCHAR(255),
props_snapshot JSONB NOT NULL,
route VARCHAR(500),
user_id VARCHAR(255),
session_id VARCHAR(255) NOT NULL,
viewport_width INTEGER,
viewport_height INTEGER,
device_platform VARCHAR(100),
feature_flags JSONB,
timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
INDEX idx_component_route (component_name, route),
INDEX idx_session (session_id),
INDEX idx_timestamp (timestamp)
);
-- Critical errors (immediate reporting)
CREATE TABLE critical_errors (
id SERIAL PRIMARY KEY,
component_name VARCHAR(255) NOT NULL,
error_message TEXT NOT NULL,
stack_trace TEXT,
error_info JSONB,
session_id VARCHAR(255),
timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
INDEX idx_component (component_name),
INDEX idx_timestamp (timestamp)
);
Key Features:
-
Render Cost Monitoring
- Uses React Profiler API for accurate measurements
- Tracks both render and commit phases
- Rolling averages for performance insights
-
Usage Context Collection
- Automatic parent component tracking
- Props sanitization (PII protection)
- Device & viewport information
- Route and session tracking
-
Defect Density Calculation
- Error grouping by type
- Severity classification (low/critical)
- Rolling error rate calculation
- Real-time threshold alerts
-
Privacy & Performance
- Configurable sampling rates
- Sensitive data redaction
- Debounced reporting
- Beacon API for reliability
- Visibility change detection
-
Production Ready
- Batch processing
- Error recovery with retry
- Kafka streaming for scale
- Comprehensive dashboard
- TypeScript support
-
Developer Experience
- Simple HOC wrapper
withTelemetry()
- Development dashboard
- Debug mode with global
__TELEMETRY__ object
- Non-intrusive (zero config works)
Installation:
npm install @your-org/telemetry
# or
yarn add @your-org/telemetry
Configuration:
// src/index.tsx
import { initializeTelemetry } from '@your-org/telemetry';
initializeTelemetry();
// Wrap components
const MonitoredButton = withTelemetry(Button, {
componentAlias: 'PrimaryButton',
defismicThreshold: 0.01,
});
// Add dashboard to development
if (process.env.NODE_ENV === 'development') {
const { TelemetryDashboard } = await import('@your-org/telemetry');
ReactDOM.render(<TelemetryDashboard />, document.getElementById('telemetry-root'));
}
This system provides:
- Real-time monitoring of component performance
- Automatic defect tracking with density calculation
- Privacy-first data collection
- Scalable architecture with Kafka streaming
- Developer-friendly dashboard
- Zero-configuration basic setup with deep customization options
The system is designed to be production-ready with proper error handling, sampling, batching, and privacy controls.