Obs Middleware

Functions

Functions

generateRequestId

Generate a unique request ID

Signature:

generateRequestId(): string

Returns:

string -

getContext

Get the current request context (if any)

Signature:

getContext(): RequestContext | undefined

Returns:

RequestContext \| undefined -

createAsyncContextMiddleware

Create async context middleware Extracts context from headers and makes it available throughout the request.

Note: The middleware calls next() synchronously within AsyncLocalStorage.run(). This ensures the async context is available throughout the entire request lifecycle, including in async handlers. The context remains available in any code that runs as part of this request, regardless of whether it's sync or async.

Signature:

createAsyncContextMiddleware(): Middleware

Returns:

Middleware -

shouldLog

Check if a log level should be logged given the configured minimum level

Signature:

shouldLog(level: LogLevel, minLevel: LogLevel): boolean

Parameters:

ParameterTypeRequiredDescription
levelLogLevelYes
minLevelLogLevelYes

Returns:

boolean -

resolveConfig

Resolve configuration from options and environment variables

Signature:

resolveConfig(options: ObsMiddlewareOptions): ResolvedConfig

Parameters:

ParameterTypeRequiredDescription
optionsObsMiddlewareOptionsYes

Returns:

ResolvedConfig -

createErrorHandler

Create error handler middleware Should be attached last in the middleware chain

Signature:

createErrorHandler(config: ResolvedConfig, client: ObsClient | null): ErrorMiddleware

Parameters:

ParameterTypeRequiredDescription
configResolvedConfigYes
clientObsClient | nullYes

Returns:

ErrorMiddleware -

createHealthCheck

Create a health check endpoint factory

Returns a curried function that can be configured with options and returns an Express request handler.

Signature:

createHealthCheck(config: ResolvedConfig, client: ObsClient | null): (options?: HealthCheckOptions) => (req: Request, res: Response) => Promise<void>

Parameters:

ParameterTypeRequiredDescription
configResolvedConfigYes- Resolved middleware configuration
clientObsClient | nullYes- ObsClient instance (may be null if not configured)

Returns:

(options?: HealthCheckOptions) => (req: Request, res: Response) => Promise<void> - Health check endpoint factory function

Examples:

const { healthCheck } = createObsMiddleware({ projectId: 'my-service' });

// Basic health check
app.get('/health', healthCheck());

// With custom checks
app.get('/health', healthCheck({
  customChecks: [
    {
      name: 'database',
      check: async () => {
        const connected = await db.ping();
        return { healthy: connected };
      },
    },
  ],
}));

createLogger

Creates a structured logger with batching support for observability.

The logger outputs to console immediately and buffers entries for batch sending to obs-server when enabled. Log levels are filtered based on the configured minimum level.

Signature:

createLogger(config: ResolvedConfig, client: ObsClient | null): Logger

Parameters:

ParameterTypeRequiredDescription
configResolvedConfigYes- Resolved configuration from resolveConfig()
clientObsClient | nullYes- ObsClient instance or null if obs-server unavailable

Returns:

Logger - Logger instance with debug, info, warn, error, and flush methods

createObsMiddleware

Create the complete observability middleware suite

This factory function initializes all observability components:

  • Async context middleware for request-scoped data
  • Request logger for HTTP request/response logging
  • Error handler for capturing and reporting errors
  • Structured logger for application-level logging
  • Health check endpoint factory

Signature:

createObsMiddleware(options: ObsMiddlewareOptions): ObsMiddlewareSuite

Parameters:

ParameterTypeRequiredDescription
optionsObsMiddlewareOptionsYes- Configuration options including projectId

Returns:

ObsMiddlewareSuite - Complete middleware suite ready to attach to Express app

Examples:

const obs = createObsMiddleware({ projectId: 'my-service' });

app.use(obs.asyncContext);
app.use(obs.requestLogger);
// ... routes ...
app.use(obs.errorHandler);

obs.logger.info('Server started', { port: 3000 });

createRequestLogger

Create request logging middleware that logs HTTP requests on response finish.

Features:

  • Logs method, path, statusCode, duration, and contentLength
  • Uses appropriate log level based on status code:
    • 2xx/3xx: info
    • 4xx: warn
    • 5xx: error
  • Skips health check and metrics endpoints to reduce log noise

Signature:

createRequestLogger(_config: ResolvedConfig, logger: Logger): Middleware

Parameters:

ParameterTypeRequiredDescription
_configResolvedConfigYes- Resolved configuration (included for consistency, not currently used)
loggerLoggerYes- Logger instance to use for logging

Returns:

Middleware - Express middleware function

Examples:

const logger = createLogger(config);
const requestLogger = createRequestLogger(config, logger);

app.use(requestLogger);
Previous
Types