Skip to main content
Lesson 10 of 12 · xAI Security & Compliance

Audit logs and monitoring via the console

Lesson 10 of 12 Updated July 28, 2026 Advanced
On this page
  1. The importance of auditing in a regulated environment
  2. The xAI console: your security dashboard
  3. Usage analysis via the API
  4. Building an alert system
  5. Client-side application logs
  6. Five metrics that make monitoring readable
  7. Key takeaways

The importance of auditing in a regulated environment

When a SOC 2 auditor asks, “Who consumed what, when, and how would you know in case of an anomaly?” the answer cannot be “we’d look into it.” For any organization subject to compliance obligations—SOC 2, HIPAA, GDPR—traceability of actions is a fundamental requirement, and you prepare it before the incident, not after. The xAI console (console.x.ai) provides the monitoring and audit tools that let you track your API key usage and detect anomalies; this lesson shows you how to use them, and then how to complement them on the application side.

The xAI console: your security dashboard

The console, accessible at console.x.ai, centralizes four functions: API key management, usage monitoring, billing with spending limits, and account security information. On the data side, it gives you usage per key (number of requests, tokens consumed), usage per model, detailed billing history by period, and the status of each key—active, blocked, or disabled. Make it a habit to review it regularly: most key compromises are spotted first by a usage curve that no longer resembles the previous weeks.

Usage analysis via the API

The console is enough for a quick look, but serious monitoring must be programmatic: that’s the role of the analysis endpoint.

POST /v1/billing/teams/{team_id}/usage

{
  "analyticsRequest": {
    "timeRange": {
      "startTime": "2026-03-01 00:00:00",
      "endTime": "2026-04-01 00:00:00",
      "timezone": "UTC"
    },
    "timeUnit": "DAY",
    "values": [{"name": "tokens", "aggregation": "SUM"}],
    "groupBy": ["model"]
  }
}

This request asks for the sum of tokens consumed, day by day, broken down by model, for the month of March. The flexibility comes from combinable options: time units range from MONTH to MINUTE, including CALENDAR_WEEK, DAY, HOUR, and QUARTER_HOUR; available aggregations are SUM, AVG, MIN, MAX, percentiles P50, P90, and P99, as well as COUNT and COUNT_DISTINCT; and you can group by model, period, or key.

These components cover four concrete needs. First, anomaly detection: a sudden spike in consumption on a key that usually handles a stable volume is the classic symptom of a compromise—this is the query your monitoring script should run every night. Next, cost optimization: by grouping by model, you spot underutilized endpoints or expensive models called unnecessarily. Compliance reports: the same query, over a quarter, produces the figures the auditor will ask for. Finally, capacity planning: the consumption trend tells you when to reload your credits before running out on a Sunday.

Building an alert system

A dashboard you don’t look at protects nothing; alerts, however, come to you. Here is the skeleton of a daily check that compares the last 24 hours of consumption to a threshold:

import requests
from datetime import datetime, timedelta

def check_usage_anomaly(team_id, threshold_tokens):
    today = datetime.utcnow()
    yesterday = today - timedelta(days=1)

    response = requests.post(
        f"https://management-api.x.ai/v1/billing/teams/{team_id}/usage",
        headers={"Authorization": f"Bearer {MGMT_KEY}"},
        json={
            "analyticsRequest": {
                "timeRange": {
                    "startTime": yesterday.strftime("%Y-%m-%d 00:00:00"),
                    "endTime": today.strftime("%Y-%m-%d 00:00:00"),
                    "timezone": "UTC"
                },
                "timeUnit": "DAY",
                "values": [{"name": "tokens", "aggregation": "SUM"}]
            }
        }
    )

    total_tokens = sum_tokens(response.json())
    if total_tokens > threshold_tokens:
        send_alert(f"Abnormal usage: {total_tokens} tokens in 24h")

Complement this setup with a budgetary safety net: the POST /v1/billing/teams/{team_id}/postpaid/spending-limits endpoint lets you set a monthly spending limit—uncontrolled overspending then becomes impossible, regardless of the cause. And to know where you stand at any point in the billing cycle, GET /v1/billing/teams/{team_id}/postpaid/invoice/preview gives you a preview of accumulated charges before the final invoice.

Client-side application logs

The xAI console sees what happens at xAI; it doesn’t see what happens on your end. Your own application logs are the other half of traceability: they are the ones that will answer the question “which user triggered this call?” For each API call, log the timestamp, the ID of the user who initiated the call, the model and endpoint used, the number of input and output tokens, the HTTP response status, latency, and the API key ID in masked version.

The reverse discipline is just as important, because a verbose log becomes a data leak itself. Never log the content of prompts containing personal data, nor responses containing sensitive information, nor API keys in plaintext, nor ephemeral tokens. A log file that contains your users’ prompts is a personal database in disguise—with all the GDPR obligations that implies, including the right to erasure.

Five metrics that make monitoring readable

To consolidate this lesson, gather your monitoring data in a single dashboard rather than multiplying screens. The first two metrics describe normal activity: daily consumption per key and per model, and the error rate (4xx, 5xx) per endpoint, which reveals both a deployment bug and a key with misconfigured permissions. The next two describe friction: triggered moderation attempts, which tell you what your users are trying to do, and keys close to expiration, to anticipate renewals rather than face them unexpectedly.

The fifth metric is the one that makes the difference: comparison with historical averages. A raw number says nothing—eight million tokens last night, is that a lot? A deviation from the norm, however, says everything, and it is on this deviation that your alerts should trigger.

Key takeaways

  • The xAI console (console.x.ai) centralizes monitoring, key management, and billing
  • The usage endpoint enables programmatic analysis with flexible aggregation (SUM to P99, from MINUTE to MONTH)
  • Configure threshold alerts on consumption: an abnormal spike is the first sign of compromise
  • Set spending limits via the Management API to cap any overrun
  • Log metadata on the application side, never sensitive content or keys in plaintext