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

    Class PluginObservable<TAttributeSchema>

    Implementation of Observable interface that wraps DTrace with observability features

    Type Parameters

    • TAttributeSchema extends z.ZodSchema = z.ZodAny

    Implements

    Index

    Constructors

    • Create a PluginObservable

      Type Parameters

      • TAttributeSchema extends ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> = ZodAny

      Parameters

      • trace: DTrace

        DTrace object

      • resource: ResourceContext

        Resource context

      • backend: IPluginObservable

        IPluginObservable instance (unified logging and metrics backend)

      • attributes: Record<string, string | number | boolean> = {}

        Initial attributes

      • Optionalspan: Trace

        Optional Trace/Span object (if created via startSpan())

      Returns PluginObservable<TAttributeSchema>

    Properties

    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.

    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

    // 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 });

    Accessors

    • get trace(): DTrace

      Core trace information (W3C compatible)

      Returns DTrace

    • get traceId(): string

      Trace ID (unique identifier for the entire trace)

      Returns string

    • get spanId(): string

      Span ID (unique identifier for this specific span)

      Returns string

    • get resource(): ResourceContext

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

      Returns ResourceContext

    • get attributes(): Record<string, string | number | boolean>

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

      Returns Record<string, string | number | boolean>

    Methods

    • Create a child span with inherited attributes

      Creates a new Observable representing a child span for distributed tracing. All attributes from the parent are automatically inherited by the child.

      Parameters

      • name: string

        Name of the span (e.g., "database-query", "api-call")

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

        Additional attributes to add to this span

      Returns Observable<TAttributeSchema>

      New Observable instance representing the child span

      public async processOrder(obs: Observable) {
      // Create child span for database operation
      const dbSpan = obs.startSpan("fetch-order", { "order.id": "123" });
      try {
      const order = await this.db.getOrder("123");
      dbSpan.end({ "order.status": order.status });
      } catch (error) {
      dbSpan.error(error);
      dbSpan.end();
      }
      }
    • Create a new Observable with an additional attribute

      Observables are immutable - this returns a new instance with the added attribute. The attribute is propagated to all child operations (logs, spans, etc.).

      Type Parameters

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

      Parameters

      • key: K

        Attribute key (e.g., "user.id", "transaction.type")

      • value: V

        Attribute value (string, number, or boolean)

      Returns Observable<TAttributeSchema>

      New Observable instance with the added attribute

      public async handleRequest(obs: Observable, userId: string) {
      // Add user ID to all subsequent operations
      const withUser = obs.setAttribute("user.id", userId);

      withUser.log.info("Processing request"); // Log includes user.id
      const span = withUser.startSpan("process"); // Span includes user.id
      }
    • Create a new Observable with multiple attributes

      Observables are immutable - this returns a new instance with the added attributes. All attributes are propagated to child operations.

      Parameters

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

        Object containing attributes to add

      Returns Observable<TAttributeSchema>

      New Observable instance with the added attributes

      public async handleRequest(obs: Observable, context: RequestContext) {
      // Add multiple attributes at once
      const withContext = obs.setAttributes({
      "user.id": context.userId,
      "request.id": context.requestId,
      "request.method": context.method
      });

      withContext.log.info("Processing request");
      }
    • Record an error to both logs and traces

      This method automatically records the error to both the logging system and the active span (if this Observable was created via startSpan()). This ensures errors are captured in both systems for complete observability.

      Parameters

      • error: BSBError<any> | Error

        Error or BSBError instance to record

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

        Additional attributes to attach to the error

      Returns void

      public async processData(obs: Observable) {
      const span = obs.startSpan("process-data");
      try {
      await this.riskyOperation();
      } catch (error) {
      // Record error to both logs and span
      span.error(error as Error, { "operation": "riskyOperation" });
      span.end();
      throw error;
      }
      }
    • End the span (only applies if this Observable was created via startSpan())

      Completes the span and records the final state. If this Observable was not created via startSpan(), this method does nothing. Always call end() when the operation is complete to ensure proper trace completion.

      Parameters

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

        Final attributes to attach before ending the span

      Returns void

      public async fetchData(obs: Observable) {
      const span = obs.startSpan("fetch-data");
      try {
      const data = await this.api.fetch();
      span.end({ "data.size": data.length, "status": "success" });
      return data;
      } catch (error) {
      span.error(error as Error);
      span.end({ "status": "failed" });
      throw error;
      }
      }