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:
@@ -4,8 +4,18 @@ CORS_ORIGIN="http://localhost:7153"
|
||||
BETTER_AUTH_SECRET="change-me-with-openssl-rand-base64-32"
|
||||
BETTER_AUTH_URL="http://localhost:4100"
|
||||
NODE_ENV="development"
|
||||
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
||||
# Optional: log level (trace, debug, info, warning, error, fatal) (defaults to "debug" outside production, "info" in production)
|
||||
# LOG_LEVEL="info"
|
||||
# Optional: ship logs to OpenObserve over OTLP/HTTP. Without OPENOBSERVE_URL logs only go to the console.
|
||||
# OPENOBSERVE_URL="http://localhost:5080"
|
||||
# Optional: organization (defaults to "default") and stream (defaults to "superlist")
|
||||
# OPENOBSERVE_ORG="default"
|
||||
# OPENOBSERVE_STREAM="superlist"
|
||||
# OpenObserve user email and password (sent as Basic auth)
|
||||
# OPENOBSERVE_USER="root@example.com"
|
||||
# OPENOBSERVE_PASSWORD=""
|
||||
# Optional: how often HTTP metrics are pushed to OpenObserve, in milliseconds (defaults to 15000)
|
||||
# METRICS_EXPORT_INTERVAL_MS="15000"
|
||||
# Resend API key used to send invitation and password reset emails. Without it, emails are logged instead.
|
||||
# RESEND_API_KEY="re_xxxxxxxx"
|
||||
# From address for outgoing email (must be a verified Resend sender)
|
||||
|
||||
@@ -18,14 +18,19 @@
|
||||
"dependencies": {
|
||||
"@better-auth/passkey": "1.7.7",
|
||||
"@hono/zod-validator": "^0.9.1",
|
||||
"@logtape/logtape": "^2.4.2",
|
||||
"@logtape/otel": "^2.4.2",
|
||||
"@logtape/pretty": "^2.4.2",
|
||||
"@opentelemetry/api": "1.9.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-http": "0.208.0",
|
||||
"@opentelemetry/resources": "2.2.0",
|
||||
"@opentelemetry/sdk-metrics": "2.2.0",
|
||||
"@prisma/adapter-pg": "^7.10.0",
|
||||
"@prisma/client": "^7.10.0",
|
||||
"@superlist/shared": "workspace:*",
|
||||
"better-auth": "^1.7.7",
|
||||
"hono": "^4.13.13",
|
||||
"pg": "^8.23.1",
|
||||
"pino": "^10.4.0",
|
||||
"pino-pretty": "^13.2.0",
|
||||
"resend": "^6.32.1",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
import { withContext } from '@logtape/logtape'
|
||||
import { Hono } from 'hono'
|
||||
import { cors } from 'hono/cors'
|
||||
import { requestId } from 'hono/request-id'
|
||||
import { routePath } from 'hono/route'
|
||||
import { secureHeaders } from 'hono/secure-headers'
|
||||
|
||||
import { auth } from '@/lib/auth'
|
||||
import { logger } from '@/lib/logger'
|
||||
import { httpMetrics } from '@/lib/metrics'
|
||||
import { errorHandler, notFoundHandler } from '@/lib/problem-details'
|
||||
import { healthModule } from '@/modules/health'
|
||||
import { invitationsModule } from '@/modules/invitations'
|
||||
import { listsModule } from '@/modules/lists'
|
||||
import { voiceModule } from '@/modules/voice'
|
||||
import type { AppEnv } from '@/types'
|
||||
import type { AppEnv, SessionUser } from '@/types'
|
||||
|
||||
const httpLogger = logger.getChild('http')
|
||||
|
||||
const allowedOrigins = (process.env.CORS_ORIGIN ?? 'http://localhost:7153')
|
||||
.split(',')
|
||||
@@ -24,20 +29,53 @@ export function createApp() {
|
||||
app.use(cors({ origin: allowedOrigins, credentials: true }))
|
||||
app.use(requestId())
|
||||
app.use(async (c, next) => {
|
||||
const requestLogger = logger.child({ requestId: c.get('requestId') })
|
||||
c.set('logger', requestLogger)
|
||||
const requestId = c.get('requestId')
|
||||
c.set('logger', httpLogger.with({ requestId }))
|
||||
|
||||
const http = httpMetrics()
|
||||
const method = c.req.method
|
||||
http.activeRequests.add(1, { 'http.request.method': method })
|
||||
|
||||
const start = performance.now()
|
||||
await next()
|
||||
requestLogger.info(
|
||||
{
|
||||
method: c.req.method,
|
||||
path: c.req.path,
|
||||
status: c.res.status,
|
||||
durationMs: Math.round(performance.now() - start),
|
||||
},
|
||||
'request',
|
||||
)
|
||||
try {
|
||||
// Every record logged while the request runs (module loggers included)
|
||||
// inherits the requestId through LogTape's implicit context.
|
||||
await withContext({ requestId }, next)
|
||||
} finally {
|
||||
http.activeRequests.add(-1, { 'http.request.method': method })
|
||||
}
|
||||
const elapsedMs = performance.now() - start
|
||||
const durationMs = Math.round(elapsedMs * 10) / 10
|
||||
|
||||
const status = c.res.status
|
||||
const route = routePath(c, -1)
|
||||
// SSE streams (/events) return their Response right away, so for them this is
|
||||
// the time to open the stream, not the lifetime of the connection.
|
||||
http.duration.record(elapsedMs / 1000, {
|
||||
'http.request.method': method,
|
||||
// The Hono pattern (/api/lists/:listId), never the raw path, to keep cardinality low.
|
||||
'http.route': route,
|
||||
'http.response.status_code': status,
|
||||
})
|
||||
|
||||
const userId = (c.get('user') as SessionUser | undefined)?.id
|
||||
const properties = {
|
||||
requestId,
|
||||
method,
|
||||
path: c.req.path,
|
||||
route,
|
||||
status,
|
||||
durationMs,
|
||||
userAgent: c.req.header('user-agent'),
|
||||
...(userId && { userId }),
|
||||
}
|
||||
const message = '{method} {path} {status} in {durationMs} ms'
|
||||
|
||||
if (status >= 500) httpLogger.error(message, properties)
|
||||
else if (status >= 400) httpLogger.warn(message, properties)
|
||||
// The container healthcheck hits /api/health every 10 s.
|
||||
else if (c.req.path === '/api/health') httpLogger.debug(message, properties)
|
||||
else httpLogger.info(message, properties)
|
||||
})
|
||||
|
||||
// Every API route lives under /api: in production nginx serves the SPA on the
|
||||
|
||||
@@ -1,11 +1,25 @@
|
||||
import { dispose } from '@logtape/logtape'
|
||||
|
||||
import { createApp } from '@/app'
|
||||
import { logger } from '@/lib/logger'
|
||||
import { configureLogging, logger } from '@/lib/logger'
|
||||
import { configureMetrics, shutdownMetrics } from '@/lib/metrics'
|
||||
|
||||
await configureLogging()
|
||||
const metricsEnabled = configureMetrics()
|
||||
|
||||
const port = Number(process.env.PORT ?? 4100)
|
||||
|
||||
const app = createApp()
|
||||
|
||||
logger.info({ port }, 'api listening')
|
||||
logger.info('api listening on port {port}', { port, metricsEnabled })
|
||||
|
||||
// Flush buffered logs and the last metrics batch before exiting.
|
||||
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
||||
process.once(signal, async () => {
|
||||
await Promise.allSettled([shutdownMetrics(), dispose()])
|
||||
process.exit(0)
|
||||
})
|
||||
}
|
||||
|
||||
export default {
|
||||
port,
|
||||
|
||||
@@ -55,7 +55,7 @@ export const auth = betterAuth({
|
||||
to: email,
|
||||
...passwordResetEmail({ otp, expiresInMinutes: OTP_EXPIRES_IN_SECONDS / 60 }),
|
||||
}).catch((error: unknown) => {
|
||||
logger.error({ err: error, to: email }, 'failed to send the password reset email')
|
||||
logger.error('failed to send the password reset email', { error, to: email })
|
||||
})
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,17 +24,18 @@ function getClient(): Resend | null {
|
||||
|
||||
/**
|
||||
* Sends an email through Resend. Without `RESEND_API_KEY` (local development)
|
||||
* it logs the message with Pino instead of sending it, so invitation links are
|
||||
* it logs the message instead of sending it, so invitation links are
|
||||
* still discoverable in the terminal.
|
||||
*/
|
||||
export async function sendEmail(email: Email): Promise<void> {
|
||||
const resend = getClient()
|
||||
|
||||
if (!resend) {
|
||||
logger.info(
|
||||
{ to: email.to, subject: email.subject, text: email.text },
|
||||
'email not sent (RESEND_API_KEY is not set) — logging payload instead',
|
||||
)
|
||||
logger.info('email not sent (RESEND_API_KEY is not set) — logging payload instead', {
|
||||
to: email.to,
|
||||
subject: email.subject,
|
||||
text: email.text,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
}
|
||||
30
apps/api/src/lib/openobserve.ts
Normal file
30
apps/api/src/lib/openobserve.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
/** Service name reported to OpenObserve for logs and metrics. */
|
||||
export const SERVICE_NAME = 'superlist-api'
|
||||
|
||||
export type OpenObserveConfig = {
|
||||
/** Base of the OTLP/HTTP endpoints: `<OPENOBSERVE_URL>/api/<org>` (append `/v1/logs`, `/v1/metrics`). */
|
||||
otlpBaseUrl: string
|
||||
/** Basic auth (user email + password) for every OTLP request. */
|
||||
authorization: string
|
||||
/** Stream that receives the logs (`stream-name` header); metrics get one stream per metric. */
|
||||
logStream: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the OpenObserve settings from the environment, or `null` when
|
||||
* `OPENOBSERVE_URL` is not set (logs and metrics then stay local).
|
||||
*/
|
||||
export function getOpenObserveConfig(): OpenObserveConfig | null {
|
||||
const baseUrl = process.env.OPENOBSERVE_URL?.trim().replace(/\/+$/, '')
|
||||
if (!baseUrl) return null
|
||||
|
||||
const org = process.env.OPENOBSERVE_ORG || 'default'
|
||||
const user = process.env.OPENOBSERVE_USER ?? ''
|
||||
const password = process.env.OPENOBSERVE_PASSWORD ?? ''
|
||||
|
||||
return {
|
||||
otlpBaseUrl: `${baseUrl}/api/${org}`,
|
||||
authorization: `Basic ${btoa(`${user}:${password}`)}`,
|
||||
logStream: process.env.OPENOBSERVE_STREAM || 'superlist',
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ export function errorHandler(error: Error, c: Context) {
|
||||
)
|
||||
}
|
||||
|
||||
logger.error({ err: error, path: c.req.path }, 'unhandled error')
|
||||
logger.error('unhandled error on {path}', { error, path: c.req.path })
|
||||
|
||||
return problemResponse(
|
||||
c,
|
||||
|
||||
@@ -137,7 +137,7 @@ export class CreateInvitation {
|
||||
|
||||
// Best effort: the person already sees the list, so a mail failure is not fatal.
|
||||
await this.mailer(message).catch((error: unknown) => {
|
||||
logger.warn({ err: error, to: email }, 'could not send the invitation email')
|
||||
logger.warn('could not send the invitation email', { error, to: email })
|
||||
})
|
||||
|
||||
return Ok({ status: 'added', email })
|
||||
@@ -148,7 +148,7 @@ export class CreateInvitation {
|
||||
} catch (error) {
|
||||
// Without the email the invitee cannot know about the list: undo everything.
|
||||
await this.db.shoppingListInvitation.delete({ where: { id: invitation.id } })
|
||||
logger.error({ err: error, to: email }, 'failed to send the invitation email')
|
||||
logger.error('failed to send the invitation email', { error, to: email })
|
||||
|
||||
return Failure(
|
||||
problems.unavailable('No pudimos enviar la invitación por correo. Inténtalo de nuevo.'),
|
||||
|
||||
@@ -47,7 +47,10 @@ export class SplitVoiceText {
|
||||
}
|
||||
|
||||
private fallback(text: string, reason: string): Result<VoiceSplitResponse, ProblemDetails> {
|
||||
this.logger.warn({ reason, textLength: text.length }, 'voice split: using the fallback split')
|
||||
this.logger.warn('voice split: using the fallback split ({reason})', {
|
||||
reason,
|
||||
textLength: text.length,
|
||||
})
|
||||
|
||||
return Ok({ items: fallbackSplit(text) })
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user