Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Allow defining page.route #185

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 49 additions & 2 deletions examples/hello-world-react-create-app/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions examples/hello-world-react-create-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
"npm": "^10.8.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router": "^6.25.1",
"react-router-dom": "^6.25.1",
"react-scripts": "5.0.1",
"typescript": "^4.9.5",
"web-vitals": "^4.0.1"
Expand Down
31 changes: 30 additions & 1 deletion examples/hello-world-react-create-app/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,13 @@ import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

import { HoneycombWebSDK } from '@honeycombio/opentelemetry-web';
import {
HoneycombWebSDK,
DynamicAttributesSpanProcessor,
} from '@honeycombio/opentelemetry-web';
import { getWebAutoInstrumentations } from '@opentelemetry/auto-instrumentations-web';
import { RouterProvider } from 'react-router-dom';
import { router } from './router';

const configDefaults = {
ignoreNetworkEvents: true,
Expand All @@ -17,6 +22,7 @@ const root = ReactDOM.createRoot(
root.render(
<React.StrictMode>
<App />
<RouterProvider router={router} />
</React.StrictMode>,
);

Expand All @@ -28,7 +34,25 @@ root.render(
// It's just for debugging purposes.
reportWebVitals(console.log);

function createRouteGetter() {
let route = window.location.pathname;
router.subscribe((state) => {
let newRoute = '';
// some shenanigans here since routes can be nested
for (let i = state.matches.length - 1; i >= 0; --i) {
const path = state.matches[i]?.route.path;
if (!path) continue;
if (!route.startsWith(path))
newRoute =
path + (newRoute.startsWith('/') ? newRoute : '/' + newRoute);
}
route = newRoute;
});
return () => route;
}

try {
const getRoute = createRouteGetter();
const sdk = new HoneycombWebSDK({
apiKey: 'api-key-goes-here',
serviceName: 'hny-web-distro-example:hello-world-react-create-app',
Expand All @@ -39,6 +63,11 @@ try {
'@opentelemetry/instrumentation-document-load': configDefaults,
}),
], // add automatic instrumentation
spanProcessors: [
new DynamicAttributesSpanProcessor({
getAttributes: () => ({ 'page.route': getRoute() }),
}),
],
});
sdk.start();
} catch (err) {
Expand Down
17 changes: 17 additions & 0 deletions examples/hello-world-react-create-app/src/router.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { createBrowserRouter, useParams } from 'react-router-dom';

function Hello({ name }: { name?: string }) {
const params = useParams();
const paramName = params['name'];
return <h1>Hello {paramName ?? name}!</h1>;
}
export const router = createBrowserRouter([
{
path: '/',
element: <Hello name="world" />,
},
{
path: '/:name',
element: <Hello />,
},
]);
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

49 changes: 20 additions & 29 deletions src/browser-attributes-span-processor.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,28 @@
import { Span } from '@opentelemetry/api';
import { SpanProcessor } from '@opentelemetry/sdk-trace-base';
import { DynamicAttributesSpanProcessor } from './dynamic-attributes-span-processor';

function getBrowserAttributes() {
const { href, pathname, search, hash, hostname } = window.location;

return {
'browser.width': window.innerWidth,
'browser.height': window.innerHeight,
'page.hash': hash,
'page.url': href,
'page.route': pathname,
'page.hostname': hostname,
'page.search': search,

'url.path': pathname,
};
}

/**
* A {@link SpanProcessor} that adds browser specific attributes to each span
* that might change over the course of a session.
* Static attributes (e.g. User Agent) are added to the Resource.
*/
export class BrowserAttributesSpanProcessor implements SpanProcessor {
constructor() {}

onStart(span: Span) {
const { href, pathname, search, hash, hostname } = window.location;

span.setAttributes({
'browser.width': window.innerWidth,
'browser.height': window.innerHeight,
'page.hash': hash,
'page.url': href,
'page.route': pathname,
'page.hostname': hostname,
'page.search': search,

'url.path': pathname,
});
}

onEnd() {}

forceFlush() {
return Promise.resolve();
}

shutdown() {
return Promise.resolve();
export class BrowserAttributesSpanProcessor extends DynamicAttributesSpanProcessor {
constructor() {
super({ getAttributes: getBrowserAttributes });
}
}
31 changes: 31 additions & 0 deletions src/dynamic-attributes-span-processor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Attributes, Span } from '@opentelemetry/api';
import { SpanProcessor } from '@opentelemetry/sdk-trace-base';

interface PageRouteSpanProcessorOptions {
getAttributes: () => Attributes;
}

/**
* A {@link SpanProcessor} that adds dynamic attributes to every span
*/
export class DynamicAttributesSpanProcessor implements SpanProcessor {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkanal, I started thinking that maybe a PageRouteSpanProcessor makes less sense than something more generic, so here is a DynamicAttributesSpanProcessor which can be exposed and the BrowserAttributesSpanProcessor can be implemented in terms of. This would avoid needing to introduce a separate processor for each little attribute that comes up over time.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like this approach! I'm wondering whether this should be something we package with the SDK or whether this should be documented for users since everyone's use case will be slightly different? 🤔

Thoughts @wolfgangcodes / @MustafaHaddara ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm arriving at the same conclusion. I think adding dynamic attributes globally like this will be a common use case, but at the same time this is so exceedingly generic as to be almost worthless. I'm hoping that sometime soon the OTel client instrumentation SIG comes up with a proposal to allow dynamic resource attributes which might fit these use cases better. At that point the page.route thing is something you'd just set up in your render cycle with a trace.addResourceAttributes({ 'page.route': match.route }) and would also take care of things like changing the enduser.id or tenant.id when a user logs in during a session.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmmmm yeah, I think that is what span processors are meant to do in general. So are we coming to the conclusion that the best thing to do here is make sure that this distro is able to support multiple span processors and that this should be expressed as a custom span processor in a consuming app?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, agreed, I'll close this PR

private getAttributes: () => Attributes;
constructor(options: PageRouteSpanProcessorOptions) {
this.getAttributes = options.getAttributes;
}

onStart(span: Span) {
const attributes = this.getAttributes();
span.setAttributes(attributes);
}

onEnd() {}

forceFlush() {
return Promise.resolve();
}

shutdown() {
return Promise.resolve();
}
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './base-otel-sdk';
export * from './honeycomb-otel-sdk';
export * from './web-vitals-autoinstrumentation';
export * from './dynamic-attributes-span-processor';
Loading