warn that otel wasn't initialized properly, every time we would have sent a span (#30)

The log should contain a warning showing the following once at startup:
```
OpenTelemetry initialization skipped: HONEYCOMB_API_KEY and/or HONEYCOMB_DATASET not set
```
and every time a span would have been created:
```
OpenTelemetry not initialized, skipping span creation
```

Also sneak in a `service.version` attribute that is `${__APP_VERSION}; ${__COMMIT_HASH}`.  e.g.:
![image](https://github.com/user-attachments/assets/6f111cb1-8fb9-46c4-9bd8-24bdd08650ab)
This commit is contained in:
Chris Toshok
2025-02-18 12:00:38 -08:00
committed by GitHub
parent 6221ab1d3e
commit d81ab41688

View File

@@ -1,11 +1,13 @@
import { Resource } from '@opentelemetry/resources';
import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions';
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { ZoneContextManager } from '@opentelemetry/context-zone';
import { SpanStatusCode, type Attributes, context, trace } from '@opentelemetry/api';
let otelInitialized = false;
function initializeOpenTelemetry() {
const honeycombApiKey = process.env.HONEYCOMB_API_KEY;
const honeycombDataset = process.env.HONEYCOMB_DATASET;
@@ -27,6 +29,7 @@ function initializeOpenTelemetry() {
const resource = new Resource({
[ATTR_SERVICE_NAME]: 'nut.server',
[ATTR_SERVICE_VERSION]: `${__APP_VERSION}; ${__COMMIT_HASH}`,
});
const provider = new WebTracerProvider({
@@ -38,6 +41,8 @@ function initializeOpenTelemetry() {
contextManager: new ZoneContextManager(),
});
otelInitialized = true;
return provider.getTracer('nut-server');
}
@@ -66,6 +71,10 @@ export function wrapWithSpan<Args extends any[], T>(
fn: (...args: Args) => Promise<T>,
): (...args: Args) => Promise<T> {
return async (...args: Args) => {
if (!otelInitialized) {
console.warn("OpenTelemetry not initialized, skipping span creation");
}
return tracer.startActiveSpan(opts.name, async (span) => {
if (opts.attrs) {
span.setAttributes(opts.attrs);