Skip to content

Request Logging & Metrics ​

Three independent options:

  • Wide events with evlog: one structured event per request, with the fields of the server. The standalone server always has it, and Nuxt apps opt in.
  • Request logging into a collection of the database
  • Metrics for Prometheus

Request logging and metrics are features that are switched on per host, see Switching the features on.

Wide events (evlog) ​

Every request becomes one structured event. evlog writes the HTTP part (method, path, status, duration), and the server adds its own fields under mongocamp:

json
{
  "level": "info",
  "service": "mongocamp-nitro-server",
  "method": "GET",
  "path": "/mongodb/collections/books/documents",
  "status": 200,
  "durationMs": 13,
  "requestId": "1aa6180c-00eb-4fe1-9018-ef865cea85f9",
  "mongocamp": {
    "requestId": "1aa6180c-00eb-4fe1-9018-ef865cea85f9",
    "operation": "listDocuments",
    "controller": "Document",
    "user": "admin",
    "collection": "books",
    "rows": 120
  }
}
FieldContent
operation, controlleroperationId and group of the REST API (NOT_SET for unknown routes)
userthe user the request was authenticated as (missing for public routes and invalid credentials)
collection, bucket, databasethe resource in the path
rowsall matching rows of a paged list
errorCode, errorMessagex-error-code and x-error-message of an error answer

The request id is shared: the event, the x-request-id header and the events of the server use the same one.

Standalone server ​

The image ships with evlog. It writes JSON lines to stdout in production (NODE_ENV=production, the default of the image) and a readable format in development. Nothing needs to be configured. To send the events somewhere else, use one of evlog's drains (OTLP, Loki, Datadog, Sentry, Axiom, files, ...). Drains need a host of your own, see below.

Nuxt app ​

Add evlog to your application. The embedded API picks it up automatically:

bash
pnpm add evlog
ts
// nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@sfxcode/nuxt-mongocamp-server', 'evlog/nuxt'],
  mongocamp: { server: { enabled: true } },
})

Requests to /api/mongocamp-server/** then carry the mongocamp fields in the app's own events, next to whatever your routes add with useLogger(event).set(...). Without evlog/nuxt nothing changes, because the module does not depend on evlog. Calls of the server composables are answered in-process without an HTTP request, so they appear in the event of the request that made them.

Own host ​

The core takes the event of the request and its id as options of fetch, and a logger for its own messages (start, failed jobs, 5xx errors). Anything with set(fields) works as the event, and anything with info, warn and error works as the logger:

ts
import { createMongocampServer } from '@sfxcode/mongocamp-server-core'
import { createRequestLogger, initLogger, log } from 'evlog'

initLogger({ env: { service: 'my-api' } })

const server = await createMongocampServer({
  logger: {
    info: message => log.info('mongocamp', message),
    warn: message => log.warn('mongocamp', message),
    error: (message, error) => log.error({ action: 'mongocamp', message, error: String(error) }),
  },
})

export default {
  async fetch(request: Request) {
    const requestLog = createRequestLogger({ method: request.method, path: new URL(request.url).pathname })
    const response = await server.fetch(request, { log: requestLog })
    requestLog.emit({ status: response.status })
    return response
  },
}

apps/server/server.ts is the complete example on Nitro 3 with evlog/nitro/v3. Without logger the core writes to console.

Switching the features on ​

HostRequest loggingMetrics
Nuxt modulemongocamp.server.requestLogging: truemongocamp.server.metrics: true
Standalone serverREQUESTLOGGING_ENABLED=trueMETRICS_ENABLED=true
Any Nitro pluginserver.use(requestLogging()) on mongocamp:readyserver.use(metrics()) on mongocamp:ready
ts
// server/plugins/monitoring.ts: the same as the module options, by hand
import { metrics, requestLogging } from '@sfxcode/mongocamp-server-core'
import { definePlugin } from 'nitro'

export default definePlugin((nitroApp) => {
  nitroApp.hooks.hook('mongocamp:ready', async (server) => {
    await server.use(requestLogging())
    if (process.env.NODE_ENV === 'production')
      await server.use(metrics())
  })
})

Both are off by default. The standalone server reads the two settings in its own Nitro plugin (apps/server/plugins/features.ts); a value stored in the database switches them on there as well.

Embedded servers (3.0)

An embedded server (Nuxt module, own host) no longer switches the features on from REQUESTLOGGING_ENABLED / METRICS_ENABLED (deprecated in 2.1, removed in 3.0): use the module options or a plugin. The option featureSwitches of createMongocampServer is gone.

Request logging ​

Every request is written as a document into <AUTH_PREFIX>request_logging (mc_request_logging).

For your own log format, listen to http:requestCompleted instead (see Events).

Metrics ​

The routes answer 404 while the feature is off.

RouteContent
GET /system/monitoring/runtimeNode.js runtime metrics (nodejs_*)
GET /system/monitoring/systemprocess and host metrics
GET /system/monitoring/mongodbMongoDB metrics selected by METRICS_MONGODB_*
GET /system/monitoring/eventscounters of the events
GET /system/monitoring/prometheuseverything in Prometheus text format

All routes need an administrator. To let Prometheus scrape them, give it a user with an API key:

yaml
scrape_configs:
  - job_name: mongocamp
    metrics_path: /system/monitoring/prometheus
    static_configs:
      - targets: ['mongocamp:8080']
    http_headers:
      X-AUTH-APIKEY:
        values: ['<api key of an admin user>']

MongoDB metrics ​

Select the groups with METRICS_MONGODB_DATABASE, _COLLECTIONS (a list of names), _CONNECTIONS, _NETWORK, _OPERATION, _SERVER, _COMMAND and _CONNECTIONPOOL.

Snapshots in the database ​

LOGGING_METRICS_MONGODB_RUNTIME, _SYSTEM, _MONGO and _EVENT write a snapshot of their category into monitoring_* collections every LOGGING_METRICS_MONGODB_STEP (default 60 minutes).

Released under the MIT License.