Skip to content
Merged

pr #27

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
2 changes: 2 additions & 0 deletions bun.lock

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

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@
"@opentelemetry/api": "^1.10.0",
"@opentelemetry/api-logs": "^0.223.0",
"@opentelemetry/exporter-logs-otlp-http": "^0.223.1",
"@opentelemetry/exporter-trace-otlp-http": "^0.223.1",
"@opentelemetry/resources": "^2.12.1",
"@opentelemetry/sdk-logs": "^0.223.1",
"@opentelemetry/sdk-node": "^0.223.1",
"@opentelemetry/sdk-trace-base": "^2.12.1",
"@orpc/client": "^1.16.2",
"@orpc/openapi": "^1.16.2",
"@orpc/server": "^1.16.2",
Expand Down
34 changes: 31 additions & 3 deletions src/hooks.client.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
import type { HandleClientError } from "@sveltejs/kit";
import posthog from "posthog-js";
import { dev } from "$app/environment";
import { captureLog } from "$lib/client/logging";
import { initBrowserTracing, startSpan } from "$lib/client/tracing";

let posthogInitialized = false;

export function isPostHogInitialized() {
return posthogInitialized;
}

function describeError(error: unknown): string {
if (error instanceof Error) {
return `${error.name}: ${error.message}`;
}
return String(error);
}

export function init() {
const key = "phc_AS2JXQsqEwNNreH5kra5Eefd5TijExE5eiLfwdzXLhPg";
const key = "phc_AS2JXQsqEwNNreH5kra5Eefd5TijExEe5eiLfwdzXLhPg";
const host = "https://us.i.posthog.com";

if (!key || !host) {
Expand All @@ -30,13 +39,32 @@ export function init() {
capture_unhandled_rejections: true,
capture_console_errors: false,
},
logs: {
serviceName: "lightcms-web",
environment: import.meta.env.MODE,
captureConsoleLogs: false,
Comment thread
Pratyay360 marked this conversation as resolved.
Resolved
},
person_profiles: "always",
});

initBrowserTracing({ posthogKey: key, posthogHost: host });

posthogInitialized = true;
}

export const handleError: HandleClientError = ({ error }) => {
if (posthogInitialized) {
posthog.captureException(error);
if (!posthogInitialized) {
return;
}

posthog.captureException(error);

const span = startSpan("client.error");

captureLog("error", describeError(error), {
span,
attributes: { "error.source": "sveltekit.handleError" },
});

span?.end();
};
41 changes: 41 additions & 0 deletions src/lib/client/logging.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import type { Span } from "@opentelemetry/api";
import posthog from "posthog-js";

/**
* Logs emitted through this module carry the trace and span ids of the span the
* caller is working in, which is what Correlates a log record with its trace in
* PostHog. Console autocapture cannot do this: posthog-js wraps `console.*` and
* sends `{ level, body, attributes }` only, with no trace fields and no access
* to OpenTelemetry context.
*/

export type LogLevel = "info" | "warn" | "error";

export type LogAttributeValue = string | number | boolean;

export interface LogContext {
span?: Span;
attributes?: Record<string, LogAttributeValue>;
}

export function captureLog(
level: LogLevel,
body: string,
{ span, attributes = {} }: LogContext = {},
): void {
if (!span) {
posthog.captureLog({ body, level, attributes });
return;
}

const { traceId, spanId, traceFlags } = span.spanContext();

posthog.captureLog({
body,
level,
attributes,
trace_id: traceId,
span_id: spanId,
trace_flags: traceFlags,
});
}
57 changes: 57 additions & 0 deletions src/lib/client/tracing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { trace, type Attributes, type Span, type Tracer } from "@opentelemetry/api";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { BasicTracerProvider, BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";

/**
* Browser tracing for PostHog.
*
* posthog-js does not create spans (see the web SDK docs, "Configuring traces"),
* so a log record emitted from the browser has no trace to point at unless this
* app produces one. Spans are exported to the same project as the logs, which
* lets PostHog resolve `trace_id` on a log record to its trace.
*/

const SERVICE_NAME = "lightcms-web";

interface BrowserTracingConfig {
posthogKey: string;
posthogHost: string;
}

let tracer: Tracer | undefined;

export function initBrowserTracing({ posthogKey, posthogHost }: BrowserTracingConfig): void {
if (tracer) {
return;
}

const exporter = new OTLPTraceExporter({
url: new URL("/i/v1/traces", posthogHost).toString(),
headers: { Authorization: `Bearer ${posthogKey}` },
});

const provider = new BasicTracerProvider({
resource: resourceFromAttributes({ "service.name": SERVICE_NAME }),
spanProcessors: [new BatchSpanProcessor(exporter)],
});

trace.setGlobalTracerProvider(provider);
tracer = provider.getTracer(SERVICE_NAME);
}

/**
* Starts a span, or returns undefined when tracing is not configured. Callers
* own the returned span and must end it.
*/
export function startSpan(name: string, attributes?: Attributes): Span | undefined {
if (!tracer) {
return undefined;
}

if (attributes) {
return tracer.startSpan(name, { attributes });
}

return tracer.startSpan(name);
}
Loading