Cedervall
Cedervall

Reputation: 1939

Token update for open telemetry in frontend

I have a front-end application (React) that would like to send logs to a collector. The problem is in my current setup I set my token at init, and can't seem to find a smooth way to update my token (valid for 5mins). So I need a way to update it.

Here's a part of the code:

Adding logs to the queue:

logger.emit({
  severityText: logLevel,
  body: message,
  attributes: {
    ...attributes,
    timestamp: new Date().toISOString(),
  },
});

This is where I create the logger provider.

const loggerProvider = new LoggerProvider({ resource });
const logExporter = new OTLPLogExporter({ url: `${COLLECTOR_URL}/logs`, headers: commonHeaders });
loggerProvider.addLogRecordProcessor(new BatchLogRecordProcessor(logExporter));

const logger = loggerProvider.getLogger("default-logger");
export { logger };

I've tried to override the send method in the OTLPLogExporter.

This is my attempt to override.

class DynamicOTLPLogExporter extends OTLPLogExporter {
  constructor(url: string) {
    super({ url });
  }

  send(objects: any[], onSuccess: () => void, onError: (error: any) => void) {
    this.headers = {
        Authorization: window.accessToken ?? "",
        concurrencyLimit: "1",
    }
    super.send(objects, onSuccess, onError);
  }
}```

Upvotes: 0

Views: 19

Answers (1)

Cedervall
Cedervall

Reputation: 1939

I found an issue on github: https://github.com/open-telemetry/opentelemetry-js/issues/2903?reload=1 where a similar problem. I modified it a little bit and here's the solution.

I read somewhere that they're redoing the export functions so while this works now ("@opentelemetry/exporter-logs-otlp-http": "^0.48.0") it might not work on future implementations.

class CustomOTLPLogExporter extends OTLPLogExporter {
  private readonly getToken: () => string | undefined;
  private _headers: Record<string, unknown>;

  constructor(config: OTLPExporterNodeConfigBase, getToken: () => string | undefined) {
    super(config);
    this.getToken = getToken;
    this._headers = { ...config.headers };
  }

  export(items: LogRecord[], resultCallback: (result: ExportResult) => void) {
    // Update headers with a fresh token on each export call
    this._headers = { ...this._headers, Authorization: `${this.getToken()}` };
    return super.export(items, resultCallback);
  }
}

Upvotes: 0

Related Questions