Skip to content
Merged
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
71 changes: 66 additions & 5 deletions src/instrumentation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
import { NodeSDK } from "@opentelemetry/sdk-node";
import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-node";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { POSTHOG_API_KEY, POSTHOG_TRACES_URL } from "./lib/posthog-config.ts";

const mockStart = vi.fn();
const mockShutdown = vi.fn().mockResolvedValue(undefined);
Expand Down Expand Up @@ -166,7 +167,7 @@ describe("instrumentation", () => {
startInstrumentation({ OTEL_EXPORTER_OTLP_ENDPOINT: "http://localhost:4318" });

expect(NodeSDK).toHaveBeenCalledOnce();
const config = vi.mocked(NodeSDK).mock.calls[0]?.[0];
const config = vi.mocked(NodeSDK).mock.calls.at(-1)?.[0];
expect(config?.spanProcessors).toHaveLength(1);
expect(config?.logRecordProcessors).toHaveLength(1);
expect(config?.metricReader).toBeDefined();
Expand All @@ -190,7 +191,7 @@ describe("instrumentation", () => {
DEPLOY_ENVIRONMENT: "production",
});

const config = vi.mocked(NodeSDK).mock.calls[0]?.[0];
const config = vi.mocked(NodeSDK).mock.calls.at(-1)?.[0];
expect(config?.logRecordProcessors).toHaveLength(1);
expect(BatchLogRecordProcessor).toHaveBeenCalledWith({
exporter: expect.any(OTLPLogExporter),
Expand All @@ -205,14 +206,74 @@ describe("instrumentation", () => {
);
});

it.each([
"prod",
"production",
])("adds a PostHog trace exporter in production even without Axiom endpoints (DEPLOY_ENVIRONMENT=%s)", async (deploymentEnvironment) => {
const { startInstrumentation } = await import("./instrumentation.ts");

startInstrumentation({
DEPLOY_ENVIRONMENT: deploymentEnvironment,
});

const config = vi.mocked(NodeSDK).mock.calls.at(-1)?.[0];
expect(config?.spanProcessors).toHaveLength(1);
expect(config?.instrumentations).toEqual([mockAutoInstrumentations]);
expect(BatchSpanProcessor).toHaveBeenCalledWith(expect.any(OTLPTraceExporter));
expect(OTLPTraceExporter).toHaveBeenCalledWith(
Comment thread
Asherlc marked this conversation as resolved.
expect.objectContaining({
url: POSTHOG_TRACES_URL,
headers: expect.objectContaining({
Authorization: `Bearer ${POSTHOG_API_KEY}`,
}),
}),
);
});

it("keeps Axiom and PostHog trace exporters alongside each other in production with an Axiom endpoint", async () => {
const { startInstrumentation } = await import("./instrumentation.ts");

startInstrumentation({
DEPLOY_ENVIRONMENT: "production",
OTEL_EXPORTER_OTLP_ENDPOINT: "http://localhost:4318",
});

const config = vi.mocked(NodeSDK).mock.calls.at(-1)?.[0];
expect(config?.spanProcessors).toHaveLength(2);
expect(BatchSpanProcessor).toHaveBeenCalledTimes(2);
});

it("adds PostHog traces without PostHog logs for production services configured with explicit OTLP endpoints", async () => {
const { startInstrumentation } = await import("./instrumentation.ts");

startInstrumentation({
NODE_ENV: "production",
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: "http://collector:4318/v1/traces",
OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: "http://collector:4318/v1/logs",
});

const config = vi.mocked(NodeSDK).mock.calls.at(-1)?.[0];
expect(config?.spanProcessors).toHaveLength(2);
expect(config?.logRecordProcessors).toHaveLength(1);
expect(OTLPTraceExporter).toHaveBeenCalledTimes(2);
expect(OTLPTraceExporter).toHaveBeenLastCalledWith({
url: POSTHOG_TRACES_URL,
headers: {
Authorization: `Bearer ${POSTHOG_API_KEY}`,
},
});
expect(OTLPLogExporter).toHaveBeenCalledOnce();
expect(OTLPLogExporter).toHaveBeenCalledWith();
});

it("only configures trace processors and auto instrumentations when only traces endpoint exists", async () => {
const { startInstrumentation } = await import("./instrumentation.ts");

startInstrumentation({
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: "http://localhost:4318/v1/traces",
});

const config = vi.mocked(NodeSDK).mock.calls[0]?.[0];
const config = vi.mocked(NodeSDK).mock.calls.at(-1)?.[0];
expect(config?.spanProcessors).toHaveLength(1);
expect(config?.logRecordProcessors).toHaveLength(0);
expect(config?.metricReader).toBeUndefined();
Expand All @@ -227,7 +288,7 @@ describe("instrumentation", () => {
OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: "http://localhost:4318/v1/logs",
});

const config = vi.mocked(NodeSDK).mock.calls[0]?.[0];
const config = vi.mocked(NodeSDK).mock.calls.at(-1)?.[0];
expect(config?.spanProcessors).toHaveLength(0);
expect(config?.logRecordProcessors).toHaveLength(1);
expect(config?.instrumentations).toEqual([]);
Expand All @@ -241,7 +302,7 @@ describe("instrumentation", () => {
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: "http://localhost:4318/v1/metrics",
});

const config = vi.mocked(NodeSDK).mock.calls[0]?.[0];
const config = vi.mocked(NodeSDK).mock.calls.at(-1)?.[0];
expect(config?.spanProcessors).toHaveLength(0);
expect(config?.logRecordProcessors).toHaveLength(0);
expect(config?.metricReader).toBeDefined();
Expand Down
45 changes: 38 additions & 7 deletions src/instrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,44 @@ import { resourceFromAttributes } from "@opentelemetry/resources";
import { BatchLogRecordProcessor, type LogRecordProcessor } from "@opentelemetry/sdk-logs";
import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
import { NodeSDK } from "@opentelemetry/sdk-node";
import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-node";
import { BatchSpanProcessor, type SpanProcessor } from "@opentelemetry/sdk-trace-node";
import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
import { POSTHOG_API_KEY, POSTHOG_LOGS_URL } from "./lib/posthog-config.ts";
import { POSTHOG_API_KEY, POSTHOG_LOGS_URL, POSTHOG_TRACES_URL } from "./lib/posthog-config.ts";

function isProductionDeployment(environment: string | undefined): boolean {
return environment === "prod" || environment === "production";
}

function createSpanProcessors(env: Record<string, string | undefined>): SpanProcessor[] {
const endpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT;
const tracesEndpoint = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT;
const hasAxiomTraceExport = Boolean(endpoint || tracesEndpoint);
const hasPostHogTraceExport =
isProductionDeployment(env.DEPLOY_ENVIRONMENT) ||
(env.NODE_ENV === "production" && hasAxiomTraceExport);

const processors: SpanProcessor[] = [];

if (hasAxiomTraceExport) {
processors.push(new BatchSpanProcessor(new OTLPTraceExporter()));
}

if (hasPostHogTraceExport) {
processors.push(
new BatchSpanProcessor(
new OTLPTraceExporter({
url: POSTHOG_TRACES_URL,
headers: {
Authorization: `Bearer ${POSTHOG_API_KEY}`,
},
}),
),
);
}

return processors;
Comment thread
qodo-code-review[bot] marked this conversation as resolved.
}

function createLogRecordProcessors(env: Record<string, string | undefined>): LogRecordProcessor[] {
const endpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT;
const logsEndpoint = env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT;
Expand Down Expand Up @@ -47,17 +77,18 @@ function createLogRecordProcessors(env: Record<string, string | undefined>): Log
}

/**
* Starts OpenTelemetry instrumentation when OTLP export env vars are set.
* Returns the SDK instance for shutdown, or undefined if OTel is disabled.
* Starts OpenTelemetry instrumentation when a telemetry export is configured
* (OTLP env vars or a production PostHog export). Returns the SDK instance for
* shutdown, or undefined if OTel is disabled.
*/
export function startInstrumentation(
env: Record<string, string | undefined> = process.env,
): NodeSDK | undefined {
const endpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT;
const tracesEndpoint = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT;
const metricsEndpoint = env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT;

const hasTraceExport = Boolean(endpoint || tracesEndpoint);
const spanProcessors = createSpanProcessors(env);
const hasTraceExport = spanProcessors.length > 0;
const logRecordProcessors = createLogRecordProcessors(env);
const hasLogExport = logRecordProcessors.length > 0;
const hasMetricExport = Boolean(endpoint || metricsEndpoint);
Expand All @@ -71,7 +102,7 @@ export function startInstrumentation(
resource: resourceFromAttributes({
[ATTR_SERVICE_NAME]: serviceName,
}),
spanProcessors: hasTraceExport ? [new BatchSpanProcessor(new OTLPTraceExporter())] : [],
spanProcessors,
logRecordProcessors,
metricReader: hasMetricExport
? new PeriodicExportingMetricReader({
Expand Down
2 changes: 2 additions & 0 deletions src/lib/posthog-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ export const POSTHOG_API_KEY = "phc_GsvyihTLSXrWGKYYGz84m44nuT59kYEwEXNnI0JICtg"
export const POSTHOG_HOST = "https://us.i.posthog.com";

export const POSTHOG_LOGS_URL = `${POSTHOG_HOST}/i/v1/logs`;

export const POSTHOG_TRACES_URL = `${POSTHOG_HOST}/i/v1/traces`;
Loading