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:
@@ -1,21 +1,99 @@
|
||||
import { pino } from 'pino'
|
||||
import { AsyncLocalStorage } from 'node:async_hooks'
|
||||
|
||||
import {
|
||||
configure,
|
||||
getConsoleSink,
|
||||
getLogger,
|
||||
isLogLevel,
|
||||
jsonLinesFormatter,
|
||||
type Logger,
|
||||
type LogLevel,
|
||||
type Sink,
|
||||
} from '@logtape/logtape'
|
||||
import { getOpenTelemetrySink } from '@logtape/otel'
|
||||
import { getPrettyFormatter } from '@logtape/pretty'
|
||||
|
||||
import { getOpenObserveConfig, SERVICE_NAME } from '@/lib/openobserve'
|
||||
|
||||
export type { Logger } from '@logtape/logtape'
|
||||
|
||||
const isProduction = process.env.NODE_ENV === 'production'
|
||||
|
||||
/**
|
||||
* Single logger instance for the whole API. Import it wherever you need to log —
|
||||
* never use `console.log` in the backend.
|
||||
* Root logger of the API (category `superlist`). Import it wherever you need to
|
||||
* log — never use `console.log` in the backend. Inside a request, prefer
|
||||
* `c.get('logger')`; either way every record emitted while the request runs
|
||||
* carries its `requestId` (see `withContext` in `app.ts`).
|
||||
*
|
||||
* LogTape loggers are inert until `configureLogging()` runs (from `index.ts`),
|
||||
* so tests that import modules using it stay silent.
|
||||
*/
|
||||
export const logger = pino({
|
||||
level: process.env.LOG_LEVEL || (isProduction ? 'info' : 'debug'),
|
||||
...(isProduction
|
||||
? {}
|
||||
: {
|
||||
transport: {
|
||||
target: 'pino-pretty',
|
||||
options: { colorize: true, translateTime: 'HH:MM:ss', ignore: 'pid,hostname' },
|
||||
},
|
||||
}),
|
||||
})
|
||||
export const logger: Logger = getLogger(['superlist'])
|
||||
|
||||
export type Logger = typeof logger
|
||||
/** Accepts LogTape levels plus Pino-style aliases (`warn`) for `LOG_LEVEL`. */
|
||||
function resolveLevel(value: string | undefined): LogLevel {
|
||||
const level = value?.trim().toLowerCase()
|
||||
if (level === 'warn') return 'warning'
|
||||
if (level && isLogLevel(level)) return level
|
||||
|
||||
return isProduction ? 'info' : 'debug'
|
||||
}
|
||||
|
||||
/**
|
||||
* Ships logs to OpenObserve over OTLP/HTTP (`/api/<org>/v1/logs`), routed to a
|
||||
* stream by the `stream-name` header. Returns `null` when it is not configured.
|
||||
*/
|
||||
function openObserveSink(): Sink | null {
|
||||
const config = getOpenObserveConfig()
|
||||
if (!config) return null
|
||||
|
||||
return getOpenTelemetrySink({
|
||||
serviceName: SERVICE_NAME,
|
||||
// Nested property objects become JSON instead of util.inspect output.
|
||||
objectRenderer: 'json',
|
||||
otlpExporterConfig: {
|
||||
url: `${config.otlpBaseUrl}/v1/logs`,
|
||||
headers: { Authorization: config.authorization, 'stream-name': config.logStream },
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures LogTape once, at startup: console output (pretty in development,
|
||||
* JSON lines in production) plus OpenObserve when `OPENOBSERVE_URL` is set.
|
||||
* Call `dispose()` from `@logtape/logtape` on shutdown to flush pending records.
|
||||
*/
|
||||
export async function configureLogging(): Promise<void> {
|
||||
const consoleSink = getConsoleSink({
|
||||
formatter: isProduction
|
||||
? jsonLinesFormatter
|
||||
: getPrettyFormatter({
|
||||
properties: true,
|
||||
categoryWidth: 16,
|
||||
wordWrap: false,
|
||||
// Interpolate strings bare ("GET /api/lists") instead of quoted.
|
||||
value: 'bare',
|
||||
}),
|
||||
})
|
||||
const openObserve = openObserveSink()
|
||||
|
||||
const sinks: Record<string, Sink> = { console: consoleSink }
|
||||
if (openObserve) sinks.openObserve = openObserve
|
||||
|
||||
await configure({
|
||||
sinks,
|
||||
contextLocalStorage: new AsyncLocalStorage(),
|
||||
loggers: [
|
||||
{
|
||||
category: ['superlist'],
|
||||
sinks: Object.keys(sinks),
|
||||
lowestLevel: resolveLevel(process.env.LOG_LEVEL),
|
||||
},
|
||||
{ category: ['logtape', 'meta'], sinks: ['console'], lowestLevel: 'warning' },
|
||||
],
|
||||
})
|
||||
|
||||
if (openObserve) {
|
||||
logger.info('shipping logs to OpenObserve at {url}', { url: process.env.OPENOBSERVE_URL })
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user