OpenTelemetry in a script tag

When I make a website, even a toy one, I want to get telemetry. Has anyone visited it? Did my JavaScript crash? Little things.

I want to send this with OpenTelemetry, because it’s the industry standard and all. Currently (November 2023), that requires a whole JavaScript build chain to package up the libraries etc etc. For a toy site, I want to include a script tag and have that do the work.

OpenTelemetry isn’t distributed that way (yet), so I made my own distribution. One packaged-up wrapper around tracing initialization, and now I can include it quickly.

a graph counting spans by name. There are 11 of "test span" and 10 each of "Error on page" and "another test span."
this is technically data

I do not recommend using my wrapper. I do recommend copying it and making your own.

Here’s the process:

Starting with the OpenTelemetry getting-started-in-the-browser docs, I made a little project that builds with Parcel.

My little bit of code includes the OpenTelemetry libraries, wraps exactly what I need, and makes that available globally. Hopefully Parcel will discard code that I don’t call. The money line:

window.Otel = { sendTestSpan, initializeTracing, trace, instrumentGlobalErrors };

Then in package.json, a target tells Parcel to build me something for global browser use:

"targets": {
    "scriptie": {
      "includeNodeModules": true,
      "context": "browser",
      "outputFormat": "global",
      "isLibrary": false,
      "source": [
        "src/otel.js"
      ],
      "sourceMap": false
    }
  },

Then I can build it with

parcel build --target script

That creates a single file: dist/otel.js

Next I created a GitHub release (publishing on npm would be better, but their password reset is broken right now) to serve that file.

Now in my toy site, I can import that script, and then use it:

<script src="https://github.com/jessitron/min-otel/releases/download/v0.0.3/otel.js"></script>
<script>
  Otel.initializeTracing();
  Otel.sendTestSpan();
</script>

This works while I’m running a collector locally, and testing my toy site locally. Check the network tab and look for calls to /v1/traces to see whether yours are working.

Discover more from Jessitron

Subscribe now to keep reading and get access to the full archive.

Continue reading