DO

documenso-observability

Implements structured logging, latency tracking, and request monitoring for Documenso API integrations.

Install

mkdir -p .claude/skills/documenso-observability && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/8428" && unzip -o skill.zip -d .claude/skills/documenso-observability && rm skill.zip

Installs to .claude/skills/documenso-observability

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Implement monitoring, logging, and tracing for Documenso integrations.
70 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Instrument Documenso API clients to track request counts and latency
  • Calculate error rates and status code distributions
  • Expose health check endpoints for monitoring systems
  • Provide Prometheus-compatible metrics for scraping
  • Log operations and errors with structured context

How it works

It uses a Proxy object to wrap the Documenso client, intercepting method calls to measure latency and track success or failure rates. Metrics are exposed via an endpoint for external monitoring tools to scrape.

Inputs & outputs

You give it
Documenso API client instance
You get back
Instrumented client with metrics collection and logging

When to use documenso-observability

  • Implementing API request tracing
  • Monitoring error rates
  • Tracking integration latency
  • Debugging production issues

About this skill

Documenso Observability

Overview

Implement monitoring, structured logging, and health checks for Documenso integrations. Since Documenso does not expose rate limit headers or usage metrics via API, observability is built around your API call patterns, latency, error rates, and webhook delivery.

Prerequisites

  • Working Documenso integration
  • Monitoring stack (Prometheus/Grafana, Datadog, or CloudWatch)
  • Logging infrastructure

Instructions

Step 1: Instrumented Client Wrapper

// src/observability/documenso-metrics.ts
import { Documenso } from "@documenso/sdk-typescript";

interface Metrics {
  requestCount: number;
  errorCount: number;
  totalLatencyMs: number;
  errorsByStatus: Record<number, number>;
}

const metrics: Metrics = {
  requestCount: 0,
  errorCount: 0,
  totalLatencyMs: 0,
  errorsByStatus: {},
};

export function createInstrumentedClient(): Documenso {
  const client = new Documenso({ apiKey: process.env.DOCUMENSO_API_KEY! });

  return new Proxy(client, {
    get(target, prop) {
      const value = (target as any)[prop];
      if (typeof value === "object" && value !== null) {
        return new Proxy(value, {
          get(innerTarget, method) {
            const fn = (innerTarget as any)[method];
            if (typeof fn !== "function") return fn;

            return async (...args: any[]) => {
              const start = Date.now();
              metrics.requestCount++;

              try {
                const result = await fn.apply(innerTarget, args);
                metrics.totalLatencyMs += Date.now() - start;
                return result;
              } catch (err: any) {
                metrics.errorCount++;
                const status = err.statusCode ?? 0;
                metrics.errorsByStatus[status] = (metrics.errorsByStatus[status] || 0) + 1;
                metrics.totalLatencyMs += Date.now() - start;
                throw err;
              }
            };
          },
        });
      }
      return value;
    },
  });
}

// Expose metrics for Prometheus scraping
export function getMetrics() {
  return {
    ...metrics,
    avgLatencyMs: metrics.requestCount > 0
      ? Math.round(metrics.totalLatencyMs / metrics.requestCount)
      : 0,
    errorRate: metrics.requestCount > 0
      ? (metrics.errorCount / metrics.requestCount * 100).toFixed(2) + "%"
      : "0%",
  };
}

Step 2: Structured Logging

// src/observability/logger.ts
import { createLogger, format, transports } from "winston";

const logger = createLogger({
  level: process.env.LOG_LEVEL ?? "info",
  format: format.combine(
    format.timestamp(),
    format.json()
  ),
  defaultMeta: { service: "documenso-integration" },
  transports: [
    new transports.Console(),
    // Add file or cloud transport for production
  ],
});

// Log Documenso operations with structured context
export function logDocumensoOperation(
  operation: string,
  documentId?: number,
  extra?: Record<string, any>
) {
  logger.info("documenso_operation", {
    operation,
    documentId,
    ...extra,
  });
}

// Log errors with full context
export function logDocumensoError(
  operation: string,
  error: any,
  documentId?: number
) {
  logger.error("documenso_error", {
    operation,
    documentId,
    statusCode: error.statusCode,
    message: error.message,
    // Never log API keys
  });
}

Step 3: Health Check Endpoint

// src/api/health.ts
import { Documenso } from "@documenso/sdk-typescript";

interface HealthStatus {
  status: "healthy" | "degraded" | "unhealthy";
  latencyMs: number;
  message: string;
}

async function checkDocumensoHealth(): Promise<HealthStatus> {
  const client = new Documenso({ apiKey: process.env.DOCUMENSO_API_KEY! });
  const start = Date.now();

  try {
    await client.documents.findV0({ page: 1, perPage: 1 });
    const latencyMs = Date.now() - start;

    if (latencyMs > 5000) {
      return { status: "degraded", latencyMs, message: "High latency" };
    }
    return { status: "healthy", latencyMs, message: "OK" };
  } catch (err: any) {
    return {
      status: "unhealthy",
      latencyMs: Date.now() - start,
      message: `${err.statusCode ?? "unknown"}: ${err.message}`,
    };
  }
}

