BSB Node.js Type Definitions
    Preparing search index...

    Interface Observable<TAttributeSchema>

    Observable context for unified observability across logging, metrics, and tracing.

    Observable replaces DTrace in the public API and provides a unified interface for:

    • Structured logging with automatic trace context
    • Metrics creation with resource context
    • Distributed tracing with W3C trace context
    • Attribute propagation to child spans
    // In a service plugin
    public async run(obs: Observable) {
    // Logging
    obs.log.info("Starting service");

    // Set attributes for all child operations
    const withUser = obs.setAttribute("user.id", "123");

    // Create child span
    const childObs = withUser.startSpan("database-query");
    childObs.log.debug("Querying database");
    // ... do work ...
    childObs.end();
    }
    interface Observable<TAttributeSchema extends z.ZodSchema = z.ZodAny> {
        trace: DTrace;
        traceId: string;
        spanId: string;
        resource: ResourceContext;
        attributes: Record<string, string | number | boolean>;
        log: {
            debug<T extends string>(message: T, ...meta: SmartLogMeta<T>): void;
            info<T extends string>(message: T, ...meta: SmartLogMeta<T>): void;
            warn<T extends string>(message: T, ...meta: SmartLogMeta<T>): void;
            error<T extends string>(
                messageOrError: Error | T,
                ...meta: SmartLogMeta<T>,
            ): void;
        };
        metrics: {
            counter<LABELS extends string | undefined>(
                name: string,
                description: string,
                help: string,
                labels?: LABELS[],
            ): Counter<LABELS>;
            gauge<LABELS extends string | undefined>(
                name: string,
                description: string,
                help: string,
                labels?: LABELS[],
            ): Gauge<LABELS>;
            histogram<LABELS extends string | undefined>(
                name: string,
                description: string,
                help: string,
                boundaries?: number[],
                labels?: LABELS[],
            ): Histogram<LABELS>;
            timer(): Timer;
        };
        startSpan(
            name: string,
            attributes?: Record<string, string | number | boolean>,
        ): Observable<TAttributeSchema>;
        setAttribute<K extends string, V extends string | number | boolean>(
            key: K,
            value: V,
        ): Observable<TAttributeSchema>;
        setAttributes(
            attrs: Record<string, string | number | boolean>,
        ): Observable<TAttributeSchema>;
        error(
            error: Error,
            attributes?: Record<string, string | number | boolean>,
        ): void;
        end(attributes?: Record<string, string | number | boolean>): void;
    }

    Type Parameters

    • TAttributeSchema extends z.ZodSchema = z.ZodAny

    Implemented by

    Index

    Properties

    trace: DTrace

    Core trace information (W3C compatible)

    traceId: string

    Trace ID (unique identifier for the entire trace)

    spanId: string

    Span ID (unique identifier for this specific span)

    resource: ResourceContext

    Resource context (service name, version, instance ID, environment, region) Automatically populated from plugin configuration

    attributes: Record<string, string | number | boolean>

    Custom attributes attached to this observable Attributes are immutable - use setAttribute() to create new observable with additional attributes

    log: {
        debug<T extends string>(message: T, ...meta: SmartLogMeta<T>): void;
        info<T extends string>(message: T, ...meta: SmartLogMeta<T>): void;
        warn<T extends string>(message: T, ...meta: SmartLogMeta<T>): void;
        error<T extends string>(
            messageOrError: Error | T,
            ...meta: SmartLogMeta<T>,
        ): void;
    }

    Logging methods with automatic trace context

    All log methods automatically include trace context (trace ID, span ID) in the output. Logs support placeholder syntax for structured logging.

    Type Declaration

    • debug: function
      • Log a debug message

        Type Parameters

        • T extends string

        Parameters

        • message: T

          The message to log with optional {placeholder} syntax

        • ...meta: SmartLogMeta<T>

          Metadata to replace placeholders and add to log

        Returns void

    • info: function
      • Log an info message

        Type Parameters

        • T extends string

        Parameters

        • message: T

          The message to log with optional {placeholder} syntax

        • ...meta: SmartLogMeta<T>

          Metadata to replace placeholders and add to log

        Returns void

    • warn: function
      • Log a warning message

        Type Parameters

        • T extends string

        Parameters

        • message: T

          The message to log with optional {placeholder} syntax

        • ...meta: SmartLogMeta<T>

          Metadata to replace placeholders and add to log

        Returns void

    • error: function
      • Log an error message or BSBError

        Type Parameters

        • T extends string

        Parameters

        • messageOrError: Error | T

          Either a message string or BSBError instance

        • ...meta: SmartLogMeta<T>

          Metadata (only used if first arg is a message)

        Returns void

    obs.log.debug("Processing {count} items", { count: 10 });
    obs.log.info("Request started");
    obs.log.warn("Rate limit approaching");
    obs.log.error("Failed to connect to database");
    metrics: {
        counter<LABELS extends string | undefined>(
            name: string,
            description: string,
            help: string,
            labels?: LABELS[],
        ): Counter<LABELS>;
        gauge<LABELS extends string | undefined>(
            name: string,
            description: string,
            help: string,
            labels?: LABELS[],
        ): Gauge<LABELS>;
        histogram<LABELS extends string | undefined>(
            name: string,
            description: string,
            help: string,
            boundaries?: number[],
            labels?: LABELS[],
        ): Histogram<LABELS>;
        timer(): Timer;
    }

    Metrics methods for creating counters, gauges, histograms, and timers

    Type Declaration

    • counter: function
      • Create a counter metric

        Type Parameters

        • LABELS extends string | undefined

        Parameters

        • name: string

          Metric name

        • description: string

          Short description

        • help: string

          Detailed help text

        • Optionallabels: LABELS[]

          Optional label names

        Returns Counter<LABELS>

    • gauge: function
      • Create a gauge metric

        Type Parameters

        • LABELS extends string | undefined

        Parameters

        • name: string

          Metric name

        • description: string

          Short description

        • help: string

          Detailed help text

        • Optionallabels: LABELS[]

          Optional label names

        Returns Gauge<LABELS>

    • histogram: function
      • Create a histogram metric

        Type Parameters

        • LABELS extends string | undefined

        Parameters

        • name: string

          Metric name

        • description: string

          Short description

        • help: string

          Detailed help text

        • Optionalboundaries: number[]

          Optional histogram boundaries

        • Optionallabels: LABELS[]

          Optional label names

        Returns Histogram<LABELS>

    • timer: function
      • Create a timer to measure elapsed time

        Returns Timer

    // Counter for tracking requests
    const requests = obs.metrics.counter(
    "requests_total",
    "Total requests",
    "Count of all incoming requests",
    ["method", "status"]
    );
    requests.increment(1, { method: "GET", status: "200" });

    // Timer for measuring duration
    const timer = obs.metrics.timer();
    await processRequest();
    const duration = timer.stop();
    obs.log.info("Request took {ms}ms", { ms: duration });

    Methods

    • Create a child span with inherited attributes

      Child spans inherit all attributes from the parent and form a parent-child relationship in the distributed trace. Always call end() when done.

      Parameters

      • name: string

        Name of the span

      • Optionalattributes: Record<string, string | number | boolean>

        Additional attributes for this span

      Returns Observable<TAttributeSchema>

      New Observable representing the child span

      public async fetchUser(obs: Observable, userId: string) {
      const span = obs.startSpan("fetch-user", { "user.id": userId });
      try {
      const user = await this.db.query("SELECT * FROM users WHERE id = ?", [userId]);
      span.end({ "user.found": true });
      return user;
      } catch (error) {
      span.error(error as Error);
      span.end({ "user.found": false });
      throw error;
      }
      }
    • Create a new Observable with an additional attribute

      Observables are immutable - this returns a new instance. Attributes are propagated to all child operations (logs, spans, metrics).

      Type Parameters

      • K extends string
      • V extends string | number | boolean

      Parameters

      • key: K

        Attribute key

      • value: V

        Attribute value

      Returns Observable<TAttributeSchema>

      New Observable with the added attribute

      public async handleRequest(obs: Observable, req: Request) {
      // Add request ID to all subsequent operations
      const withRequestId = obs.setAttribute("request.id", req.id);
      withRequestId.log.info("Handling request");

      // Chain multiple attributes
      const withUser = withRequestId.setAttribute("user.id", req.userId);
      const span = withUser.startSpan("process-request");
      }
    • Create a new Observable with multiple attributes

      Observables are immutable - this returns a new instance. More efficient than calling setAttribute multiple times.

      Parameters

      • attrs: Record<string, string | number | boolean>

        Attributes to add

      Returns Observable<TAttributeSchema>

      New Observable with the added attributes

      public async handleRequest(obs: Observable, req: Request) {
      const withContext = obs.setAttributes({
      "request.id": req.id,
      "user.id": req.userId,
      "request.method": req.method,
      "request.path": req.path
      });
      withContext.log.info("Processing request");
      }
    • Record an error to both logs and traces

      Automatically records the error to both the logging system and the active span. This ensures errors are captured in both systems for complete observability.

      Parameters

      • error: Error

        Error or BSBError to record

      • Optionalattributes: Record<string, string | number | boolean>

        Additional attributes to attach

      Returns void

      const span = obs.startSpan("risky-operation");
      try {
      await this.doSomethingRisky();
      span.end({ "status": "success" });
      } catch (error) {
      span.error(error as Error, { "status": "failed", "retry": true });
      span.end();
      throw error;
      }
    • End the span (only applies if this Observable was created via span())

      Completes the span and records the final state. If this Observable was not created via span(), this method does nothing.

      Parameters

      • Optionalattributes: Record<string, string | number | boolean>

        Final attributes to attach before ending

      Returns void

      const span = obs.startSpan("process-batch");
      const items = await this.fetchItems();
      await this.processItems(items);
      span.end({ "items.processed": items.length, "status": "complete" });