feat(api): ship logs and HTTP metrics to OpenObserve
Replace Pino with LogTape and add OpenTelemetry metrics, both pushed to
OpenObserve over OTLP/HTTP when OPENOBSERVE_URL is set (console only otherwise).
- lib/logger.ts: console sink (pretty in dev, JSON lines in production) plus an
OpenObserve sink via @logtape/otel. Each request runs inside
withContext({ requestId }), so every record logged during it carries the id.
- The request middleware logs method, path, route pattern, status, durationMs,
userId and user agent, at error/warning/info by status (/api/health at debug).
- lib/metrics.ts: http.server.request.duration (histogram, 5 ms to 10 s) and
http.server.active_requests, attributed by method, route pattern and status,
exported every METRICS_EXPORT_INTERVAL_MS (15 s).
- lib/openobserve.ts holds the shared endpoint and Basic auth settings; logs and
metrics are flushed on SIGINT/SIGTERM.
- docs/openobserve-dashboard.md explains the dashboard and its queries, and
docs/openobserve-dashboard.json can be imported as is.
- New variables are declared in turbo.json, the .env examples and the compose.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
92
apps/api/src/lib/metrics.ts
Normal file
92
apps/api/src/lib/metrics.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { type Histogram, metrics, type UpDownCounter } from '@opentelemetry/api'
|
||||
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'
|
||||
import { resourceFromAttributes } from '@opentelemetry/resources'
|
||||
import {
|
||||
AggregationTemporality,
|
||||
AggregationType,
|
||||
MeterProvider,
|
||||
PeriodicExportingMetricReader,
|
||||
} from '@opentelemetry/sdk-metrics'
|
||||
|
||||
import { getOpenObserveConfig, SERVICE_NAME } from '@/lib/openobserve'
|
||||
|
||||
const DEFAULT_EXPORT_INTERVAL_MS = 15_000
|
||||
|
||||
/** Bucket bounds (seconds) of the request duration histogram: 5 ms … 10 s. */
|
||||
const DURATION_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
|
||||
|
||||
let provider: MeterProvider | null = null
|
||||
|
||||
/**
|
||||
* Starts exporting metrics to OpenObserve (`/api/<org>/v1/metrics`) every
|
||||
* `METRICS_EXPORT_INTERVAL_MS` (15 s by default). Without `OPENOBSERVE_URL` the
|
||||
* global meter stays a no-op, so instruments cost nothing in tests or locally.
|
||||
*/
|
||||
export function configureMetrics(): boolean {
|
||||
const config = getOpenObserveConfig()
|
||||
if (!config) return false
|
||||
|
||||
const exporter = new OTLPMetricExporter({
|
||||
url: `${config.otlpBaseUrl}/v1/metrics`,
|
||||
headers: { Authorization: config.authorization },
|
||||
// Cumulative is what OpenObserve's PromQL (rate, histogram_quantile) expects.
|
||||
temporalityPreference: AggregationTemporality.CUMULATIVE,
|
||||
})
|
||||
|
||||
provider = new MeterProvider({
|
||||
resource: resourceFromAttributes({ 'service.name': SERVICE_NAME }),
|
||||
views: [
|
||||
{
|
||||
instrumentName: 'http.server.request.duration',
|
||||
aggregation: {
|
||||
type: AggregationType.EXPLICIT_BUCKET_HISTOGRAM,
|
||||
options: { boundaries: DURATION_BUCKETS },
|
||||
},
|
||||
},
|
||||
],
|
||||
readers: [
|
||||
new PeriodicExportingMetricReader({
|
||||
exporter,
|
||||
exportIntervalMillis:
|
||||
Number(process.env.METRICS_EXPORT_INTERVAL_MS) || DEFAULT_EXPORT_INTERVAL_MS,
|
||||
}),
|
||||
],
|
||||
})
|
||||
metrics.setGlobalMeterProvider(provider)
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/** Flushes the last batch and stops the exporter (call on shutdown). */
|
||||
export async function shutdownMetrics(): Promise<void> {
|
||||
await provider?.shutdown()
|
||||
}
|
||||
|
||||
type HttpInstruments = {
|
||||
duration: Histogram
|
||||
activeRequests: UpDownCounter
|
||||
}
|
||||
|
||||
let http: HttpInstruments | null = null
|
||||
|
||||
/**
|
||||
* HTTP server instruments, following the OpenTelemetry semantic conventions.
|
||||
* Created lazily so they bind to the provider set by `configureMetrics()`.
|
||||
*/
|
||||
export function httpMetrics(): HttpInstruments {
|
||||
if (!http) {
|
||||
const meter = metrics.getMeter(SERVICE_NAME)
|
||||
http = {
|
||||
duration: meter.createHistogram('http.server.request.duration', {
|
||||
description: 'Duration of HTTP server requests.',
|
||||
unit: 's',
|
||||
}),
|
||||
activeRequests: meter.createUpDownCounter('http.server.active_requests', {
|
||||
description: 'Number of HTTP server requests in flight.',
|
||||
unit: '{request}',
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
return http
|
||||
}
|
||||
Reference in New Issue
Block a user