// Express endpoint
app.get("/health/documenso", async (req, res) => {
  const health = await checkDocumensoHealth();
  const httpStatus = health.status === "healthy" ? 200 : health.status === "degraded" ? 200 : 503;
  res.status(httpStatus).json(health);
});

Step 4: Prometheus Metrics Endpoint

// src/api/metrics.ts
import { getMetrics } from "../observability/documenso-metrics";

app.get("/metrics/documenso", (req, res) => {
  const m = getMetrics();
  res.type("text/plain").send(`
# HELP documenso_requests_total Total API requests
# TYPE documenso_requests_total counter
documenso_requests_total ${m.requestCount}

# HELP documenso_errors_total Total API errors
# TYPE documenso_errors_total counter
documenso_errors_total ${m.errorCount}

# HELP documenso_avg_latency_ms Average request latency
# TYPE documenso_avg_latency_ms gauge
documenso_avg_latency_ms ${m.avgLatencyMs}
  `.trim());
});

Step 5: Webhook Delivery Monitoring

// Track webhook delivery success/failure
const webhookMetrics = {
  received: 0,
  processed: 0,
  failed: 0,
  byEvent: {} as Record<string, number>,
};

app.post("/webhooks/documenso", async (req, res) => {
  webhookMetrics.received++;
  const { event } = req.body;
  webhookMetrics.byEvent[event] = (webhookMetrics.byEvent[event] || 0) + 1;

  res.status(200).json({ received: true });

  try {
    await processWebhookEvent(req.body);
    webhookMetrics.processed++;
  } catch (err) {
    webhookMetrics.failed++;
    logDocumensoError("webhook_processing", err);
  }
});

// Expose webhook metrics
app.get("/metrics/webhooks", (req, res) => {
  res.json(webhookMetrics);
});

Step 6: Alerting Rules

# alerting-rules.yml (Prometheus)
groups:
  - name: documenso
    rules:
      - alert: DocumensoHighErrorRate
        expr: rate(documenso_errors_total[5m]) / rate(documenso_requests_total[5m]) > 0.05
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Documenso error rate above 5%"

      - alert: DocumensoUnhealthy
        expr: up{job="documenso-health"} == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Documenso health check failing"

      - alert: DocumensoHighLatency
        expr: documenso_avg_latency_ms > 5000
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Documenso average latency above 5s"

Key Metrics to Monitor

MetricHealthyWarningCritical
API error rate< 1%1-5%> 5%
Average latency< 1s1-5s> 5s
Health checkPassingDegradedFailing
Webhook delivery> 99%95-99%< 95%

Error Handling

Observability IssueCauseSolution
Metrics not appearingScrape config wrongVerify Prometheus targets
Logs missingLog level too highSet LOG_LEVEL=debug temporarily
False alertsThresholds too sensitiveAdjust to match your traffic patterns
Health check flappingTransient network issuesAdd for: 2m to alert rules

Resources

Next Steps

For incident response, see documenso-incident-runbook.

When not to use it

  • When logging sensitive information like API keys
  • When the integration lacks a monitoring stack for scraping

Prerequisites

Working Documenso integrationMonitoring stack (Prometheus/Grafana, Datadog, or CloudWatch)Logging infrastructure

Limitations

  • Documenso does not expose rate limit headers via API
  • Health check latency threshold is fixed at 5000ms

How it compares

Unlike manual logging, this approach uses a Proxy wrapper to automatically instrument all API methods without modifying individual service calls.

Compared to similar skills

documenso-observability side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
documenso-observability (this skill)025dReviewIntermediate
perplexity-observability125dNo flagsIntermediate
setup-sap-btp-logging06moReviewBeginner
mcp-builder1363moReviewAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

perplexity-observability

jeremylongshore

Set up comprehensive observability for Perplexity integrations with metrics, traces, and alerts. Use when implementing monitoring for Perplexity operations, setting up dashboards, or configuring alerting for Perplexity integration health. Trigger with phrases like "perplexity monitoring", "perplexity metrics", "perplexity observability", "monitor perplexity", "perplexity alerts", "perplexity tracing".

10

setup-sap-btp-logging

leotrinh

Automates the setup of sap-btp-cloud-logging-client in a project.

00

mcp-builder

anthropics

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

136215

telegram-mini-app

davila7

Expert in building Telegram Mini Apps (TWA) - web apps that run inside Telegram with native-like experience. Covers the TON ecosystem, Telegram Web App API, payments, user authentication, and building viral mini apps that monetize. Use when: telegram mini app, TWA, telegram web app, TON app, mini app.

62163

stripe-integration

wshobson

Implement Stripe payment processing for robust, PCI-compliant payment flows including checkout, subscriptions, and webhooks. Use when integrating Stripe payments, building subscription systems, or implementing secure checkout flows.

48165

copilot-sdk

github

Build agentic applications with GitHub Copilot SDK. Use when embedding AI agents in apps, creating custom tools, implementing streaming responses, managing sessions, connecting to MCP servers, or creating custom agents. Triggers on Copilot SDK, GitHub SDK, agentic app, embed Copilot, programmable agent, MCP server, custom agent.

763

Search skills

Search the agent skills registry