Tips > Data, APIs & Webhooks

Track API Usage by Logging Calls with Timestamps, Endpoints, and Token Counts

You cannot optimize what you do not measure.

TipIntermediate3 min read

You cannot optimize what you do not measure. Add a lightweight logging step to every workflow that calls paid APIs. Track the timestamp, endpoint, model used, token count, and estimated cost. Review this log weekly to find your most expensive workflows and optimize them first.

Real-world example: A team runs 15 workflows that call OpenAI, Anthropic, and various SaaS APIs. Without tracking, they discover a $2,000 monthly bill but do not know which workflows are responsible.

// Code node: "Log API Usage" -- place after every paid API call
const apiResponse = $input.first().json;

// Extract token usage from OpenAI response format
const usage = apiResponse.usage || {};

// Pricing per 1K tokens (update these as prices change)
const pricing = {
  'gpt-4o': { input: 0.0025, output: 0.01 },
  'gpt-4o-mini': { input: 0.00015, output: 0.0006 },
  'claude-sonnet-4': { input: 0.003, output: 0.015 },
  'claude-3-5-haiku': { input: 0.0008, output: 0.004 }
};

const model = apiResponse.model || 'unknown';
const modelPricing = pricing[model] || { input: 0, output: 0 };

const inputTokens = usage.prompt_tokens || 0;
const outputTokens = usage.completion_tokens || 0;
const estimatedCost = (
  (inputTokens / 1000) * modelPricing.input +
  (outputTokens / 1000) * modelPricing.output
);

const logEntry = {
  timestamp: new Date().toISOString(),
  workflow_name: $workflow.name,
  execution_id: $execution.id,
  node_name: $prevNode.name,
  model: model,
  endpoint: 'chat/completions',
  input_tokens: inputTokens,
  output_tokens: outputTokens,
  total_tokens: inputTokens + outputTokens,
  estimated_cost_usd: Math.round(estimatedCost * 10000) / 10000,
  success: !apiResponse.error
};

return [{
  json: {
    ...apiResponse,
    _usage_log: logEntry
  }
}];
```text
Write the log to a Google Sheet or database:

```sql
-- Postgres: Create the tracking table
CREATE TABLE api_usage_log (
  id SERIAL PRIMARY KEY,
  timestamp TIMESTAMPTZ NOT NULL,
  workflow_name TEXT NOT NULL,
  execution_id TEXT,
  node_name TEXT,
  model TEXT,
  endpoint TEXT,
  input_tokens INTEGER DEFAULT 0,
  output_tokens INTEGER DEFAULT 0,
  total_tokens INTEGER DEFAULT 0,
  estimated_cost_usd NUMERIC(10, 6) DEFAULT 0,
  success BOOLEAN DEFAULT true
);

-- Weekly cost analysis query
SELECT
  workflow_name,
  model,
  COUNT(*) as call_count,
  SUM(input_tokens) as total_input_tokens,
  SUM(output_tokens) as total_output_tokens,
  SUM(estimated_cost_usd) as total_cost,
  ROUND(AVG(estimated_cost_usd)::numeric, 6) as avg_cost_per_call
FROM api_usage_log
WHERE timestamp > NOW() - INTERVAL '7 days'
GROUP BY workflow_name, model
ORDER BY total_cost DESC;
```text
Build a monitoring dashboard workflow:

```yaml

# Scheduled workflow: "Weekly API Cost Report"

# Runs every Monday at 9am

[Schedule Trigger: Monday 9am]
  --> [Postgres: Run weekly analysis query]
  --> [Code: Format report]
  --> [IF: Total cost > $100 threshold]
      True:  [Slack: Send alert with breakdown]
      False: [Slack: Send normal summary]
```text
```yaml
Sample report output:
  Total API spend this week: $47.23

  Top workflows by cost:
  1. Customer Support Classifier  - $18.50 (392 calls, gpt-4o)
  2. Product Description Generator - $12.30 (41 calls, gpt-4o)
  3. Email Summarizer              - $8.90 (890 calls, gpt-4o-mini)
  4. Lead Enrichment               - $4.20 (420 calls, clearbit)
  5. Translation Pipeline          - $3.33 (111 calls, gpt-4o-mini)

  Recommendation: Switch "Customer Support Classifier" to gpt-4o-mini
  (estimated savings: $16.50/week)
```text
This visibility lets you make data-driven decisions about which workflows to optimize first and measure the impact of changes.

**Related:** [Use Structured Output (JSON Mode) for Parseable Responses](../ai-and-llm-integration/01-use-structured-output-json-mode-for-parseable-responses.md) | [Configure Payload Size and Binary Data Mode for Large Files](../performance-and-large-files/01-configure-payload-size-and-binary-data-mode-for-large-files.md)

Want this running in your stack?

I build production n8n and Cloudflare automation for teams — the same engineering behind HarperFlow. Fixed-price, escrow-protected, US-based.