# Axiom documentation
---
# Changelog
Source: https://axiom.co/docs/changelog
Axiom ships continuously. Read the latest release notes on the [Axiom changelog](https://axiom.co/changelog).
This section will become the first-party home for product updates as the changelog publishing workflow moves into the documentation platform.
---
# Annotations
Source: https://axiom.co/docs/annotations
Annotations show when deployments, outages, or other configured events happened alongside your data. Mark a point or interval in time across Query, dashboards, and monitors to put changes in context.
## Prerequisites [#prerequisites]
* [Create an Axiom account](https://app.axiom.co/register).
* [Create a dataset in Axiom](/reference/datasets#create-dataset) where you send your data.
* [Send data](/send-data/methods) to your Axiom dataset.
* To view annotations in Console, use an account with permission to read annotations.
* For API requests and GitHub Actions, [create an API token](/reference/tokens) with the annotation permissions for the operations you use: create, read, update, or delete.
## Show and hide annotations in Console [#show-and-hide-annotations-in-console]
### Query [#show-and-hide-annotations-in-query]
Annotations appear on time series and percentile charts, and on heatmaps when the query returns a single chart. Use **Chart options** to show or hide annotations for the queried dataset and selected time range.
### Dashboards [#show-and-hide-annotations-on-dashboards]
To choose the annotation types to display, click **Annotations** in the dashboard toolbar.
In the chart editor, expand **Chart** and click **Manage** in **Annotations**.
Each chart shows annotations for the datasets it queries. Your selections apply across the dashboard and aren't saved with it.
### Monitors [#show-and-hide-annotations-in-monitors]
Threshold and anomaly monitor charts show annotations for the monitor’s dataset and the chart’s time range.
In Recent activity , click Annotations beside the time range and select the types to display. On phones, open Recent activity options (⋯) and select Annotations .
In the monitor editor, run the preview query. Expand Chart in the settings panel and click Manage in Annotations .
Your selections aren't saved with the monitor.
## Display limits [#display-limits]
For time ranges longer than 100 days, charts show annotations only for the latest 100 days of that range. To view older annotations, select a shorter range around the event.
## Create annotations [#create-annotations]
Create annotations with a [GitHub Action](#create-annotations-with-github-actions) or the [Axiom API](#create-annotations-using-axiom-api). The [Axiom Vercel integration](/apps/vercel) also creates annotations when deployments complete.
### Create annotations with GitHub Actions [#create-annotations-with-github-actions]
Add the [Axiom annotation action](https://github.com/axiomhq/annotation-action) after the deployment step in your workflow:
```yml
- name: Add deployment annotation
uses: axiomhq/annotation-action@v0.2.0
with:
axiomToken: ${{ secrets.API_TOKEN }}
datasets: DATASET_NAME
type: "production-release"
title: "Production deployment"
description: "Commit ${{ github.event.head_commit.message }}"
```
By default, the action uses the current time and links to the workflow run.
### Create annotations using Axiom API [#create-annotations-using-axiom-api]
To create an annotation using the Axiom API, use the following API request:
```bash
curl -X 'POST' 'https://api.axiom.co/v2/annotations' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"time": "2024-03-18T08:39:28.382Z",
"type": "deploy",
"datasets": ["DATASET_NAME"],
"title": "Production deployment",
"description": "Deploy new feature to the sales form",
"url": "https://example.com"
}'
```
Customize the other fields of the code above such as the title, the description, and the URL. For more information on the allowed fields, see [Annotation object](#annotation-object).
**Example response**
```json
{
"datasets": ["my-dataset"],
"description": "Deploy new feature to the sales form",
"id": "ann_123",
"time": "2024-03-18T08:39:28.382Z",
"title": "Production deployment",
"type": "deploy",
"url": "https://example.com"
}
```
The API response from Axiom contains an `id` field. This is the annotation ID that you can later use to change or delete the annotation.
## Get information about annotations [#get-information-about-annotations]
To list annotations in your organization, use the following API request:
```bash
curl -X 'GET' 'https://api.axiom.co/v2/annotations' \
-H 'Authorization: Bearer API_TOKEN'
```
Without filters, this endpoint returns all annotations in your organization. Use the following parameters to filter by time range or dataset:
* `start` is an RFC 3339 timestamp that specifies the beginning of the time interval.
* `end` is an RFC 3339 timestamp that specifies the end of the time interval.
* `datasets` is the list of datasets whose annotations you want to get information about. Separate datasets by commas, for example `datasets=my-dataset1,my-dataset2`.
Set both `start` and `end`, or omit both. Use a range of 100 days or less, with `end` at or after `start`. Results include annotations that overlap the range.
The following example lists annotations for `my-dataset` between March 16 and 19, 2024:
```bash
curl -X 'GET' 'https://api.axiom.co/v2/annotations?start=2024-03-16T00:00:00.000Z&end=2024-03-19T23:59:59.999Z&datasets=my-dataset' \
-H 'Authorization: Bearer API_TOKEN'
```
**Example response**
```json
[
{
"datasets": ["my-dataset"],
"description": "Deploy new feature to the navigation component",
"id": "ann_234",
"time": "2024-03-17T01:15:45.232Z",
"title": "Production deployment",
"type": "deploy",
"url": "https://example.com"
},
{
"datasets": ["my-dataset"],
"description": "Deploy new feature to the sales form",
"id": "ann_123",
"time": "2024-03-18T08:39:28.382Z",
"title": "Production deployment",
"type": "deploy",
"url": "https://example.com"
}
]
```
The API response from Axiom contains an `id` field. This is the annotation ID that you can later use to change or delete the annotation. For more information on the other fields, see [Annotation object](#annotation-object).
To get information about a specific annotation, use the following API request:
```bash
curl -X 'GET' 'https://api.axiom.co/v2/annotations/ANNOTATION_ID' \
-H 'Authorization: Bearer API_TOKEN'
```
Replace `ANNOTATION_ID` with the ID of the annotation.
**Example response**
```json
{
"datasets": ["my-dataset"],
"description": "Deploy new feature to the sales form",
"id": "ann_123",
"time": "2024-03-18T08:39:28.382Z",
"title": "Production deployment",
"type": "deploy",
"url": "https://example.com"
}
```
For more information on these fields, see [Annotation object](#annotation-object).
## Change annotations [#change-annotations]
To change an existing annotation, use the following API request:
```bash
curl -X 'PUT' 'https://api.axiom.co/v2/annotations/ANNOTATION_ID' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"endTime": "2024-03-18T08:49:28.382Z"
}'
```
Replace `ANNOTATION_ID` with the ID of the annotation. For more information about how to determine the annotation ID, see [Get information about annotations](#get-information-about-annotations).
In the payload, specify the fields to change. Omitted fields keep their current values. Empty text values and an empty `datasets` list leave existing values unchanged. The example adds `endTime` to the annotation created above. For more information, see [Annotation object](#annotation-object).
**Example response**
```json
{
"datasets": ["my-dataset"],
"description": "Deploy new feature to the sales form",
"id": "ann_123",
"time": "2024-03-18T08:39:28.382Z",
"title": "Production deployment",
"type": "deploy",
"url": "https://example.com",
"endTime": "2024-03-18T08:49:28.382Z"
}
```
## Delete annotations [#delete-annotations]
To delete an existing annotation, use the following API request:
```bash
curl -X 'DELETE' 'https://api.axiom.co/v2/annotations/ANNOTATION_ID' \
-H 'Authorization: Bearer API_TOKEN'
```
Replace `ANNOTATION_ID` with the ID of the annotation. For more information about how to determine the annotation ID, see [Get information about annotations](#get-information-about-annotations).
## Annotation object [#annotation-object]
Annotations are represented as objects with the following fields:
* `datasets` is the list of dataset names for which the annotation appears on charts. Specify at least one existing dataset when creating an annotation.
* `id` is the unique ID of the annotation.
* `time` is the start time of the annotation, in RFC 3339 format. If you omit this field when creating an annotation, Axiom uses the time of the API request. Axiom rejects future start times.
* Optional: `endTime` is the end time of the annotation, in RFC 3339 format. Specify an end time at or after `time`. Omit this field when creating an annotation to mark a point in time.
* `type` is the type of event marked by the annotation. For example, `production-deployment`. Specify this field when creating an annotation. Use lowercase letters, numbers, and hyphens.
* Optional: `title` is a summary of the annotation that appears on the charts.
* Optional: `description` is an explanation of the event the annotation marks on the charts.
* Optional: `url` is the URL relevant for the event marked by the annotation. For example, a link to a GitHub pull request.
For more information, see [Create annotation](/restapi/endpoints/createAnnotation), [List all annotations](/restapi/endpoints/getAnnotations), and [Update annotation](/restapi/endpoints/updateAnnotation).
## Example use case [#example-use-case]
The example below demonstrates how annotations help you troubleshoot issues in your app or system. Your monitor alerts you about rising form submission errors. You explore this trend and when it started. Right before form submission errors started rising, you see an annotation about a deployment of a new feature to the form. You make the hypothesis that the deployment is the reason for the error and decide to investigate the code changes it introduced.
### Create annotation [#create-annotation]
Use the following API request to create an annotation:
```bash
curl -X 'POST' 'https://api.axiom.co/v2/annotations' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"time": "2024-03-18T08:39:28.382Z",
"type": "deploy",
"datasets": ["my-dataset"],
"title": "Production deployment",
"description": "Deploy new feature to the sales form",
"url": "https://example.com"
}'
```
### Create a monitor [#create-a-monitor]
In this example, you set up a monitor that alerts you when the number of form submission errors rises. For more information on creating a monitor, see [Monitoring and Notifiers](/monitor-data/monitors).
### Explore trends [#explore-trends]
Suppose your monitor sends you a notification about rising form submission errors.
You decide to investigate and run a query to display the number of form submission errors over time. Ensure you select a time range that includes the annotation.
You get a chart similar to the example below displaying form submission errors and annotations about the time of important events such as deployments.
### Inspect issue [#inspect-issue]
1. From the chart, you see that the number of errors started to rise after the deployment of a new feature to the sales form. This correlation allows you to form the hypothesis that the errors might be caused by the deployment.
2. You click the annotation’s link to investigate the deployment.
3. You inspect the code changes in depth and discover the cause of the errors.
4. You quickly fix the issue in another deployment.
---
# Quickstart
Source: https://axiom.co/docs/getting-started
This guide takes you from foundational knowledge to advanced proficiency with Axiom. The sections are structured to build upon one another but can also serve as standalone references. By the end, you can independently query data, diagnose performance, derive insights, and set up proactive alerting.
## Axiom fundamentals [#axiom-fundamentals]
Axiom is the modern machine data platform. Machine data is any record a system produces: logs, distributed traces, metrics, and events like product analytics, marketing attribution, or security audit trails. Axiom stores and queries all of it through one engine.
**Datasets** store related machine data, similar to a table in a traditional database. For example, the Axiom Playground includes datasets like `sample-http-logs` for HTTP request logs and `github-push-event` for GitHub activity.
**Fields** are named pieces of data on each record, like columns in a spreadsheet. Fields have a name (for example, `status`, `resp_body_size_bytes`, `geo.city`) and a value. Axiom supports various data types including strings, numbers, booleans, and complex JSON objects.
* **Single dataset:** Use one dataset when events share many common fields and you often query them together.
* **Multiple datasets:** Split into multiple datasets when the data is structurally different or serves entirely different use cases. This prevents a single dataset from accumulating fields that are only relevant to a small subset of its events.
## Send data to Axiom [#send-data-to-axiom]
You can send your first event with a single HTTP request:
```shell wrap
curl -X 'POST' 'https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/x-ndjson' \
-d '{ "http": { "request": { "method": "GET", "duration_ms": 231 }, "response": { "body": { "size": 3012 } } }, "url": { "path": "/download" } }'
```
To send events continuously, Axiom supports a wide range of tools and libraries:
* **[OpenTelemetry](/send-data/opentelemetry)** for industry-standard instrumentation of traces, logs, and metrics.
* **[Axiom API](/restapi/ingest)** for direct HTTP ingestion from any language or platform.
* **Language libraries** for [JavaScript](/guides/javascript), [Python](/guides/python), [Go](/guides/go), [Rust](/guides/rust), [.NET](/guides/send-logs-from-dotnet), and more.
* **Log shippers** like [Vector](/send-data/vector), [Fluent Bit](/send-data/fluent-bit), and [Logstash](/send-data/logstash).
* **Platform integrations** for [AWS](/send-data/cloudwatch), [Kubernetes](/send-data/kubernetes), [Vercel](/apps/vercel), and [Cloudflare Logpush](/apps/cloudflare-logpush).
For the full list, see [Methods for sending data](/send-data/methods).
## Explore your data [#explore-your-data]
Start by identifying the correct dataset in the [Datasets tab](https://app.axiom.co/datasets). You can explore the fields within a dataset to find relevant information. For example, in `sample-http-logs` you might look at `resp_header_size_bytes` (response size), `status` (HTTP status code), and `geo.country` (geographic origin).
Pay attention to field data types. A field stored as a number behaves differently than one stored as a string. The schema view in the Datasets tab shows the type for each field.
## Build your first queries [#build-your-first-queries]
You typically interact with this data by creating queries using one of the following interfaces:
* **[Builder](/query-data/explore):** A point-and-click interface that helps you build filters and aggregations without writing code. It's excellent for simple, quick-look analyses.
* **[Editor](/query-data/query-editor)**: An interface where you can write queries using powerful, text-based query languages for sophisticated analysis. Use [APL (Axiom Processing Language)](/apl/introduction) for logs, traces, and events, and [MPL (Metrics Processing Language)](/mpl/introduction) for metrics.
* **[Axiom API](/restapi/query)**: Query your data programmatically.
* **[AI-assisted query building](/query-data/query-editor#generate-query-using-natural-language)**: Generate APL queries from natural language descriptions after pressing `Cmd+K` (macOS) or `Ctrl+K` (Windows/Linux) in the Query tab.
* **[MCP Server](/console/intelligence/mcp-server) and [Skills](/console/intelligence/skills)**: Enable AI agents to query your data. Agents without an existing organization can [provision their own temporary organization](/console/intelligence/agent-created-orgs).
An APL query starts with a data source, followed by operators connected by the pipe `|` character. Each pipe takes the output of the previous line and uses it as input for the next, allowing you to chain operations. A common pattern is dataset, filter (`where`), transform (`extend`), analyze (`summarize`).
This example counts distinct users per day, grouped by HTTP method:
```kusto
['sample-http-logs']
| summarize dcount(id) by bin(_time, 1d), method
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20summarize%20dcount\(id\)%20by%20bin\(_time%2C%201d\)%2C%20method%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
* `['sample-http-logs']` selects the dataset.
* `|` passes the data to the next operator.
* `summarize` groups rows that share values in the `by` clause.
* `dcount(id)` calculates the distinct count of the `id` field. This is a probabilistic function that provides a highly accurate approximation and runs faster than an exact count.
* `by bin(_time, 1d), method` groups by time binned into 1-day intervals and by HTTP method.
* Start with Builder to understand the basic structure of a query, then switch to Editor to refine it.
* Use the AI assistant as a learning tool. Generate a query and then study its structure to understand the APL.
* Use the `where` operator early to narrow down events. This is important for performance.
* Review your team's saved queries in Axiom to learn from real-world examples.
* The full list of functions and operators is available in the [Query reference](/apl/overview).
## Set up monitors [#set-up-monitors]
[Monitors](/monitor-data/monitors) run queries on a schedule and trigger notifications when conditions are met. This moves you from reactive investigation to proactive awareness.
* **[Threshold monitors](/monitor-data/threshold-monitors)** trigger when an aggregated value crosses a threshold (for example, error counts above 100 in 5 minutes). This is the most common type.
* **[Match monitors](/monitor-data/match-monitors)** trigger for each individual event that matches a specific pattern (for example, a critical error message). Use these sparingly for high-volume events.
* **[Anomaly monitors](/monitor-data/anomaly-monitors)** use machine learning to detect unexpected deviations from a historical baseline, without a static threshold.
* **[New values monitors](/monitor-data/new-values-monitors)** trigger when a column holds a value that the monitor hasn’t seen recently (for example, a new error type or a new country).
This example creates a threshold monitor to get a notification if the number of server errors exceeds a threshold.
1. Write and test the query:
```kusto
['sample-http-logs']
| where status >= 500
| summarize error_count = count()
```
2. Go to **Monitors** tab and create a new threshold monitor.
3. Paste your query and set the trigger condition, for example, `When error_count is above 50`.
4. Set the schedule, for example, evaluate every 5 minutes.
5. Select or create a [notifier](/monitor-data/notifiers-overview) (Slack, PagerDuty, email, and more).
* Customize the notifier description to include important context such as a link to a relevant dashboard.
* Avoid creating match monitors on high-volume logs without specific filters. This can lead to excessive notifications.
## Build dashboards [#build-dashboards]
[Dashboards](/dashboards/create) are collections of saved queries visualized as charts, tables, and other elements. They provide a single view for monitoring a service, tracking an experiment, or sharing key metrics.
This example creates a dashboard to monitor HTTP request performance.
**Element 1: P75 and P95 latency (time series)**
This query calculates the 75th and 95th percentiles of request duration and displays them as a time series.
```kusto
['sample-http-logs']
| summarize
P75 = percentile(req_duration_ms, 75),
P95 = percentile(req_duration_ms, 95)
by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20summarize%5Cn%20%20%20%20P75%20%3D%20percentile\(req_duration_ms%2C%2075\)%2C%5Cn%20%20%20%20P95%20%3D%20percentile\(req_duration_ms%2C%2095\)%5Cn%20%20by%20bin_auto\(_time\)%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Element 2: Requests by country (table)**
This query counts the number of requests by country and displays them as a table.
```kusto
['sample-http-logs']
| summarize request_count = count() by ['geo.country']
| sort by request_count desc
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20summarize%20request_count%20%3D%20count\(\)%20by%20%5B'geo.country'%5D%5Cn%7C%20sort%20by%20request_count%20desc%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Element 3: Total distinct users (statistic)**
This query counts the number of distinct users and displays them as a statistic.
```kusto
['sample-http-logs']
| summarize dcount(id)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20summarize%20dcount\(id\)%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
* Give dashboards and their elements clear, descriptive names.
* Use dashboard filters to allow viewers to slice data by dimensions like region, status code, or service.
* Avoid cluttering a single dashboard with unrelated metrics. Create separate dashboards for different use cases.
## What's next [#whats-next]
* [APL introduction](/apl/introduction) for the full query language reference.
* [Sample queries](/apl/tutorial) for real-world APL examples you can run in the Playground.
* [Send data to Axiom](/send-data/methods) to connect your own data sources.
* [Monitor examples](/monitor-data/monitor-examples) for more alerting patterns.
---
# What is Axiom?
Source: https://axiom.co/docs/introduction
Axiom is a data platform designed to efficiently collect, store, and analyze event and telemetry data at massive scale. At its core, Axiom combines a high-performance, proprietary data store with an intelligent Console, helping teams reach actionable insights from their data faster.
Trusted by 30,000+ organizations, from high-growth startups to global enterprises.
## Components [#components]
Axiom consists of two purpose-built data stores supported by a unified console experience:
### EventDB [#eventdb]
Robust, cost-effective, and scalable datastore specifically optimized for timestamped event data. Built from the ground up to handle the vast volumes and high velocity of event ingestion, EventDB ensures:
* **Scalable data loading:** Events are ingested seamlessly without complex middleware, scaling linearly with no single points of failure.
* **Extreme compression:** Tuned storage format compresses data 25-50x, significantly reducing storage costs and ensuring data remains queryable at any time.
* **Serverless querying:** Axiom spins up ephemeral, serverless runtimes on-demand to execute queries efficiently, minimizing idle compute resources and costs.
### MetricsDB [#metricsdb]
Dedicated metrics datastore engineered specifically for high-cardinality time-series data. Unlike traditional metrics solutions that penalize you for dimensional complexity, MetricsDB embraces high-cardinality tags as a design principle:
* **High-cardinality native:** Store metrics with high-cardinality dimensional tags without performance degradation or cost penalties.
* **Optimized storage:** Purpose-built storage format designed for time-series workloads delivers efficient compression and fast aggregations across millions of unique tag combinations.
* **Thoughtful constraints:** Design choices prioritize the most common metrics use cases while maintaining exceptional performance.
For more information, see [Axiom’s architecture](/platform-overview/architecture).
### Console [#console]
Intuitive web app built for exploration, visualization, and monitoring of your data.
* **Real-time exploration:** Effortlessly query and visualize data streams in real-time, providing instant clarity on operational and business conditions.
* **Dynamic visualizations:** Generate insightful visualizations, from straightforward counts to sophisticated aggregations, tailored specifically to your needs.
* **Robust monitoring:** Set up threshold-based and anomaly driven alerts, ensuring proactive visibility into potential issues.
## Why choose Axiom? [#why-choose-axiom]
* **Cost-efficiency:** Axiom dramatically lowers data ingestion and storage costs compared to traditional observability and logging solutions.
* **Flexible insights:** Real-time query capabilities and an increasingly intelligent UI help pinpoint issues and opportunities without sampling.
* **One platform, many use cases:** Use Axiom for observability (logs, metrics, traces), LLM observability, product analytics, and any other machine data workload.
## Getting started [#getting-started]
* [Learn more about Axiom’s features](/platform-overview/features).
* [Explore the interactive demo playground](https://play.axiom.co/).
* [Create your own organization](https://app.axiom.co/register).
* Building with AI agents? Agents can [provision their own temporary organization](/console/intelligence/agent-created-orgs) with a single API request.
---
# API limits
Source: https://axiom.co/docs/restapi/api-limits
Axiom limits the number of calls a user (and their organization) can make over a certain period
of time to ensure fair usage and to maintain the quality of service for everyone.
Axiom systems closely monitor API usage and if a user exceeds any thresholds, Axiom
temporarily halts further processing of requests from that user (and/or organization).
This is to prevent any single user or app from overloading the system,
which could potentially impact other users' experience.
## Rate Limits [#rate-limits]
Rate limits vary and are specified by the following header in all responses:
| Header | Description |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `X-RateLimit-Scope` | Indicates if the limits counts against the organisation or personal rate limit. |
| `X-RateLimit-Limit` | The maximum number of requests a user is permitted to make per minute. |
| `X-RateLimit-Remaining` | The number of requests remaining in the current rate limit window. |
| `X-RateLimit-Reset` | The time at which the current rate limit window resets in UTC [epoch seconds](https://en.wikipedia.org/wiki/Unix_time). |
**Possible values for X-RateLimit-Scope :**
* `user`
* `organization`
**When the rate limit is exceeded, an error is returned with the status "429 Too Many Requests"**:
```json
{
"message": "rate limit exceeded",
}
```
## Query Limits [#query-limits]
| Header | Description |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------- |
| `X-QueryLimit-Limit` | The query cost limit of your plan in Gigabyte Milliseconds (GB\*ms). |
| `X-QueryLimit-Remaining` | The remaining query Gigabyte Milliseconds. |
| `X-QueryLimit-Reset` | The time at which the current rate limit window resets in UTC [epoch seconds](https://en.wikipedia.org/wiki/Unix_time). |
## Ingest Limits [#ingest-limits]
| Header | Description |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `X-IngestLimit-Limit` | The maximum bytes ingested a user is permitted to make per month. |
| `X-IngestLimit-Remaining` | The bytes ingested remaining in the current rate limit window. |
| `X-IngestLimit-Reset` | The time at which the current rate limit window resets in UTC [epoch seconds](https://en.wikipedia.org/wiki/Unix_time). |
Alongside data volume limits, Axiom also monitors the rate of ingest requests.
If an organization consistently sends an excessive number of requests per second,
far exceeding normal usage patterns, Axiom reserves the right to suspend their ingest
to maintain system stability and ensure fair resource allocation for all users.
To prevent exceeding these rate limits, it’s highly recommended to use batching clients,
which can efficiently manage the number of requests by aggregating data before sending.
## Limits on ingested data [#limits-on-ingested-data]
For more information on limits and requirements imposed by Axiom, see [Limits](/reference/limits).
---
# Dashboard JSON
Source: https://axiom.co/docs/restapi/dashboard-json
The [Create dashboard](/restapi/endpoints/createDashboard) and [Update dashboard](/restapi/endpoints/updateDashboard) endpoints take a dashboard document in the `dashboard` field of the request body. The [Retrieve dashboard](/restapi/endpoints/getDashboard) endpoint returns the same document. This page explains the structure of the dashboard document.
## JSON Schema [#json-schema]
Axiom publishes a JSON Schema for the dashboard document:
```txt
https://axiom.co/docs/schemas/dashboard.json
```
The schema describes every field and every chart type. Axiom generates it from the v2 OpenAPI spec, which is available at `https://axiom.co/docs/openapi/v2.json`.
To check a dashboard document before you send it, validate it against the schema. For example, with [check-jsonschema](https://check-jsonschema.readthedocs.io/):
```bash
uvx check-jsonschema --schemafile https://axiom.co/docs/schemas/dashboard.json dashboard.json
```
Don't add a `$schema` field to the dashboard document. The API rejects unknown top-level fields.
## Top-level fields [#top-level-fields]
| Field | Required | Description |
| ------------------ | -------- | ------------------------------------------------------------------------------------------------------------ |
| `name` | Yes | Dashboard name, up to 100 characters. |
| `owner` | Yes | User ID of the owner. Use `X-AXIOM-EVERYONE` to share the dashboard with everyone in the organization. |
| `schemaVersion` | Yes | Version of the dashboard format. Use `2`. |
| `refreshTime` | Yes | Seconds between automatic refreshes: `0` (off), `15`, `60`, or `300`. |
| `timeWindowStart` | Yes | Start of the time range. For example, `qr-now-1h` for the last hour, or Unix epoch milliseconds as a string. |
| `timeWindowEnd` | Yes | End of the time range. Use `qr-now` with a relative start, or Unix epoch milliseconds as a string. |
| `charts` | Yes | Dashboard elements. For more information, see [Charts](#charts). |
| `layout` | Yes | Position and size of each chart. For more information, see [Layout](#layout). |
| `sections` | No | Collapsible sections in display order. For more information, see [Sections](#sections). |
| `description` | No | Dashboard description, up to 1,000 characters. |
| `against` | No | Relative offset for comparison against a previous period. For example, `-1d`. |
| `againstTimestamp` | No | Absolute or relative timestamp for comparison. Use either `against` or `againstTimestamp`. |
| `uid` | No | Stable dashboard identifier. Letters, digits, `_`, and `-`, up to 128 characters. |
## Charts [#charts]
Each element of `charts` is an object with the following fields:
* `id`: Identifier of the chart. Use any string of up to 200 characters that is unique in the dashboard.
* `type`: Chart type. One of `TimeSeries`, `Heatmap`, `LogStream`, `Pie`, `Scatter`, `Table`, `TopK`, `Statistic`, `Gauge`, `Note`, `MonitorList`, `SmartFilter`, `Spacer`, or `Visualize`.
* `sectionId`: Optional. ID of the section that contains the chart.
Charts that run a query take it in the `query` field. Use `query.apl` for an APL query or `query.mpl` for an MPL query. The other fields depend on the chart type. In the JSON Schema, the definition for each chart type is in `$defs`, named after the type. For example, `$defs.TimeSeriesChart` and `$defs.NoteChart`.
## Layout [#layout]
The dashboard is a grid with 12 columns. Each chart needs one element in `layout`:
* `i`: ID of the chart.
* `x`: Column where the chart starts, from `0` to `11`.
* `y`: Row where the chart starts.
* `w`: Width in columns, from `1` to `12`.
* `h`: Height in rows.
## Sections [#sections]
`sections` lists the sections of the dashboard from top to bottom. Each section has the following fields:
* `id`: Identifier of the section. Must be a UUID.
* `title`: Section name, up to 200 characters.
* `defaultCollapsed`: Optional. If `true`, the section is collapsed when the dashboard opens.
To place a chart in a section, set the chart's `sectionId` to the section's `id`. Charts without a `sectionId` appear above the first section. For more information, see [Dashboard sections](/dashboards/sections).
## Rules outside the schema [#rules-outside-the-schema]
JSON Schema can't express some rules that a valid dashboard follows:
* Chart IDs, layout `i` values, and section IDs are unique.
* Every chart has a layout element whose `i` is the chart's `id`, and every layout element refers to a chart.
* Every `sectionId` is the `id` of an element in `sections`.
* `SmartFilter` charts have no `sectionId`. Filter bars apply to the entire dashboard.
## Example [#example]
The following dashboard document contains a note outside all sections and a time series chart in a section:
```json
{
"name": "HTTP service overview",
"owner": "X-AXIOM-EVERYONE",
"description": "Request volume for the HTTP service",
"schemaVersion": 2,
"refreshTime": 60,
"timeWindowStart": "qr-now-1h",
"timeWindowEnd": "qr-now",
"sections": [
{ "id": "5b0e7d4a-3c1f-4e2a-9a6b-1f2d3c4b5a69", "title": "Traffic" }
],
"charts": [
{
"id": "about",
"type": "Note",
"text": "Charts in **Traffic** show requests to the HTTP service."
},
{
"id": "requests",
"type": "TimeSeries",
"name": "Requests",
"sectionId": "5b0e7d4a-3c1f-4e2a-9a6b-1f2d3c4b5a69",
"query": { "apl": "['http-logs'] | summarize count() by bin_auto(_time)" }
}
],
"layout": [
{ "i": "about", "x": 0, "y": 0, "w": 12, "h": 2 },
{ "i": "requests", "x": 0, "y": 2, "w": 12, "h": 6 }
]
}
```
To create the dashboard, send the document in the `dashboard` field:
```bash
curl -X 'POST' 'https://api.axiom.co/v2/dashboards' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{ "dashboard": DASHBOARD_JSON }'
```
Replace `API_TOKEN` with your API token and `DASHBOARD_JSON` with the dashboard document.
---
# Send data to Axiom via API
Source: https://axiom.co/docs/restapi/ingest
The Axiom REST API accepts the following data formats:
* [JSON](#send-data-in-json-format)
* [NDJSON](#send-data-in-ndjson-format)
* [CSV](#send-data-in-csv-format)
This page explains how to send data to Axiom via cURL commands in each of these formats, and how to send data with the [Axiom Node.js library](#send-data-with-axiom-node-js).
For more information on choosing an ingest format, see [Optimize data loading](/reference/optimize-usage#optimize-data-loading).
For more information on other ingest options, see [Send data](/send-data/methods).
For an introduction to the basics of the Axiom API and to the authentication options, see [Introduction to Axiom API](/restapi/introduction).
The API requests on this page use the ingest data endpoint. For more information, see the [API reference](/restapi/endpoints/ingestToDataset).
The [Ingest data endpoint](/restapi/endpoints/ingestToDataset) only supports API tokens. Personal access tokens (PATs) aren't supported. For more information, see [Tokens](/reference/tokens).
## Send data in JSON format [#send-data-in-json-format]
To send data to Axiom in JSON format:
1. Encode the events as JSON objects.
2. Enter the array of JSON objects into the body of the API request.
3. Optional: In the body of the request, set optional parameters such as `timestamp-field` and `timestamp-format`. For more information, see the [ingest data API reference](/restapi/endpoints/ingestToDataset).
4. Set the `Content-Type` header to `application/json`.
5. Set the `Authorization` header to `Bearer API_TOKEN`.
6. Send the POST request to `https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME`.
### Example with grouped events [#example-with-grouped-events]
The following example request contains grouped events. The structure of the JSON payload has the scheme of `[ { "labels": { "key1": "value1", "key2": "value2" } }, ]` where the array contains one or more JSON objects describing events.
**Example request**
```bash
curl -X 'POST' 'https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '[
{
"time":"2025-01-12T00:00:00.000Z",
"data":{"key1":"value1","key2":"value2"}
},
{
"data":{"key3":"value3"},
"labels":{"key4":"value4"}
}
]'
```
**Example response**
```json
{
"ingested": 2,
"failed": 0,
"failures": [],
"processedBytes": 219,
"blocksCreated": 0,
"walLength": 2
}
```
### Example with nested arrays [#example-with-nested-arrays]
**Example request**
```bash
curl -X 'POST' 'https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '[
{
"axiom": [{
"logging":[{
"observability":[{
"location":[{
"credentials":[{
"datasets":[{
"first_name":"axiom",
"last_name":"logging",
"location":"global"
}],
"work":[{
"details":"https://app.axiom.co/",
"tutorials":"https://www.axiom.co/blog",
"changelog":"https://www.axiom.co/changelog",
"documentation": "https://www.axiom.co/docs"
}]
}],
"social_media":[{
"details":[{
"twitter":"https://twitter.com/AxiomFM",
"linkedin":"https://linkedin.com/company/axiomhq",
"github":"https://github.com/axiomhq"
}],
"features":[{
"datasets":"view logs",
"stream":"live_tail",
"explorer":"queries"
}]
}]
}]
}],
"logs":[{
"apl": "functions"
}]
}],
"storage":[{}]
}]}
]'
```
**Example response**
```json
{
"ingested":1,
"failed":0,
"failures":[],
"processedBytes":1587,
"blocksCreated":0,
"walLength":3
}
```
### Example with objects, strings, and arrays [#example-with-objects-strings-and-arrays]
**Example request**
```bash
curl -X 'POST' 'https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '[{ "axiom": {
"logging": {
"observability": [
{ "apl": 23, "function": "tostring" },
{ "apl": 24, "operator": "summarize" }
],
"axiom": [
{ "stream": "livetail", "datasets": [4, 0, 16], "logging": "observability", "metrics": 8, "dashboard": 10, "alerting": "kubernetes" }
]
},
"apl": {
"reference":
[[80, 12], [30, 40]]
}
}
}]'
```
**Example response**
```json
{
"ingested":1,
"failed":0,
"failures":[],
"processedBytes":432,
"blocksCreated":0,
"walLength":4
}
```
## Send data in NDJSON format [#send-data-in-ndjson-format]
To send data to Axiom in NDJSON format:
1. Encode the events as JSON objects.
2. Enter each JSON object in a separate line into the body of the API request.
3. Optional: In the body of the request, set optional parameters such as `timestamp-field` and `timestamp-format`. For more information, see the [ingest data API reference](/restapi/endpoints/ingestToDataset).
4. Set the `Content-Type` header to either `application/json` or `application/x-ndjson`.
5. Set the `Authorization` header to `Bearer API_TOKEN`. Replace `API_TOKEN` with the Axiom API token you have generated.
6. Send the POST request to `https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME`. Replace `DATASET_NAME` with the name of the Axiom dataset where you want to send data.
**Example request**
```bash
curl -X 'POST' 'https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/x-ndjson' \
-d '{"id":1,"name":"machala"}
{"id":2,"name":"axiom"}
{"id":3,"name":"apl"}
{"index": {"_index": "products"}}
{"timestamp": "2016-06-06T12:00:00+02:00", "attributes": {"key1": "value1","key2": "value2"}}
{"queryString": "count()"}'
```
**Example response**
```json
{
"ingested": 6,
"failed": 0,
"failures": [],
"processedBytes": 266,
"blocksCreated": 0,
"walLength": 6
}
```
## Send data in CSV format [#send-data-in-csv-format]
To send data to Axiom in JSON format:
1. Encode the events in CSV format. The first line specifies the field names separated by commas. Subsequent new lines specify the values separated by commas.
2. Enter the CSV representation in the body of the API request.
3. Optional: In the body of the request, set optional parameters such as `timestamp-field` and `timestamp-format`. For more information, see the [ingest data API reference](/restapi/endpoints/ingestToDataset).
4. Set the `Content-Type` header to `text/csv`.
5. Set the `Authorization` header to `Bearer API_TOKEN`. Replace `API_TOKEN` with the Axiom API token you have generated.
6. Send the POST request to `https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME`. Replace `DATASET_NAME` with the name of the Axiom dataset where you want to send data.
**Example request**
```bash
curl -X 'POST' 'https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: text/csv' \
-d 'user, name
foo, bar'
```
**Example response**
```json
{
"ingested": 1,
"failed": 0,
"failures": [],
"processedBytes": 28,
"blocksCreated": 0,
"walLength": 2
}
```
## Send data with Axiom Node.js [#send-data-with-axiom-nodejs]
1. [Install and configure](/guides/javascript#use-axiomhq-js) the Axiom Node.js library.
2. Encode the events as JSON objects.
3. Pass the dataset name and the array of JSON objects to the `axiom.ingest` function.
```ts
axiom.ingest('DATASET_NAME', [{ foo: 'bar' }]);
await axiom.flush();
```
For more information on other libraries you can use to send data, see [Send data](/send-data/methods).
## What’s next [#whats-next]
After ingesting data to Axiom, you can [query it via API](/restapi/query) or the [Axiom Console](/query-data/explore).
---
# Get started with Axiom API
Source: https://axiom.co/docs/restapi/introduction
You can use the Axiom API (Application Programming Interface) to send data to Axiom, query data, and manage resources programmatically. This page covers the basics for interacting with the Axiom API.
## API basics [#api-basics]
Axiom API follows the REST architectural style and uses JSON for serialization. You can send API requests to Axiom with curl or API tools such as [Postman](https://www.postman.com/).
For example, the following curl command ingests data to an Axiom dataset:
```bash
curl -X 'POST' 'https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '[
{
"axiom": "logs"
}
]'
```
For more information, see [Send data to Axiom via API](/restapi/ingest) and [Ingest data endpoint](/restapi/endpoints/ingestToDataset).
## Base domain [#base-domain]
The base domain of an API request depends on the following:
* To ingest data, use the [Ingest data endpoint](/restapi/endpoints/ingestToDataset) with the base domain of your edge deployment.
For more information on edge deployments, see [Edge deployments](/reference/edge-deployments).
* For all other API endpoints, use the base domain `https://api.axiom.co`.
## Content type [#content-type]
Encode the body of API requests as JSON objects and set the `Content-Type` header to `application/json`. Unless otherwise specified, Axiom encodes all responses (including errors) as JSON objects.
## Authentication [#authentication]
To prove that API requests come from you, you must include forms of authentication called tokens in your API requests. Axiom offers two types of tokens:
* [API tokens](/reference/tokens#api-tokens) let you control the actions that can be performed with the token. For example, you can specify that requests authenticated with a certain API token can only query data from a particular dataset.
* [Personal access tokens (PATs)](/reference/tokens#personal-access-tokens-pat) provide full control over your Axiom account. Requests authenticated with a PAT can perform every action you can perform in Axiom. When possible, use API tokens instead of PATs.
If you use an API token for authentication, include the API token in the `Authorization` header.
```bash
Authorization: Bearer API_TOKEN
```
If you use a PAT for authentication, include the PAT in the `Authorization` header and the org ID in the `x-axiom-org-id` header. For more information, see [Determine org ID](/reference/tokens#determine-org-id).
```bash
Authorization: Bearer API_TOKEN
x-axiom-org-id: ORG_ID
```
If authentication is unsuccessful for a request, Axiom returns the error status code `403`.
## Data types [#data-types]
Below is a list of the types of data used within the Axiom API:
| Name | Definition | Example |
| ----------- | ----------------------------------------------------------------- | ------------------------ |
| **ID** | A unique value used to identify resources. | "io12h34io1h24i" |
| **String** | A sequence of characters used to represent text. | "string value" |
| **Boolean** | A type of two possible values representing true or false. | true |
| **Integer** | A number without decimals. | 4567 |
| **Float** | A number with decimals. | 15.67 |
| **Map** | A data structure with a list of values assigned to a unique key. | \{ "key": "value" } |
| **List** | A data structure with only a list of values separated by a comma. | `["value", 4567, 45.67]` |
## What’s next [#whats-next]
* [Ingest data via API](/restapi/ingest)
* [Query data via API](/restapi/query)
---
# Pagination in Axiom API
Source: https://axiom.co/docs/restapi/pagination
Pagination allows you to retrieve responses in manageable chunks.
You can use pagination for the following endpoints:
* [Run APL query to edge deployment](/restapi/endpoints/queryEdge)
* [Run APL query (legacy)](/restapi/endpoints/queryApl)
* [Run Query (Legacy)](/restapi/endpoints/queryDataset)
## Pagination mechanisms [#pagination-mechanisms]
You can use one of the following pagination mechanisms:
* [Pagination based on timestamp](#timestamp-based-pagination) (stable)
* [Pagination based on cursor](#cursor-based-pagination) (public preview)
Axiom recommends timestamp-based pagination. Cursor-based pagination is in public preview and may return unexpected query results.
## Timestamp-based pagination [#timestamp-based-pagination]
The parameters and mechanisms differ between the current and legacy endpoints.
### Run Query [#run-query]
To use timestamp-based pagination with the Run Query endpoint:
* Include the [limit operator](/apl/tabular-operators/limit-operator) in the APL query of your API request. The argument of this operator determines the number of events to display per page.
* Use `sort by _time asc` or `sort by _time desc` in the APL query. This returns the results in ascending or descending chronological order. For more information, see [sort operator](/apl/tabular-operators/sort-operator).
* Specify `startTime` and `endTime` in the body of your API request.
### Run Query (Legacy) [#run-query-legacy]
To use timestamp-based pagination with the legacy Run Query endpoint:
* Add the `limit` parameter to the body of your API request. The value of this parameter determines the number of events to display per page.
* Add the `order` parameter to the body of your API request. In the value of this parameter, order the results by time in either ascending or descending chronological order. For example, `[{ "field": "_time", "desc": true }]`. For more information, see [order operator](/apl/tabular-operators/order-operator).
* Specify `startTime` and `endTime` in the body of your API request.
## Page through the result set [#page-through-the-result-set]
Use the timestamps as boundaries to page through the result set.
### Queries with descending order [#queries-with-descending-order]
To go to the next page of the result set for queries with descending order (`_time desc`):
1. Determine the timestamp of last item on the current page. This is the least recent event.
2. Optional: Subtract 1 nanosecond from the timestamp.
3. In your next request, change the value `endTime` parameter in the body of your API request to the timestamp of the last item (optionally, minus 1 nanosecond).
Repeat this process until the result set is empty.
### Queries with ascending order [#queries-with-ascending-order]
To go to the next page of the result set for queries with ascending order (`_time asc`):
1. Determine the timestamp of last item on the current page. This is the most recent event.
2. Optional: Add 1 nanosecond to the timestamp.
3. In your next request, change the value `startTime` parameter in the body of your API request to the timestamp of the last item (optionally, plus 1 nanosecond).
Repeat this process until the result set is empty.
### Deduplication mechanism [#deduplication-mechanism]
In the procedures above, the steps about incrementing the timestamp are optional. If you increment the timestamp, there is a risk of duplication. If you don’t increment the timestamp, there is a risk of overlap. Duplicated data is possible for many reasons, such as backfill or natural duplication from external data sources. For these reasons, regardless of the method you choose (increment or not increment the timestamp, sort by descending or ascending order), Axiom recommends you implement some form of deduplication mechanism in your pagination script.
### Limits [#limits]
Both the Run Query and the Run Query (Legacy) endpoints allow request-based limit configuration. This means that the limit they use is the lowest of the following: the query limit, the request limit, and Axiom’s server-side internal limit. Without a query or request limit, Axiom currently defaults to the limit of 1,000 events per page. For the pagination of datasets that are greater than 1,000 events, Axioms recommends specifying the same limit in the request and the APL query to avoid the default value and contradictory limits.
### Examples [#examples]
#### Example request Run Query [#example-request-run-query]
```bash
curl -X 'POST' 'https://api.axiom.co/v1/datasets/_apl?format=tabular' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"apl": "DATASET_NAME | sort by _time desc | limit 100",
"startTime": "2024-11-30T00:00:00.000Z",
"endTime": "2024-11-30T23:59:59.999Z"
}'
```
#### Example request Run Query (Legacy) [#example-request-run-query-legacy]
```bash
curl -X 'POST' 'https://api.axiom.co/v1/datasets/DATASET_NAME/query' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"startTime": "2024-11-30T00:00:00.000Z",
"endTime": "2024-11-30T23:59:59.999Z",
"limit": 100,
"order": [{ "field": "_time", "desc": true }]
}'
```
#### Example request to page through the result set [#example-request-to-page-through-the-result-set]
Example request to go to next page for Run Query:
```bash
curl -X 'POST' 'https://api.axiom.co/v1/datasets/_apl?format=tabular' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"apl": "DATASET_NAME | sort by _time desc | limit 100",
"startTime": "2024-11-30T00:00:00.000Z",
"endTime": "2024-11-30T22:59:59.999Z"
}'
```
Example request to go to next page for Run Query (Legacy):
```bash
curl -X 'POST' 'https://api.axiom.co/v1/datasets/DATASET_NAME/query' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"startTime": "2024-11-30T00:00:00.000Z",
"endTime": "2024-11-30T22:59:59.999Z",
"limit": 100,
"order": [{ "field": "_time", "desc": true }]
}'
```
## Cursor-based pagination [#cursor-based-pagination]
Cursor-based pagination is in public preview and may return unexpected query results. Axiom recommends timestamp-based pagination.
The parameters and mechanisms differ between the current and legacy endpoints.
### Run Query [#run-query-1]
To use cursor-based pagination with the Run Query endpoint:
* Include the [`limit` operator](/apl/tabular-operators/limit-operator) in the APL query of your API request. The argument of this operator determines the number of events to display per page.
* Use `sort by _time asc` or `sort by _time desc` in the APL query. This returns the results in ascending or descending chronological order. For more information, see [sort operator](/apl/tabular-operators/sort-operator).
* Specify `startTime` and `endTime` in the body of your API request.
### Run Query (Legacy) [#run-query-legacy-1]
To use cursor-based pagination with the legacy Run Query endpoint:
* Add the `limit` parameter to the body of your API request. The value of this parameter determines the number of events to display per page.
* Add the `order` parameter to the body of your API request. In the value of this parameter, order the results by time in either ascending or descending chronological order. For example, `[{ "field": "_time", "desc": true }]`. For more information, see [order operator](/apl/tabular-operators/order-operator).
* Specify `startTime` and `endTime` in the body of your API request.
### Response format [#response-format]
Contains metadata about the response including pagination information.
Cursor for the first item in the current page.
Cursor for the last item in the current page.
Total number of rows matching the query.
Contains the list of returned objects.
## Page through the result set [#page-through-the-result-set-1]
To page through the result set, add the `cursor` parameter to the body of your API request.
Optional. A cursor for use in pagination. Use the cursor string returned in previous responses to fetch the next or previous page of results.
The `minCursor` and `maxCursor` fields in the response are boundaries that help you page through the result set.
For queries with descending order (`_time desc`), use `minCursor` from the response as the `cursor` in your next request to go to the next page. You reach the end when your provided `cursor` matches the `minCursor` in the response.
For queries with ascending order (`_time asc`), use `maxCursor` from the response as the `cursor` in your next request to go to the next page. You reach the end when your provided `cursor` matches the `maxCursor` in the response.
If the query returns fewer results than the specified limit, paging can stop.
### Examples [#examples-1]
#### Example request Run Query [#example-request-run-query-1]
```bash
curl -X 'POST' 'https://api.axiom.co/v1/datasets/_apl?format=tabular' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"apl": "DATASET_NAME | sort by _time desc | limit 100",
"startTime": "2024-01-01T00:00:00.000Z",
"endTime": "2024-01-31T23:59:59.999Z"
}'
```
#### Example request Run Query (Legacy) [#example-request-run-query-legacy-1]
```bash
curl -X 'POST' 'https://api.axiom.co/v1/datasets/DATASET_NAME/query' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"startTime": "2024-01-01T00:00:00.000Z",
"endTime": "2024-01-31T23:59:59.999Z",
"limit": 100,
"order": [{ "field": "_time", "desc": true }]
}'
```
#### Example response [#example-response]
```json
{
"status": {
"rowsMatched": 2500,
"minCursor": "0d3wo7v7e1oii-075a8c41710018b9-0000ecc5",
"maxCursor": "0d3wo7v7e1oii-075a8c41710018b9-0000faa3"
},
"matches": [
// ... events ...
]
}
```
#### Example request to page through the result set [#example-request-to-page-through-the-result-set-1]
To page through the result set, use the appropriate cursor value in your next request. For more information, see [Page through the result set](#page-through-the-result-set).
Example request to go to next page for Run Query:
```bash
curl -X 'POST' 'https://api.axiom.co/v1/datasets/_apl?format=tabular' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"apl": "DATASET_NAME | sort by _time desc | limit 100",
"startTime": "2024-01-01T00:00:00.000Z",
"endTime": "2024-01-31T23:59:59.999Z",
"cursor": "0d3wo7v7e1oii-075a8c41710018b9-0000ecc5"
}'
```
Example request to go to next page for Run Query (Legacy):
```bash
curl -X 'POST' 'https://api.axiom.co/v1/datasets/DATASET_NAME/query' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"startTime": "2024-01-01T00:00:00.000Z",
"endTime": "2024-01-31T23:59:59.999Z",
"limit": 100,
"order": [{ "field": "_time", "desc": true }],
"cursor": "0d3wo7v7e1oii-075a8c41710018b9-0000ecc5"
}'
```
---
# Query data via Axiom API
Source: https://axiom.co/docs/restapi/query
This page explains how to query data via the Axiom API using the following:
* [cURL](#query-data-with-curl)
* [Axiom JavaScript library (`@axiomhq/js`)](#query-data-with-the-axiom-javascript-library)
For an introduction to the basics of the Axiom API and to the authentication options, see [Introduction to Axiom API](/restapi/introduction).
The API requests on this page use the query data endpoint. For more information, see the [API reference](/restapi/endpoints/queryEdge).
## Query data with cURL [#query-data-with-curl]
To query data with cURL:
1. Build the APL query. For more information, see [Introduction to APL](/apl/introduction).
2. Encode the APL query as a JSON object and enter it into the body of the API request.
3. Optional: In the body of the request, set optional parameters such as `startTime` and `endTime`. For more information, see the [query data API reference](/restapi/endpoints/queryEdge).
4. Set the `Content-Type` header to `application/json`.
5. Set the `Authorization` header to `Bearer API_TOKEN`.
6. Send the POST request to one of the following:
* For tabular output, use `https://AXIOM_DOMAIN/v1/query/_apl?format=tabular`.
* For legacy output, use `https://AXIOM_DOMAIN/v1/query/_apl?format=legacy`.
### Example [#example]
```bash
curl --request POST \
--url 'https://AXIOM_DOMAIN/v1/query/_apl?format=tabular' \
--header 'Authorization: Bearer API_TOKEN' \
--header 'Content-Type: application/json' \
--data '{
"apl": "DATASET_NAME | limit 10",
"startTime": "string",
"endTime": "string"
}'
```
**Example response**
```json [expandable]
{
"format": "tabular",
"status": {
"elapsedTime": 260650,
"minCursor": "0d8q6stroluyo-07c3957e7400015c-0000c875",
"maxCursor": "0d8q6stroluyo-07c3957e7400015c-0000c877",
"blocksExamined": 4,
"blocksCached": 0,
"blocksMatched": 0,
"rowsExamined": 197604,
"rowsMatched": 197604,
"numGroups": 0,
"isPartial": false,
"cacheStatus": 1,
"minBlockTime": "2025-03-26T12:03:14Z",
"maxBlockTime": "2025-03-26T12:12:42Z"
},
"tables": [
{
"name": "0",
"sources": [
{
"name": "DATASET_NAME"
}
],
"fields": [
{
"name": "_sysTime",
"type": "datetime"
},
{
"name": "_time",
"type": "datetime"
},
{
"name": "content_type",
"type": "string"
},
{
"name": "geo.city",
"type": "string"
},
{
"name": "geo.country",
"type": "string"
},
{
"name": "id",
"type": "string"
},
{
"name": "is_tls",
"type": "boolean"
},
{
"name": "message",
"type": "string"
},
{
"name": "method",
"type": "string"
},
{
"name": "req_duration_ms",
"type": "float"
},
{
"name": "resp_body_size_bytes",
"type": "integer"
},
{
"name": "resp_header_size_bytes",
"type": "integer"
},
{
"name": "server_datacenter",
"type": "string"
},
{
"name": "status",
"type": "string"
},
{
"name": "uri",
"type": "string"
},
{
"name": "user_agent",
"type": "string"
},
{
"name": "is_ok_2 ",
"type": "boolean"
},
{
"name": "city_str_len",
"type": "integer"
}
],
"order": [
{
"field": "_time",
"desc": true
}
],
"groups": [],
"range": {
"field": "_time",
"start": "1970-01-01T00:00:00Z",
"end": "2025-03-26T12:12:43Z"
},
"columns": [
[
"2025-03-26T12:12:42.68112905Z",
"2025-03-26T12:12:42.68112905Z",
"2025-03-26T12:12:42.68112905Z"
],
[
"2025-03-26T12:12:42Z",
"2025-03-26T12:12:42Z",
"2025-03-26T12:12:42Z"
],
[
"text/html",
"text/plain-charset=utf-8",
"image/jpeg"
],
[
"Ojinaga",
"Humboldt",
"Nevers"
],
[
"Mexico",
"United States",
"France"
],
[
"8af366cf-6f25-42e6-bbb4-d860ab535a60",
"032e7f68-b0ab-47c0-a24a-35af566359e5",
"4d2c7baa-ff28-4b1f-9db9-8e6c0ed5a9c9"
],
[
false,
false,
true
],
[
"QCD permutations were not solvable in linear time, expected compressed time",
"QCD permutations were not solvable in linear time, expected compressed time",
"Expected a new layer of particle physics but got a Higgs Boson"
],
[
"GET",
"GET",
"GET"
],
[
1.396373193863436,
0.16252390534308514,
0.4093416175186162
],
[
3448,
2533,
1906
],
[
84,
31,
29
],
[
"DCA",
"GRU",
"FRA"
],
[
"201",
"200",
"200"
],
[
"/api/v1/buy/commit/id/go",
"/api/v1/textdata/cnfigs",
"/api/v1/bank/warn"
],
[
"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko",
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
"Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))"
],
[
true,
true,
true
],
[
7,
8,
6
]
]
}
],
"datasetNames": [
"DATASET_NAME"
],
"fieldsMetaMap": {
"DATASET_NAME": [
{
"name": "status",
"type": "",
"unit": "",
"hidden": false,
"description": "HTTP status code"
},
{
"name": "resp_header_size_bytes",
"type": "integer",
"unit": "none",
"hidden": false,
"description": ""
},
{
"name": "geo.city",
"type": "string",
"unit": "",
"hidden": false,
"description": "the city"
},
{
"name": "resp_body_size_bytes",
"type": "integer",
"unit": "decbytes",
"hidden": false,
"description": ""
},
{
"name": "content_type",
"type": "string",
"unit": "",
"hidden": false,
"description": ""
},
{
"name": "geo.country",
"type": "string",
"unit": "",
"hidden": false,
"description": ""
},
{
"name": "req_duration_ms",
"type": "float",
"unit": "ms",
"hidden": false,
"description": "Request duration"
}
]
}
}
```
## Query data with the Axiom JavaScript library [#query-data-with-the-axiom-javascript-library]
1. [Install and configure](/guides/javascript#use-axiomhq-js) the Axiom JavaScript library (`@axiomhq/js`).
2. Build the APL query. For more information, see [Introduction to APL](/apl/introduction).
3. Pass the APL query as a string to the `axiom.query` function.
```ts
const res = await axiom.query(`['DATASET_NAME'] | where foo == 'bar' | limit 100`);
console.log(res);
```
To run queries within a specific edge deployment, set the `edge` option when you create the client. The client then routes queries to the [edge query endpoint](/restapi/endpoints/queryEdge) automatically. For more information, see [Configure region](/guides/javascript#configure-region).
For more examples, see the [examples in GitHub](https://github.com/axiomhq/axiom-js/tree/main/examples).
---
# Enrich Axiom experience with AWS PrivateLink
Source: https://axiom.co/docs/apps/aws-privatelink
[AWS PrivateLink](https://aws.amazon.com/privatelink/) is a networking service provided by Amazon Web Services (AWS) that allows you to securely access services hosted on the AWS cloud over a private network connection. With AWS PrivateLink, you can access Axiom directly from your AWS without an internet gateway or NAT device, simplifying your network setup.
## Cross-region support [#cross-region-support]
Axiom supports native cross-region PrivateLink for the following regions:
| Axiom edge deployment | Supported PrivateLink regions |
| :-------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `US East 1 (AWS)` | `us-east-1` `us-east-2` `us-west-1` `us-west-2` `eu-west-1` `eu-west-2` `eu-west-3` `eu-central-1` `ca-central-1` |
| `EU Central 1 (AWS)` | `eu-central-1` `eu-north-1` |
To connect to a region that isn't listed above, [contact Axiom](https://axiom.co/contact).
For more information, see [Edge deployments](/reference/edge-deployments).
## Setup [#setup]
Use the service details for your edge deployment to set up the VPC endpoint.
| Axiom edge deployment | PrivateLink service name | PrivateLink service region |
| :-------------------- | :----------------------------------------------------------- | :------------------------- |
| `US East 1 (AWS)` | `com.amazonaws.vpce.us-east-1.vpce-svc-0daeb6c5a00337061` | `us-east-1` |
| `EU Central 1 (AWS)` | `com.amazonaws.vpce.eu-central-1.vpce-svc-00e8d47e8c60784f7` | `eu-central-1` |
1. In your VPC Console, go to **PrivateLink and Lattice > Endpoints**, and then click **Create endpoint**.
2. Select **PrivateLink ready partner services**, and then enter the service name for your edge deployment.
3. Under **Service Region**, turn on **Cross-region endpoint**, and then select the service region for your edge deployment. This is the region where the Axiom service is hosted, and it's independent of your VPC's region.
4. Click **Verify service**.
5. Select the VPC and subnets that you want to connect to the Axiom VPC service endpoint. Ensure that **Enable DNS name** is turned on and the security group accepts inbound traffic on TCP port `443`.
6. Finish the setup and wait for the VPC endpoint to become available. This usually takes 10 minutes.
---
# Connect Axiom with Cloudflare Logpush
Source: https://axiom.co/docs/apps/cloudflare-logpush
Cloudflare Logpush is a feature that allows you to push HTTP request logs and other Cloudflare-generated logs directly to your desired storage, analytics, and monitoring solutions like Axiom. The integration with Axiom aims to provide real-time insights into web traffic, and operational issues, thereby helping to monitor and troubleshoot effectively.
The Cloudflare Logpush integration supports all [edge deployments](/reference/edge-deployments). The integration sends data to your organization’s default edge deployment automatically, without any additional configuration.
## What’s Cloudflare Logpush? [#whats-cloudflare-logpush]
Cloudflare Logpush enables Cloudflare users to automatically export their logs in JSON format to a variety of endpoints. This feature is incredibly useful for analytics, auditing, debugging, and monitoring the performance and security of websites. Types of logs you can export include HTTP request logs, firewall events, and more.
## Installing Cloudflare Logpush app [#installing-cloudflare-logpush-app]
### Prerequisites [#prerequisites]
* An active Cloudflare Enterprise account
* API token or global API key
You can create a token that has access to a single zone, single account or a mix of all these, depending on your needs. For account access, the token must
have these permissions:
* Logs: Edit
* Account settings: Read
For the zones, only edit permission is required for logs.
**Zero Trust datasets require an additional permission.** To create Logpush jobs for Cloudflare Zero Trust datasets (Access, Gateway, and DEX) — for example **Access requests**, **Gateway DNS**, **Gateway HTTP**, **Gateway Network**, and **Zero Trust Network Session Logs** — your token must also have the **Zero Trust: PII Read** permission in addition to **Logs: Edit**. These datasets can contain personally identifiable information (such as private IP addresses, user names, and device names), and Cloudflare blocks the job with a `missing required permissions` error when this permission isn't granted.
The standard **Administrator** role includes **Logs: Edit** but not Zero Trust PII access, so an admin or owner account alone isn't enough. A **Super Administrator** must assign the **Cloudflare Zero Trust PII** role to the user (or grant the token the **Zero Trust: PII Read** permission) before these jobs can be created. If you don't use Cloudflare Zero Trust, Gateway, or Access, you can leave these datasets unselected.
## Steps [#steps]
* Log in to Cloudflare, go to your Cloudflare dashboard, and then select the Enterprise zone (domain) you want to enable Logpush for.
* Optionally, set filters and fields. You can filter logs by field (like Client IP, User Agent, etc.) and set the type of logs you want (for example, HTTP requests, firewall events).
* In Axiom, click **Settings**, select **Apps**, and install the Cloudflare Logpush app with the token you created from the profile settings in Cloudflare.
* You see your available accounts and zones. Select the Cloudflare datasets you want to subscribe to.
* The installation uses the Cloudflare API to create Logpush jobs for each selected dataset.
* After the installation completes, you can find the installed Logpush jobs at Cloudflare.
For zone-scoped Logpush jobs:
For account-scoped Logpush jobs:
* In the Axiom, you can see your Cloudflare Logpush dashboard.
Using Axiom with Cloudflare Logpush offers a powerful solution for real-time monitoring, observability, and analytics. Axiom can help you gain deep insights into your app’s performance, errors, and app bottlenecks.
### Benefits of using the Axiom Cloudflare Logpush Dashboard [#benefits-of-using-the-axiom-cloudflare-logpush-dashboard]
* Real-time visibility into web performance: One of the most crucial features is the ability to see how your website or app is performing in real-time. The dashboard can show everything from page load times to error rates, giving you immediate insights that can help in timely decision-making.
* Actionable insights for troubleshooting: The dashboard doesn’t just provide raw data; it provides insights. Whether it’s an error that needs immediate fixing or performance metrics that show an error from your app, having this information readily available makes it easier to identify problems and resolve them swiftly.
* DNS metrics: Understanding the DNS requests, DNS queries, and DNS cache hit from your app is vital to track if there’s a request spike or get the total number of queries in your system.
* Centralized logging and error tracing: With logs coming in from various parts of your app stack, centralizing them within Axiom makes it easier to correlate events across different layers of your infrastructure. This is crucial for troubleshooting complex issues that may span multiple services or components.
## Supported Cloudflare Logpush Datasets [#supported-cloudflare-logpush-datasets]
Axiom supports all the Cloudflare account-scoped datasets.
Zone-scoped
* DNS logs
* Firewall events
* HTTP requests
* NEL reports
* Spectrum events
Account-scoped
* Access requests
* Audit logs
* CASB Findings
* Device posture results
* DNS Firewall Logs
* Gateway DNS
* Gateway HTTP
* Gateway Network
* Magic IDS Detections
* Network Analytics Logs
* Workers Trace Events
* Zero Trust Network Session Logs
The Zero Trust, Gateway, and Access datasets (**Access requests**, **Gateway DNS**, **Gateway HTTP**, **Gateway Network**, and **Zero Trust Network Session Logs**) require the **Zero Trust: PII Read** token permission in addition to **Logs: Edit**. See [Prerequisites](#prerequisites) above. Without it, Cloudflare returns a `missing required permissions` error for these datasets.
---
# Connect Axiom with Cloudflare Workers
Source: https://axiom.co/docs/apps/cloudflare-workers
The Axiom Cloudflare Workers app provides granular detail about the traffic coming in from your monitored sites. This includes edge requests, static resources, client auth, response duration, and status. Axiom gives you an all-at-once view of key Cloudflare Workers metrics and logs, out of the box, with the dynamic Cloudflare Workers dashboard.
The data obtained with the Axiom dashboard gives you better insights into the state of your Cloudflare Workers so you can easily monitor bad requests, popular URLs, cumulative execution time, successful requests, and more. The app is part of Axiom’s unified logging and observability platform, so you can easily track Cloudflare Workers edge requests alongside a comprehensive view of other resources in your Cloudflare Worker environments.
Axiom Cloudflare Workers is an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/axiom-cloudflare-workers).
## What’s Cloudflare Workers [#whats-cloudflare-workers]
[Cloudflare Workers](https://developers.cloudflare.com/workers/) is a serverless computing platform developed by Cloudflare. The Workers platform allows developers to deploy and run JavaScript code directly at the network edge in more than 200 data centers worldwide. This serverless architecture enables high performance, low latency, and efficient scaling for web apps and APIs.
## Send Cloudflare Worker logs to Axiom [#send-cloudflare-worker-logs-to-axiom]
1. In Cloudflare, create a new worker. For more information, see the [Cloudflare documentation](https://developers.cloudflare.com/workers/get-started/guide/).
2. Copy the contents of the [src/worker.js](https://github.com/axiomhq/axiom-cloudflare-workers/blob/main/src/worker.js) file into the worker you have created.
3. Update the authentication variables:
```bash
const axiomDataset = "DATASET_NAME"
const axiomToken = "API_TOKEN"
```
4. Add triggers for the worker. For example, add a route trigger using the [Cloudflare documentation](https://developers.cloudflare.com/workers/configuration/routing/routes/#set-up-a-route-in-the-dashboard).
When the routes receive requests, the worker is triggered and the logs are sent to your Axiom dataset.
---
# Connect Axiom with Convex
Source: https://axiom.co/docs/apps/convex
Connect Axiom with [Convex](https://convex.dev) to get comprehensive observability into your backend functions and app events. Stream function executions, console logs, and metadata from your Convex deployment to Axiom for powerful querying, data visualization, and monitoring.
This page explains how to connecting with Convex can enhance your Axiom experience. For instructions on streaming data from Convex to Axiom, see [Send data from Convex](/send-data/convex).
## Convex and log streams [#convex-and-log-streams]
[Convex](https://convex.dev) is the backend platform that keeps your app in sync. It’s the open source, reactive database where queries are TypeScript code running right in the database. Just like React components react to state changes, Convex queries react to database changes.
Convex provides a database, a place to write your server functions, and client libraries. It makes it easy to build and scale dynamic live-updating apps.
Log streams enable streaming of events such as function executions and `console.log`s from your Convex deployment to supported destinations like Axiom, Datadog, or custom webhooks.
Log streams require a Convex Professional plan. Learn more about [Convex pricing plans](https://www.convex.dev/pricing) or upgrade your account.
## Benefits of connecting Axiom with Convex [#benefits-of-connecting-axiom-with-convex]
Convex’s built-in features allow you to see the most recent logs produced by your deployment. Additionally, log streaming to Axiom provides comprehensive observability for your backend operations.
* **Historical log storage** beyond the recent logs view.
* **Powerful querying** with Axiom Processing Language (APL).
* **Advanced data visualization** and custom dashboards.
* **Integration with monitoring tools** like PagerDuty, Slack, and more.
* **Real-time alerting** based on function performance and errors.
## Analyze function performance [#analyze-function-performance]
Convex log streams send structured data to Axiom that includes the following key fields:
* **`['data.topic']`**: Event type
* **`['data.status']`**: Execution status
* **`['data.function.path']`**: Full function path
* **`['data.function.type']`**: Function type
* **`['data.function.component_path']`**: Component path
* **`['data.execution_time_ms']`**: Function execution time in milliseconds
* **`['data.usage.database_read_documents']`**: Number of documents read
* **`['data.usage.database_read_bytes']`**: Bytes of data read
* **`['data.function.cached']`**: Cache hit indicator for queries
* **`['convex.project_slug']`**: Convex project identifier
* **`['convex.deployment_name']`**: Deployment name
* **`['convex.deployment_type']`**: Deployment type
After sending Convex log streams to Axiom, explore your Convex data and analyze your function performance using Axiom’s powerful [query capabilities](/query-data/query-editor).
Identify slow-performing functions by analyzing execution times:
```kusto
['convex']
| where ['data.topic'] == "function_execution"
| summarize
avg_time_ms = avg(['data.execution_time_ms']),
max_time_ms = max(['data.execution_time_ms']),
total_calls = count()
by ['data.function.path']
| order by avg_time_ms desc
```
Track functions that are experiencing failures:
```kusto
['convex']
| where ['data.topic'] == "function_execution" and ['data.status'] == "failure"
| summarize count() by ['data.function.path'], ['data.function.type']
| order by count_ desc
```
Compare performance across different function types (queries, mutations, actions):
```kusto
['convex']
| where ['data.topic'] == "function_execution"
| summarize
total_calls = count(),
avg_duration_ms = avg(['data.execution_time_ms'])
by ['data.function.type']
```
Track database read patterns and identify resource-intensive functions:
```kusto
['convex']
| where ['data.topic'] == "function_execution"
| summarize
avg_docs_read = avg(['data.usage.database_read_documents']),
avg_bytes_read = avg(['data.usage.database_read_bytes'])
by ['data.function.path']
| order by avg_bytes_read desc
```
Track query cache hit rates for optimization:
```kusto
['convex']
| where ['data.topic'] == "function_execution"
and ['data.function.type'] == "query"
and isnotempty(['data.function.cached'])
| summarize
cache_hits = countif(['data.function.cached'] == true),
total_queries = count()
| extend cache_hit_rate = (cache_hits * 100) / total_queries
```
Track scheduled job lag and performance:
```kusto
['convex']
| where ['data.topic'] == "scheduled_job_lag"
| summarize
max_lag_seconds = max(['data.lag_seconds']),
avg_lag_seconds = avg(['data.lag_seconds'])
by ['convex.project_slug'], ['convex.deployment_name']
```
## Highlight console log levels [#highlight-console-log-levels]
Axiom supports [severity matching](/reference/limits#requirements-for-log-level-fields) for Convex console logs.
## Set up monitoring and alerting [#set-up-monitoring-and-alerting]
[Create monitors](/monitor-data/monitors) to get notified about issues in your Convex deployment.
Monitor functions with high error rates:
```kusto
['convex']
| where ['data.topic'] == "function_execution"
| summarize
total_calls = count(),
failures = countif(['data.status'] == "failure")
by ['data.function.path']
| extend error_rate = (failures * 100) / total_calls
| where error_rate > 5 // Alert if error rate exceeds 5%
```
Set up alerts for functions exceeding execution time thresholds:
```kusto
['convex']
| where ['data.topic'] == "function_execution" and ['data.execution_time_ms'] > 5000
| summarize count() by ['data.function.path']
```
## Prebuilt dashboard [#prebuilt-dashboard]
When you configure a Convex dataset in Axiom, a dashboard is automatically created in the **Integrations** section of the Dashboards tab. This prebuilt dashboard provides immediate insights into your Convex function performance and errors.
The dashboard includes:
* **Function execution metrics**: Success rates, error counts, and performance trends.
* **Database operation insights**: Query patterns, mutation frequencies, and subscription activity.
* **Error analysis**: Error types, frequency, and affected functions.
* **Performance monitoring**: Response times, throughput, and resource utilization.
You can customize this dashboard or create additional dashboards tailored to your specific monitoring needs and business requirements. For more information, see [Create dashboards](/dashboards/create) and [Configure dashboards](/dashboards/configure).
## Next steps [#next-steps]
* [Explore your Convex data](/query-data/query-editor) in Axiom and [learn APL](/apl/introduction) to query your Convex logs.
* [Create custom dashboards](/dashboards/create) for your team.
* [Set up monitors](/monitor-data/monitors) to get alerted about issues.
---
# Connect Axiom with Grafana
Source: https://axiom.co/docs/apps/grafana
## What’s a Grafana data source plugin? [#whats-a-grafana-data-source-plugin]
Grafana is an open-source tool for time-series analytics, visualization, and alerting. It’s frequently used in DevOps and IT Operations roles to provide real-time information on system health and performance.
Data sources in Grafana are the actual databases or services where the data is stored. Grafana has a variety of data source plugins that connect Grafana to different types of databases or services. This enables Grafana to query those sources from display that data on its dashboards. The data sources can be anything from traditional SQL databases to time-series databases or metrics, and logs from Axiom.
A Grafana data source plugin extends the functionality of Grafana by allowing it to interact with a specific type of data source. These plugins enable users to extract data from a variety of different sources, not just those that come supported by default in Grafana.
## Prerequisites [#prerequisites]
* [Create an Axiom account](https://app.axiom.co/register).
* [Create a dataset in Axiom](/reference/datasets#create-dataset) where you send your data.
* [Create an advanced API token in Axiom](/reference/tokens#create-advanced-api-token) with permissions to query data from the dataset you have created. Basic API tokens only allow data ingestion and won't work with Grafana.
## Install the Axiom Grafana data source plugin on Grafana Cloud [#install-the-axiom-grafana-data-source-plugin-on-grafana-cloud]
* In Grafana, click Administration > Plugins in the side navigation menu to view installed plugins.
* In the filter bar, search for the Axiom plugin
* Click on the plugin logo.
* Click Install.
When the update is complete, a confirmation message is displayed, indicating that the installation was successful.
* The Axiom Grafana Plugin is also installable from the [Grafana Plugins page](https://grafana.com/grafana/plugins/axiomhq-axiom-datasource/)
## Install the Axiom Grafana data source plugin on local Grafana [#install-the-axiom-grafana-data-source-plugin-on-local-grafana]
The Axiom data source plugin for Grafana is [open source on GitHub](https://github.com/axiomhq/axiom-grafana). It can be installed via the Grafana CLI, or via Docker.
### Install the Axiom Grafana Plugin using Grafana CLI [#install-the-axiom-grafana-plugin-using-grafana-cli]
```bash
grafana-cli plugins install axiomhq-axiom-datasource
```
### Install Via Docker [#install-via-docker]
* Add the plugin to your `docker-compose.yml` or `Dockerfile`
* Set the environment variable `GF_INSTALL_PLUGINS` to include the plugin
Example:
`GF_INSTALL_PLUGINS="axiomhq-axiom-datasource"`
## Configuration [#configuration]
* Add a new data source in Grafana
* Select the Axiom data source type.
* Enter the previously generated API token.
* Save and test the data source.
## Build Queries with Query Editor [#build-queries-with-query-editor]
The Axiom data source Plugin provides a custom query editor to build and visualize your Axiom event data. After configuring the Axiom data source, start building visualizations from metrics and logs stored in Axiom.
* Create a new panel in Grafana by clicking on Add visualization
* Select the Axiom data source.
* Use the query editor to choose the desired metrics, dimensions, and filters.
## Query limits [#query-limits]
The Axiom data source doesn’t have a setting for the number of rows that a query returns. The limits of APL queries apply: if your query doesn’t contain `limit`, Axiom applies a default limit of 1,000 rows to the query result. To return more rows, for example in panels that cover a long time range, add `limit` to the end of your APL query. The maximum value is 50,000.
When a limit truncates the query result, Axiom returns a warning such as `default_limit_warning: A default limit of 1000 was applied`. To see the warning, open the query inspector in Grafana.
For more information, see [Default and maximum limits](/apl/tabular-operators/limit-operator#default-and-maximum-limits).
## Benefits of the Axiom Grafana data source plugin [#benefits-of-the-axiom-grafana-data-source-plugin]
The Axiom Grafana data source plugin allows users to display and interact with their Axiom data directly from within Grafana. By doing so, it provides several advantages:
1. **Unified visualization:** The Axiom Grafana data source plugin allows users to utilize Grafana’s powerful visualization tools with Axiom’s data. This enables users to create, explore, and share dashboards which visually represent their Axiom logs and metrics.
2. **Rich Querying Capability:** Grafana has a powerful and flexible interface for building data queries. With the Axiom plugin, and leverage this capability to build complex queries against your Axiom data.
3. **Customizable Alerting:** Grafana’s alerting feature allows you to set alerts based on your queries' results, and set up custom alerts based on specific conditions in your Axiom log data.
4. **Sharing and Collaboration:** Grafana’s features for sharing and collaboration can help teams work together more effectively. Share Axiom data visualizations with others, collaborate on dashboards, and discuss insights directly in Grafana.
---
# Map location data with Axiom and Hex
Source: https://axiom.co/docs/apps/hex
Hex is a powerful collaborative data platform that allows you to create notebooks with Python/SQL code and interactive visualizations.
This page explains how to integrate Hex with Axiom to visualize geospatial data from your logs. You ingest location data into Axiom, query it using APL, and create interactive map visualizations in Hex.
* [Create a Hex account](https://app.hex.tech/).
## Send geospatial data to Axiom [#send-geospatial-data-to-axiom]
Send your sample location data to Axiom using the API endpoint. For example, the following HTTP request sends sample robot location data with latitude, longitude, status, and satellite information.
```bash
curl -X 'POST' 'https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/json' \
-d '[
{
"data": {
"robot_id": "robot-001",
"latitude": 37.7749,
"longitude": -122.4194,
"num_satellites": 8,
"status": "active"
}
}
]'
```
Verify that your data has been ingested correctly by running an APL query in the Axiom UI.
## Set up your Hex project [#set-up-your-hex-project]
1. Create a new Hex project. For more information, see the [Hex documentation](https://learn.hex.tech/docs/getting-started/create-your-first-project).
2. Save your Axiom API token as a secret in Hex. This example uses the secret name `AXIOM_TOKEN`. For more information, see the [Hex documentation](https://learn.hex.tech/docs/explore-data/projects/environment-configuration/environment-views#secrets).
## Query data from Axiom [#query-data-from-axiom]
Write the Python code in your Hex notebook that retrieves data from Axiom. For example, customize the code below:
```python
import requests
import pandas as pd
from datetime import datetime, timedelta
import os
# Retrieve the API token from Hex secrets
axiom_token = os.environ.get("AXIOM_TOKEN")
# Define Axiom API endpoint and headers
base_url = "https://AXIOM_DOMAIN/v1/query/_apl"
headers = {
'Authorization': f'Bearer {axiom_token}',
'Content-Type': 'application/json',
'Accept': 'application/json',
'Accept-Encoding': 'gzip'
}
# Define the time range for your query
end_time = datetime.utcnow()
start_time = end_time - timedelta(days=3) # Get data from the last 3 days
# Construct the APL query
query = {
"apl": """DATASET_NAME
| project ['data.latitude'], ['data.longitude'], ['data.num_satellites'], ['data.robot_id'], ['data.status']""",
"startTime": start_time.strftime("%Y-%m-%dT%H:%M:%SZ"),
"endTime": end_time.strftime("%Y-%m-%dT%H:%M:%SZ")
}
try:
# Send the request to Axiom API
response = requests.post(
f"{base_url}?format=tabular",
headers=headers,
json=query,
timeout=10
)
# Print request details for debugging
print("Request Details:")
print(f"URL: {base_url}?format=tabular")
print(f"Query: {query['apl']}")
print(f"Response Status: {response.status_code}")
if response.status_code == 200:
data = response.json()
if 'tables' in data:
table = data['tables'][0]
if table.get('columns') and len(table['columns']) > 0:
columns = [field['name'] for field in table['fields']]
rows = table['columns']
# Create DataFrame with proper column orientation
df = pd.DataFrame(list(zip(*rows)), columns=columns)
# Ensure data types are appropriate for mapping
df['data.latitude'] = pd.to_numeric(df['data.latitude'])
df['data.longitude'] = pd.to_numeric(df['data.longitude'])
df['data.num_satellites'] = pd.to_numeric(df['data.num_satellites'])
# Display the first few rows to verify our data
print("\nDataFrame Preview:")
display(df.head())
# Store the DataFrame for visualization
robot_locations = df
else:
print("\nNo data found in the specified time range.")
else:
print("\nNo tables found in response")
print("Response structure:", data.keys())
except Exception as e:
print(f"\nError: {str(e)}")
```
## Create map visualisation [#create-map-visualisation]
Create an interactive map visualization in Hex and customize it. For more information, see the [Hex documentation](https://learn.hex.tech/docs/explore-data/cells/visualization-cells/map-cells).
---
# Extensions
Source: https://axiom.co/docs/apps/introduction
This section walks you through a catalog of dedicated extensions that enrich your experience in Axiom’s Console.
To use standard APIs and other data shippers like the Elasticsearch Bulk API, Fluent Bit log processor or Fluentd log collector, go to [Send data](/send-data/methods) instead.
A pre-configured dashboard for logs sent from AWS Lambda.
A configuration path for sending data to Axiom via AWS PrivateLink.
A pre-configured dashboard for logs sent from Cloudflare Workers.
An integrated workflow for sending data from Cloudflare Logpush to Axiom.
Stream function executions and console logs from your Convex deployment to Axiom.
A data source plugin for visualizing data stored in Axiom in Grafana.
A recommended pathway to visualize data stored in Axiom in Hex.
An integrated workflow for sending data from Netlify to Axiom.
A setup that allows you to stream your Supabase project's raw log events directly to Axiom.
A pre-configured dashboard for audit and network flow logs sent from Tailscale.
A walkthrough on configuring resources in Axiom using Terraform.
Stream workspace audit logs from Unkey to Axiom.
A pre-configured dashboard for logs sent from Vercel.
---
# Enrich Axiom experience with AWS Lambda
Source: https://axiom.co/docs/apps/lambda
Use the Axiom Lambda Extension to enrich your Axiom organization with quick filters and a dashboard.
For information on how to send logs and platform events of your Lambda function to Axiom, see [Send data from AWS Lambda](/send-data/aws-lambda).
## What’s the Axiom Lambda Extension [#whats-the-axiom-lambda-extension]
AWS Lambda is a compute service that allows you to build applications and run your code at scale without provisioning or maintaining any servers.
Use the AWS Lambda Extension to collect Lambda logs, performance metrics, platform events, and memory usage from your Lambda functions. With the Axiom Lambda Extension, you can monitor Lambda performance and aggregate system-level metrics for your serverless applications and optimize lambda functions through easy-to-use automatic dashboards.
With the Axiom Lambda extension, you can:
* Monitor your Lambda functions and invocations.
* Get full visibility into your AWS Lambda events in minutes.
* Collect metrics and logs from your Lambda-based Serverless Applications.
* Track and view enhanced memory usage by versions, durations, and cold start.
* Detect and get alerts on Lambda event errors, Lambda request timeout, and low execution time.
## Comprehensive AWS Lambda dashboards [#comprehensive-aws-lambda-dashboards]
The Axiom AWS Lambda integration comes with a pre-built dashboard where you can see and group your functions with the versions and AWS resource that triggers them, making this the ideal starting point for getting an advanced view of the performance and health of your AWS Lambda serverless services and Lambda function events. The AWS Lambda dashboards automatically show up in Axiom through schema detection after installing the Axiom Lambda Extension.
These new zero-config dashboards help you spot and troubleshoot Lambda function errors. For example, if there’s high memory usage on your functions, you can spot the unusual delay from the max execution dashboard and filter your errors by functions, durations, invocations, and versions. With your Lambda version name, you can gain and expand your views on what’s happening in your Lambda event source mapping and invocation type.
## Monitor Lambda functions and usage in Axiom [#monitor-lambda-functions-and-usage-in-axiom]
Having real-time visibility into your function logs is important because any duration between sending your lambda request and the execution time can cause a delay and adds to customer-facing latency. You need to be able to measure and track your Lambda invocations, maximum execution time, minimum execution time, and all invocations by function.
The Axiom Lambda Extension gives you full visibility into the most important metrics and logs coming from your Lambda function out of the box without any further configuration required.
## Track cold start on your Lambda function [#track-cold-start-on-your-lambda-function]
A cold start occurs when there’s a delay between your invocation and runtime created during the initialization process. During this period, there’s no available function instance to respond to an invocation. With the Axiom built-in Serverless AWS Lambda dashboard, you can track and see the effect of cold start on your Lambda functions and its impact on every Lambda function. This data lets you know when to take actionable steps, such as using provisioned concurrency or reducing function dependencies.
## Optimize slow-performing Lambda queries [#optimize-slow-performing-lambda-queries]
Grouping logs with Lambda invocations and execution time by function provides insights into your events request and response pattern. You can extend your query to view when an invocation request is rejected and configure alerts to be notified on Serverless log patterns and Lambda function payloads. With the invocation request dashboard, you can monitor request function logs and see how your Lambda serverless functions process your events and Lambda queues over time.
## Detect timeout on your Lambda function [#detect-timeout-on-your-lambda-function]
Axiom Lambda function monitors let you identify the different points of invocation failures, cold-start delays, and AWS Lambda errors on your Lambda functions. With standard function logs like invocations by function, and Lambda cold start, monitoring the rate of your execution time can alert you to be aware of a significant spike whenever an error occurs in your Lambda function.
## Smart filters [#smart-filters]
Axiom Lambda Serverless Smart Filters lets you easily filter down to specific AWS Lambda functions or Serverless projects and use saved queries to get deep insights on how functions are performing with a single click.
---
# Connect Axiom with Netlify
Source: https://axiom.co/docs/apps/netlify
Netlify is a platform for building and deploying highly performant websites, e-commerce stores, and web apps. Netlify automatically builds your site and deploys it across its global edge network.
Integrating Axiom with Netlify allows you to stream traffic, function, and deployment logs directly to Axiom, giving you comprehensive observability over your Netlify projects. With real-time, unsampled data, you can monitor site performance, detect errors quickly, and make informed decisions about your Jamstack apps.
The Netlify integration supports all [edge deployments](/reference/edge-deployments). The integration sends data to your organization's default edge deployment automatically.
This integration is only available for Netlify customers on enterprise-level plans where Log Drains are supported. For more information, see [Netlify documentation](https://docs.netlify.com/manage/monitoring/log-drains/).
* [Create a Netlify account](https://app.netlify.com/signup).
## Setup [#setup]
1. In Axiom, click **Settings > Apps > Netlify > Install now**.
2. Click **Authorize**, and then copy the integration token.
3. In Netlify, select the site you want to integrate with Axiom. Go to **Logs & Metrics > Log Drains**, and then click **Enable a log drain**.
4. In **Log drain service**, select **Axiom**.
5. Select the log types to send to Axiom.
6. In **Region**, select the default edge deployment of your organization.
The edge deployment you select must match the default edge deployment of your organization. To determine your organization's default edge deployment, see [Edge deployments](/reference/edge-deployments).
7. In **Integration token**, paste the integration token from Axiom.
8. Click **Connect**.
For more information on Log Drains, see the [Netlify documentation](https://docs.netlify.com/manage/monitoring/log-drains/).
## Netlify dashboard [#netlify-dashboard]
Axiom displays the data it receives in a pre-built Netlify dashboard that delivers immediate, actionable insights into your sites' activity and performance.
This comprehensive overview includes:
* **Traffic logs**: Monitor traffic volume, request patterns, and site configurations.
* **Function logs**: Track serverless function executions, errors, and resource usage.
* **Live log streaming**: Stream your site and app logs live with filtering for important information.
With these insights, you can:
* Quickly detect site errors and unusual traffic patterns.
* Monitor serverless function performance and resource usage.
* Analyze your build and deployment processes.
* Drill down into specific events using APL queries.
* Fork the dashboard and build your own custom site monitors.
---
# Connect Axiom with Supabase
Source: https://axiom.co/docs/apps/supabase
Supabase is an open-source Firebase alternative that provides a Postgres database, authentication, instant APIs, edge functions, real-time subscriptions, storage, and vector embeddings.
Integrating Axiom with Supabase allows you to stream your project's raw log events directly to Axiom using Supabase's log drain feature. With your logs in Axiom, you can query, visualize, and monitor your Supabase projects in real time, giving you full observability over your database operations, authentication events, and edge functions.
* [Create a Supabase account](https://supabase.com/dashboard) and upgrade to a Pro, Team, or Enterprise plan.
## Setup [#setup]
1. In Supabase, go to your project's dashboard and navigate to **Project Settings > Log Drains**.
2. Click **Axiom**, and then create a new destination with the following configuration:
* **Dataset name**: Enter the name of the Axiom dataset you created.
* **API token**: Enter the Axiom API token you created.
3. Click **Save destination**.
Supabase sends logs to Axiom as JSON raw log events with timestamps formatted for Axiom's ingestion endpoint.
For more information on log drains, see the [Supabase documentation](https://supabase.com/docs/guides/telemetry/log-drains).
## Explore your Supabase data [#explore-your-supabase-data]
After setting up the log drain, your Supabase logs appear in the dataset you specified. Open the [Stream tab](/query-data/stream) in Axiom to watch events arrive in real time.
With your Supabase data in Axiom, you can:
* Track authentication events and detect unusual sign-in patterns.
* Observe edge function executions and errors.
* Set up [monitors](/monitor-data/monitors) to get alerted about issues in your Supabase project.
* Build [custom dashboards](/dashboards/create) tailored to your Supabase workload.
---
# Connect Axiom with Tailscale
Source: https://axiom.co/docs/apps/tailscale
Tailscale is a secure networking solution that allows you to create and manage a private network (tailnet), securely connecting all your devices.
Integrating Axiom with Tailscale allows you to stream your audit and network flow logs directly to Axiom seamlessly, unlocking powerful insights and analysis. Whether you’re conducting a security audit, optimizing performance, or ensuring compliance, Axiom’s Tailscale dashboard equips you with the tools to maintain a secure and efficient network, respond quickly to potential issues, and make informed decisions about your network configuration and usage.
* [Create a Tailscale account](https://login.tailscale.com/start).
## Setup [#setup]
1. In Tailscale, go to the [configuration logs page](https://login.tailscale.com/admin/logs) of the admin console.
2. Add Axiom as a configuration log streaming destination in Tailscale. For more information, see the [Tailscale documentation](https://tailscale.com/kb/1255/log-streaming?q=stream#add-a-configuration-log-streaming-destination).
## Tailscale dashboard [#tailscale-dashboard]
Axiom displays the data it receives in a pre-built Tailscale dashboard that delivers immediate, actionable insights into your tailnet’s activity and health.
This comprehensive overview includes:
* **Log type distribution**: Understand the balance between configuration audit logs and network flow logs over time.
* **Top actions and hosts**: Identify the most common network actions and most active devices.
* **Traffic visualization**: View physical, virtual, and exit traffic patterns for both sources and destinations.
* **User activity tracking**: Monitor actions by user display name, email, and ID for security audits and compliance.
* **Configuration log stream**: Access a detailed audit trail of all configuration changes.
With these insights, you can:
* Quickly identify unusual network activity or traffic patterns.
* Track configuration changes and user actions.
* Monitor overall network health and performance.
* Investigate specific events or users as needed.
* Understand traffic distribution across your tailnet.
---
# Connect Axiom with Terraform
Source: https://axiom.co/docs/apps/terraform
Axiom Terraform Provider lets you provision and manage Axiom resources (datasets, notifiers, monitors, and users) with Terraform. This means that you can programmatically create resources, access existing ones, and perform further infrastructure automation tasks.
Install the Axiom Terraform Provider from the [Terraform Registry](https://registry.terraform.io/providers/axiomhq/axiom/latest). To see the provider in action, check out the [example](https://github.com/axiomhq/terraform-provider-axiom/blob/main/example/main.tf).
This guide explains how to install the provider and perform some common procedures such as creating new resources and accessing existing ones. For the full API reference, see the [documentation in the Terraform Registry](https://registry.terraform.io/providers/axiomhq/axiom/latest/docs).
## Prerequisites [#prerequisites]
* [Sign up for a free Axiom account](https://app.axiom.co/register). All you need is an email address.
* [Create an advanced API token in Axiom](/reference/tokens#create-advanced-api-token) with the permissions to perform the actions you want to use Terraform for. For example, to use Terraform to create and update datasets, create the advanced API token with these permissions.
* [Create a Terraform account](https://app.terraform.io/signup/account).
* [Install the Terraform CLI](https://developer.hashicorp.com/terraform/cli).
## Install the provider [#install-the-provider]
To install the Axiom Terraform Provider from the [Terraform Registry](https://registry.terraform.io/providers/axiomhq/axiom/latest), follow these steps:
1. Add the following code to your Terraform configuration file. Replace `API_TOKEN` with the Axiom API token you have generated. For added security, store the API token in an environment variable.
```hcl
terraform {
required_providers {
axiom = {
source = "axiomhq/axiom"
}
}
}
provider "axiom" {
api_token = "API_TOKEN"
}
```
2. In your terminal, go to the folder of your main Terraform configuration file, and then run the command `terraform init`.
## Create new resources [#create-new-resources]
### Create dataset [#create-dataset]
To create a dataset in Axiom using the provider, add the following code to your Terraform configuration file. Customize the `name` and `description` fields.
```hcl
resource "axiom_dataset" "test_dataset" {
name = "test_dataset"
description = "This is a test dataset created by Terraform."
}
```
### Create notifier [#create-notifier]
To create a Slack notifier in Axiom using the provider, add the following code to your Terraform configuration file. Replace `SLACK_URL` with the webhook URL from your Slack instance. For more information on obtaining this URL, see the [Slack documentation](https://api.slack.com/messaging/webhooks).
```hcl
resource "axiom_notifier" "test_slack_notifier" {
name = "test_slack_notifier"
properties = {
slack = {
slack_url = "SLACK_URL"
}
}
}
```
To create a Discord notifier in Axiom using the provider, add the following code to your Terraform configuration file.
* Replace `DISCORD_CHANNEL` with the webhook URL from your Discord instance. For more information on obtaining this URL, see the [Discord documentation](https://docs.discord.com/developers/platform/webhooks#webhook-events).
* Replace `DISCORD_TOKEN` with your Discord API token. For more information on obtaining this token, see the [Discord documentation](https://docs.discord.com/developers/topics/oauth2#oauth2).
```hcl
resource "axiom_notifier" "test_discord_notifier" {
name = "test_discord_notifier"
properties = {
discord = {
discord_channel = "DISCORD_CHANNEL"
discord_token = "DISCORD_TOKEN"
}
}
}
```
To create an email notifier in Axiom using the provider, add the following code to your Terraform configuration file. Replace `EMAIL1` and `EMAIL2` with the email addresses you want to notify.
```hcl
resource "axiom_notifier" "test_email_notifier" {
name = "test_email_notifier"
properties = {
email= {
emails = ["EMAIL1","EMAIL2"]
}
}
}
```
For more information on the types of notifier you can create, see the [documentation in the Terraform Registry](https://registry.terraform.io/providers/axiomhq/axiom/latest/docs/resources/notifier).
### Create monitor [#create-monitor]
To create a monitor in Axiom using the provider, add the following code to your Terraform configuration file and customize it:
```hcl
resource "axiom_monitor" "test_monitor" {
depends_on = [axiom_dataset.test_dataset, axiom_notifier.test_slack_notifier]
# `type` can be one of the following:
# - "Threshold": For numeric values against thresholds. It requires `operator` and `threshold`.
# - "MatchEvent": For detecting specific events. It doesn’t require `operator` and `threshold`.
# - "AnomalyDetection": For detecting anomalies. It requires `compare_days` and `tolerance, operator`.
type = "Threshold"
name = "test_monitor"
description = "This is a test monitor created by Terraform."
apl_query = "['test_dataset'] | summarize count() by bin_auto(_time)"
interval_minutes = 5
# `operator` is required for threshold and anomaly detection monitors.
# Valid values are "Above", "AboveOrEqual", "Below", "BelowOrEqual".
operator = "Above"
range_minutes = 5
# `threshold` is required for threshold monitors
threshold = 1
# `compare_days` and `tolerance` are required for anomaly detection monitors.
# Uncomment the two lines below for anomaly detection monitors.
# compare_days = 7
# tolerance = 25
notifier_ids = [
axiom_notifier.test_slack_notifier.id
]
alert_on_no_data = false
notify_by_group = false
}
```
This example creates a monitor using the dataset `test_dataset` and the notifier `test_slack_notifier`. These are resources you have created and accessed in the sections above.
* Customize the `name` and the `description` fields.
* In the `apl_query` field, specify the APL query for the monitor.
For more information on these fields, see the [documentation in the Terraform Registry](https://registry.terraform.io/providers/axiomhq/axiom/latest/docs/resources/monitor).
### Create user [#create-user]
To create a user in Axiom using the provider, add the following code to your Terraform configuration file. Customize the `name`, `email`, and `role` fields.
```hcl
resource "axiom_user" "test_user" {
name = "test_user"
email = "test@abc.com"
role = "user"
}
```
## Access existing resources [#access-existing-resources]
### Access existing dataset [#access-existing-dataset]
To access an existing dataset, follow these steps:
1. Determine the ID of the Axiom dataset by sending a GET request to the [`datasets` endpoint of the Axiom API](/restapi/endpoints/getDatasets).
2. Add the following code to your Terraform configuration file. Replace `DATASET_ID` with the ID of the Axiom dataset.
```hcl
data "axiom_dataset" "test_dataset" {
id = "DATASET_ID"
}
```
### Access existing notifier [#access-existing-notifier]
To access an existing notifier, follow these steps:
1. Determine the ID of the Axiom notifier by sending a GET request to the `notifiers` endpoint of the Axiom API.
2. Add the following code to your Terraform configuration file. Replace `NOTIFIER_ID` with the ID of the Axiom notifier.
```hcl
data "axiom_notifier" "test_slack_notifier" {
id = "NOTIFIER_ID"
}
```
### Access existing monitor [#access-existing-monitor]
To access an existing monitor, follow these steps:
1. Determine the ID of the Axiom monitor by sending a GET request to the `monitors` endpoint of the Axiom API.
2. Add the following code to your Terraform configuration file. Replace `MONITOR_ID` with the ID of the Axiom monitor.
```hcl
data "axiom_monitor" "test_monitor" {
id = "MONITOR_ID"
}
```
### Access existing user [#access-existing-user]
To access an existing user, follow these steps:
1. Determine the ID of the Axiom user by sending a GET request to the `users` endpoint of the Axiom API.
2. Add the following code to your Terraform configuration file. Replace `USER_ID` with the ID of the Axiom user.
```hcl
data "axiom_user" "test_user" {
id = "USER_ID"
}
```
---
# Connect Axiom with Unkey
Source: https://axiom.co/docs/apps/unkey
Unkey provides infrastructure for building and operating APIs. Connect Unkey with Axiom to send audit logs, key verifications, gateway HTTP requests, runtime logs, and rate-limit decisions to an Axiom dataset.
* [Create an Unkey account](https://app.unkey.com).
## Supported event streams [#supported-event-streams]
Each log drain sends one event stream. To send all five streams, create five drains. You can send them to the same Axiom dataset and use the `stream` field to distinguish them, or use a separate dataset for each stream.
| Stream | `stream` value | Events |
| --------------------- | ------------------- | ------------------------------------------------------------------------------ |
| Audit logs | `audit_logs` | Workspace actions, such as creating projects or changing configuration |
| Key verifications | `key_verifications` | API key verification results, including successful and rejected verifications |
| Gateway HTTP requests | `gateway_requests` | Recorded HTTP requests served through Unkey's gateway |
| Runtime logs | `runtime_logs` | Collected application output, including structured logs and multiline messages |
| Rate limits | `ratelimits` | Recorded API rate-limit decisions, including passed and blocked checks |
## Set up an Axiom log drain [#set-up-an-axiom-log-drain]
Create a log drain in your Unkey workspace.
1. In the Unkey dashboard, select your workspace, and then go to **Settings > Log Drains**.
2. Click **Create Log Drain**.
3. Select **Axiom** as the destination.
4. Enter a descriptive name for the log drain.
5. In **Stream**, select **Audit logs**, **Key verifications**, **Gateway HTTP requests**, **Runtime logs**, or **Rate limits**.
6. Optional: Configure stream filters to limit which events Unkey sends.
7. Enter the name of your Axiom dataset and your Axiom API token.
8. Click **Create Log Drain**.
9. Repeat these steps for each additional stream you want to send.
Drains start at creation time. Historical backfill isn't supported. Unkey sends events asynchronously in batches, so events can take several minutes to appear in Axiom.
## Explore your Unkey events [#explore-your-unkey-events]
After you create a drain, open the [Stream tab](/query-data/stream) in Axiom to verify that events arrive in your dataset. Filter by `stream` to inspect an event type.
Each event includes `_time`, when it occurred, and `stream`, its event type.
### Audit logs [#audit-logs]
The `audit_logs` stream records who performed a workspace action and which resources it affected.
```json
{
"_time": "2026-09-10T12:34:56.789Z",
"stream": "audit_logs",
"id": "evt_123",
"action": "key.create",
"occurred_at": "2026-09-10T12:34:56.789Z",
"actor": {
"id": "user_123",
"type": "user",
"name": "Ada",
"metadata": null
},
"targets": [
{
"id": "key_123",
"type": "key",
"name": "Production API key",
"metadata": null
}
],
"context": {
"location": "203.0.113.10",
"user_agent": "Mozilla/5.0"
},
"metadata": null,
"description": "Created Production API key",
"correlation_id": "req_123"
}
```
See [Unkey audit log event types](https://www.unkey.com/docs/audit-log/types) for the complete list of actions.
### Key verifications [#key-verifications]
The `key_verifications` stream records API key verification outcomes.
```json
{
"_time": "2026-09-10T12:34:56.789Z",
"stream": "key_verifications",
"request_id": "req_123",
"key_space_id": "ks_production",
"key_id": "key_123",
"identity": {
"id": "id_123",
"externalId": "customer_123"
},
"region": "eu-west-1",
"source": { "type": "api" },
"outcome": "VALID",
"tags": ["paid"],
"spent_credits": 1
}
```
See [Unkey key verification payloads](https://www.unkey.com/docs/log-drains/overview#read-a-key-verification-payload) for field details.
### Gateway HTTP requests [#gateway-http-requests]
The `gateway_requests` stream records gateway request metadata, response status, latency, and captured request details.
```json
{
"_time": "2026-09-10T12:34:56.789Z",
"stream": "gateway_requests",
"request_id": "req_123",
"project_id": "proj_store",
"app_id": "app_backend",
"environment_id": "env_production",
"deployment_id": "dep_release",
"region": "eu-west-1",
"request": {
"method": "GET",
"host": "api.example.com",
"path": "/orders",
"query_string": "status=paid",
"query_params": { "status": ["paid"] },
"headers": ["Accept: application/json"],
"body": "",
"user_agent": "store-client/1.0",
"ip_address": "203.0.113.10"
},
"response": {
"status": 200,
"headers": ["Content-Type: application/json"],
"body": "{\"orders\":[]}"
},
"latency": { "total": 52, "instance": 41, "gateway": 11 }
}
```
Captured details follow your Unkey logging policy. See [Unkey gateway request payloads](https://www.unkey.com/docs/log-drains/overview#read-a-gateway-request-payload) for field details and capture limits.
### Runtime logs [#runtime-logs]
The `runtime_logs` stream forwards collected application output, including multiline messages and nested structured attributes.
```json
{
"_time": "2026-09-10T12:34:56.789Z",
"stream": "runtime_logs",
"log_id": "rlog_123",
"severity": "error",
"message": "Payment failed",
"attributes": { "order": { "id": 42 }, "retry": false },
"project_id": "proj_store",
"app_id": "app_backend",
"environment_id": "env_production",
"deployment_id": "dep_release",
"region": "eu-west-1"
}
```
See [Unkey runtime log payloads](https://www.unkey.com/docs/log-drains/overview#read-a-runtime-log-payload) for field details and handling of application output.
### Rate limits [#rate-limits]
The `ratelimits` stream exports recorded decisions from `ratelimit.limit` and `ratelimit.multiLimit`. These are rate-limit checks, not audit events for configuration changes.
```json
{
"_time": "2026-09-10T12:34:56.789Z",
"stream": "ratelimits",
"request_id": "req_123",
"namespace_id": "rl_payments",
"identifier": "customer_123",
"passed": false,
"limit": 100,
"remaining": 0,
"reset_at": 1789043756789,
"tokens": 3,
"source": "api"
}
```
See [Unkey rate-limit payloads](https://www.unkey.com/docs/log-drains/overview#read-a-rate-limit-payload) for field details and which decisions are recorded.
## Delivery and troubleshooting [#delivery-and-troubleshooting]
For delivery status, retention, retries, and troubleshooting, see the [Unkey log drain documentation](https://www.unkey.com/docs/log-drains/overview).
---
# Connect Axiom with Vercel
Source: https://axiom.co/docs/apps/vercel
Connect Axiom with Vercel to get the deepest observability experience for your Vercel projects.
Easily monitor data from requests, functions, firewall events, and web vitals in one place. 100% live and 100% of your data, no sampling.
Axiom’s Vercel app ships with a pre-built dashboard and pre-installed monitors so you can be in complete control of your projects with minimal effort.
If you use Axiom Vercel integration, [annotations](/annotations) are automatically created for deployments.
The Vercel integration supports all [edge deployments](/reference/edge-deployments). The integration sends data to your organization’s default edge deployment automatically, without any additional configuration.
## What’s Vercel? [#whats-vercel]
Vercel is a platform for frontend frameworks and static sites, built to integrate with your headless content, commerce, or database.
Vercel provides a frictionless developer experience to take care of the hard things: deploying instantly, scaling automatically, and serving personalized content around the globe.
Vercel makes it easy for frontend teams to develop, preview, and ship delightful user experiences, where performance is the default.
## Send logs to Axiom [#send-logs-to-axiom]
Simply install the [Axiom Vercel app from here](https://vercel.com/integrations/axiom) and be streaming logs and web vitals within minutes.
## App Overview [#app-overview]
### Request and function logs [#request-and-function-logs]
For both requests and serverless functions, Axiom automatically installs a [drain](https://vercel.com/docs/drains/using-drains) in your Vercel account to capture data live.
As users interact with your website, various logs are produced. Axiom captures all these logs and ingests them into the `vercel` dataset. You can stream and analyze these logs live, or use the pre-built Vercel Dashboard to get an overview of all the important metrics. When you’re ready, you can fork the dashboard and start building your own.
For function logs, if you call `console.log`, `console.warn` or `console.error` in your function, the output is also captured and made available as part of the log. You can use APL to easily search these logs.
### Log sources [#log-sources]
The log drain that Axiom installs subscribes to the following [Vercel log sources](https://vercel.com/docs/drains/reference/logs#log-sources): `static`, `lambda`, `build`, `edge`, `external`, and `firewall`. Axiom records the origin of each event in the `vercel.source` field. To show events from one origin, use the **Source** quick filter in the query builder on the Query tab, or the **Source** filter in the Stream tab.
### Firewall logs [#firewall-logs]
Vercel sends firewall log entries for requests that a [Vercel Firewall](https://vercel.com/docs/vercel-firewall) rule denies. Axiom ingests these entries into the `vercel` dataset with `vercel.source` set to `firewall`. A firewall event has no `message` field. The fields that describe the denied request and the matched rule include the following:
| Field | Description | Example |
| :------------------- | :---------------------------------------------------------- | :------------- |
| `vercel.source` | Origin of the event. Always `firewall` for firewall events. | `firewall` |
| `request.wafAction` | Action that the firewall rule took. | `deny` |
| `request.wafRule` | ID of the firewall rule that matched the request. | `rule_abc123` |
| `request.statusCode` | HTTP status code that Vercel returned to the client. | `403` |
| `request.method` | HTTP method of the denied request. | `POST` |
| `request.path` | Path of the denied request. | `/api/webhook` |
| `request.ip` | IP address of the client. | `203.0.113.7` |
For example, the following query counts denied requests by firewall rule:
```kusto
['vercel']
| where ['vercel.source'] == "firewall"
| summarize count() by ['request.wafRule'], ['request.wafAction']
```
When Vercel reports a matched firewall rule on another request event, Axiom populates the same `request.wafAction` and `request.wafRule` fields on that event. To see all events that matched a rule, regardless of their source, filter on the rule field:
```kusto
['vercel']
| where isnotempty(['request.wafRule'])
| summarize count() by ['vercel.source'], ['request.wafAction'], ['request.wafRule']
```
Axiom populates the `request.wafAction`, `request.wafRule`, `request.cacheId`, `request.vercelCache`, and `request.referer` fields for installations created after October 7, 2024. If you installed the Axiom Vercel app before that date, [reinstall the integration](#update-the-log-drain-of-an-existing-installation) to receive these fields.
### Update the log drain of an existing installation [#update-the-log-drain-of-an-existing-installation]
Axiom sets the sources of the log drain when it installs the drain. You can't change them later from the Vercel dashboard or from the Axiom app. Log drains installed before Axiom added the `firewall` source keep their original list of sources. To start receiving firewall logs, reinstall the integration.
To check whether your log drain receives firewall logs, run the following query over a time range in which your firewall denied requests. If the query returns no results, reinstall the integration.
```kusto
['vercel']
| where ['vercel.source'] == "firewall"
| count
```
To reinstall the integration:
1. In your Vercel dashboard, go to **Integrations**, and then select **Manage** next to the Axiom integration.
2. Select **Settings**, and then select **Uninstall Integration**. Vercel removes the log drain and the environment variables that the integration created.
3. Install the [Axiom Vercel app](https://vercel.com/integrations/axiom) again and select the projects that you want to monitor. Axiom installs a new log drain for each project with the current list of sources.
4. If your projects send Web Vitals or use next-axiom, redeploy them. The new installation sets a new value for the `NEXT_PUBLIC_AXIOM_INGEST_ENDPOINT` environment variable, and your deployments only use the new value after you redeploy.
Uninstalling the integration doesn't delete the `vercel` dataset or the data in it. When you reinstall, Axiom connects the new installation to the existing dataset, so your history, saved queries, dashboards, and monitors continue to work.
## Web vitals [#web-vitals]
Axiom supports capturing and analyzing Web Vital data directly from your user’s browser without any sampling and with more data than is available elsewhere. It’s perfect to pair with Vercel’s in-built analytics when you want to get really deep into a specific problem or debug issues with a specific audience (user-agent, location, region, etc).
Web Vitals are only currently supported for Next.js websites. Expanded support is coming soon.
### Installation [#installation]
Perform the following steps to install Web Vitals:
1. In your Vercel project, run `npm install --save next-axiom`.
2. In `next.config.js`, wrap your NextJS config in `withAxiom` as follows:
```js
const { withAxiom } = require('next-axiom');
module.exports = withAxiom({
// ... your existing config
})
```
This proxies the Axiom ingest call to improve deliverability.
3. For Web Vitals, navigate to `app/layout.tsx` and add the `AxiomWebVitals` component:
```js
import { AxiomWebVitals } from 'next-axiom';
export default function RootLayout() {
return (
...
...
);
}
```
WebVitals are sent only from production deployments.
4. Deploy your site and watch data coming into your Axiom dashboard.
* To send logs from different parts of your app, make use of the provided logging functions. For example:
```js
log.info('Payment completed', { userID: '123', amount: '25USD' });
```
### Client Components [#client-components]
For Client Components, replace the `log` prop usage with the `useLogger` hook:
```js
'use client';
import { useLogger } from 'next-axiom';
export default function ClientComponent() {
const log = useLogger();
log.debug('User logged in', { userId: 42 });
return Logged in ;
}
```
### Server Components [#server-components]
For Server Components, create a logger and make sure to call flush before returning:
```js
import { Logger } from 'next-axiom';
export default async function ServerComponent() {
const log = new Logger();
log.info('User logged in', { userId: 42 });
// ... other operations ...
await log.flush();
return Logged in ;
}
```
### Route Handlers [#route-handlers]
For Route Handlers, wrapping your Route Handlers in `withAxiom` adds a logger to your request and automatically log exceptions:
```js
import { withAxiom, AxiomRequest } from 'next-axiom';
export const GET = withAxiom((req: AxiomRequest) => {
req.log.info('Login function called');
// You can create intermediate loggers
const log = req.log.with({ scope: 'user' });
log.info('User logged in', { userId: 42 });
return NextResponse.json({ hello: 'world' });
});
```
## Use Next.js 12 for Web Vitals [#use-nextjs-12-for-web-vitals]
If you’re using Next.js version 12, follow the instructions below to integrate Axiom for logging and capturing Web Vitals data.
In your `pages/_app.js` or `pages/_app.ts` and add the following line:
```js
export { reportWebVitals } from 'next-axiom';
```
## Upgrade to Next.js 13 from Next.js 12 [#upgrade-to-nextjs-13-from-nextjs-12]
If you plan on upgrading to Next.js 13, you’ll need to make specific changes to ensure compatibility:
* Upgrade the next-axiom package to version `1.0.0` or higher:
* Make sure any exported variables have the `NEXT_PUBLIC_ prefix`, for example,, `NEXT_PUBLIC_AXIOM_TOKEN`.
* In client components, use the `useLogger` hook instead of the `log` prop.
* For server-side components, you need to create an instance of the `Logger` and flush the logs before the component returns.
* For Web Vitals tracking, you’ll replace the previous method of capturing data. Remove the `reportWebVitals()` line and instead integrate the `AxiomWebVitals` component into your layout.
## Vercel Function logs 4KB limit [#vercel-function-logs-4kb-limit]
The Vercel 4KB log limit refers to a restriction placed by Vercel on the size of log output generated by serverless functions running on their platform. The 4KB log limit means that each log entry produced by your function should be at most 4 Kilobytes in size.
If your log output is larger than 4KB, you might experience truncation or missing logs. To log above this limit, you can send your function logs using [next-axiom](https://github.com/axiomhq/next-axiom).
## Parse JSON on the message field [#parse-json-on-the-message-field]
If you use a logging library in your Vercel project that prints JSON, your **message** field contains a stringified and therefore escaped JSON object.
* If your Vercel logs are encoded as JSON, they look like this:
```json
{
"level": "error",
"message": "{ \"message\": \"user signed in\", \"metadata\": { \"userId\": 2234, \"signInType\": \"sso-google\" }}",
"request": {
"host": "www.axiom.co",
"id": "iad1:iad1::sgh2r-1655985890301-f7025aa764a9",
"ip": "199.16.157.13",
"method": "GET",
"path": "/sign-in/google",
"scheme": "https",
"statusCode": 500,
"teamName": "AxiomHQ",
},
"vercel": {
"deploymentId": "dpl_7UcdgdgNsdgbcPY3Lg6RoXPfA6xbo8",
"deploymentURL": "axiom-bdsgvweie6au-axiomhq.vercel.app",
"projectId": "prj_TxvF2SOZdgdgwJ2OBLnZH2QVw7f1Ih7",
"projectName": "axiom-co",
"region": "iad1",
"route": "/signin/[id]",
"source": "lambda-log"
}
}
```
* The **JSON** data in your **message** would be:
```json
{
"message": "user signed in",
"metadata": {
"userId": 2234,
"signInType": "sso-google"
}
}
```
You can **parse** the JSON using the [parse\_json function](/apl/scalar-functions/string-functions#parse-json\(\)) and run queries against the **values** in the **message** field.
### Example [#example]
```kusto
['vercel']
| extend parsed = parse_json(message)
```
* You can select the field to **insert** into new columns using the [project operator](/apl/tabular-operators/project-operator)
```kusto
['vercel']
| extend parsed = parse_json('{"message":"user signed in", "metadata": { "userId": 2234, "SignInType": "sso-google" }}')
| project parsed["message"]
```
### More Examples [#more-examples]
* If you have **null values** in your data you can use the **isnotnull()** function
```kusto
['vercel']
| extend parsed = parse_json(message)
| where isnotnull(parsed)
| summarize count() by parsed["message"], parsed["metadata"]["userId"]
```
* Check out the [APL Documentation on how to use more functions](/apl/scalar-functions/string-functions) and run your own queries against your Vercel logs.
## Migrate from Vercel app to next-axiom [#migrate-from-vercel-app-to-next-axiom]
In May 2024, Vercel [introduced higher costs](https://axiom.co/blog/changes-to-vercel-log-drains) for using Vercel Drains. Because the Axiom Vercel app depends on Drains, using the next-axiom library can be the cheaper option to analyze telemetry data for higher volume projects.
To migrate from the Axiom Vercel app to the next-axiom library, follow these steps:
1. Delete the existing log drain from your Vercel project.
2. Delete `NEXT_PUBLIC_AXIOM_INGEST_ENDPOINT` from the environment variables of your Vercel project. For more information, see the [Vercel documentation](https://vercel.com/projects/environment-variables).
3. [Create a new dataset in Axiom](/reference/datasets), and [create a new advanced API token](/reference/tokens) with ingest permissions for that dataset.
4. Add the following environment variables to your Vercel project:
* `NEXT_PUBLIC_AXIOM_DATASET` is the name of the Axiom dataset where you want to send data.
* `NEXT_PUBLIC_AXIOM_TOKEN` is the Axiom API token you have generated.
5. In your terminal, go to the root folder of your Next.js app, and then run `npm install --save next-axiom` to install the latest version of next-axiom.
6. In the `next.config.ts` file, wrap your Next.js configuration in `withAxiom`:
```js
const { withAxiom } = require('next-axiom');
module.exports = withAxiom({
// Your existing configuration
});
```
For more configuration options, see the [documentation in the next-axiom GitHub repository](https://github.com/axiomhq/next-axiom).
## Send logs from Vercel preview deployments [#send-logs-from-vercel-preview-deployments]
To send logs from Vercel preview deployments to Axiom, enable preview deployments for the environment variable `NEXT_PUBLIC_AXIOM_INGEST_ENDPOINT`. For more information, see the [Vercel documentation](https://vercel.com/docs/projects/environment-variables/managing-environment-variables).
---
# Intelligence
Source: https://axiom.co/docs/console/intelligence
Axiom’s Console is evolving from a powerful space for human-led investigation to incorporate assistance that helps you reach insights faster. By combining Axiom's cost-efficient data platform with intelligence features, Axiom is transforming common workflows from reactive chores into proactive, machine-assisted actions.
This section covers the intelligence features built into the Axiom Console.
## Spotlight [#spotlight]
Spotlight is an interactive analysis feature that helps you find the root cause faster.
Rather than reviewing data from a notable period event-by-event, Spotlight allows you to compare a subset against baseline automatically. Spotlight analyzes every field to surface the most significant differences, turning manual investigation into a fast, targeted discovery process.
Learn more about [Spotlight](/console/intelligence/spotlight).
## AI agent integrations [#ai-agent-integrations]
Axiom provides two complementary approaches for integrating AI agents with your data:
### Axiom MCP Server [#axiom-mcp-server]
Axiom MCP Server is a [Model Context Protocol](https://modelcontextprotocol.io/) server implementation that enables AI agents to query your data using Axiom Processing Language (APL). MCP provides OAuth-based credential isolation where agents never see your tokens.
Learn more about [Axiom MCP Server](/console/intelligence/mcp-server).
### Skills [#skills]
Skills are instruction files that give AI coding agents specialized capabilities. Skills work by embedding methodology and context directly into the agent's prompt.
Learn more about [Axiom Skills for AI agents](/console/intelligence/skills).
## AI-assisted workflows [#ai-assisted-workflows]
Axiom also includes several features that leverage AI to accelerate common workflows.
### Natural language querying [#natural-language-querying]
Ask questions of your data in plain English and have Axiom translate your request directly into a valid Axiom Processing Language (APL) query. This lowers the barrier to exploring your data and makes it easier for everyone on your team to find the answers they need.
Learn more about [generating queries using AI](/query-data/query-editor#generate-query-using-natural-language).
### AI-powered dashboard generation [#ai-powered-dashboard-generation]
Instead of building dashboards from scratch, you can describe your requirements in natural language and have Axiom generate a complete dashboard for you instantly. Axiom analyzes your events and goals to select the most appropriate visualizations.
Learn more about [generating dashboards using AI](/dashboards/create#generate-dashboards-using-ai).
### AI summaries in Spotlight [#ai-summaries-in-spotlight]
Spotlight provides you with clear, concise explanations of the key differences between selected and baseline data. This makes it easier to spot root causes, understand anomalies, and communicate findings to your team, without needing to pore over every visualization.
---
# Configure dashboard elements
Source: https://axiom.co/docs/dashboard-elements/configure
When you create a chart, click to access the following options.
## Values [#values]
Specify how to treat missing or undefined values:
* **Auto:** This option automatically decides the best way to represent missing or undefined values in the data series based on the chart type and the rest of the data.
* **Ignore:** This option ignores any missing or undefined values in the data series. This means that the chart only displays the known, defined values.
* **Join adjacent values:** This option connects adjacent data points in the data series, effectively filling in any gaps caused by missing values. The benefit of joining adjacent values is that it can provide a smoother, more continuous visualization of your data.
* **Fill with zeros:** This option replaces any missing or undefined values in the data series with zero. This can be useful if you want to emphasize that the data is missing or undefined, as it causes a drop to zero in your chart.
## Variant [#variant]
Specify the chart type.
**Area:** An area chart displays the area between the data line and the axes, often filled with a color or pattern. Stacked charts provide the capability to design and implement intricate query dashboards while integrating advanced visualizations, enriching your logging experience over time.
**Bars:** A bar chart represents data in rectangular bars. The length of each bar is proportional to the value it represents. Bar charts can be used to compare discrete quantities, or when you have categorical data.
**Line:** A line chart connects individual data points into a continuous line, which is useful for showing logs over time. Line charts are often used for time series data.
## Y-Axis [#y-axis]
Specify the scale of the vertical axis.
**Linear:** A linear scale maintains a consistent scale where equal distances represent equal changes in value. This is the most common scale type and is useful for most types of data.
**Log:** A logarithmic (or log) scale represents values in terms of their order of magnitude. Each unit of distance on a log scale represents a tenfold increase in value. Log scales make it easy to see backend errors and compare values across a wide range.
## Annotations [#annotations]
In **Annotations**, click **Manage** to select the types to display.
For more information, see [Annotations](/annotations#show-and-hide-annotations-on-dashboards).
---
# Create dashboard elements
Source: https://axiom.co/docs/dashboard-elements/create
Dashboard elements are the different visual elements that you can include in your dashboard to display your data and other information. For example, you can track key metrics, logs, and traces, and monitor real-time data flow.
You can create the following dashboard elements:
* [Filter bar](/query-data/filters)
* [Gauge](/dashboard-elements/gauge)
* [Heatmap](/dashboard-elements/heatmap)
* [Log stream](/dashboard-elements/log-stream)
* [Monitor list](/dashboard-elements/monitor-list)
* [Note](/dashboard-elements/note)
* [Pie](/dashboard-elements/pie-chart)
* [Scatter](/dashboard-elements/scatter-plot)
* [Statistic](/dashboard-elements/statistic)
* [Table](/dashboard-elements/table)
* [Time series](/dashboard-elements/time-series)
* [Top list](/dashboard-elements/top-list)
* [Spacer](/dashboard-elements/spacer)
To organize related dashboard elements into collapsible groups, [create dashboard sections](/dashboards/sections).
## Create dashboard elements [#create-dashboard-elements]
1. [Create a dashboard](/dashboards/create) or open an existing dashboard.
2. Click **Edit dashboard**.
3. Click **Add element** in the top right corner.
4. Choose the dashboard element from the list.
5. For charts, select one of the following:
* Click **Builder** to create your chart using a [visual query builder](#create-chart-using-visual-query-builder).
* Click **APL** to create your chart using the Axiom Processing Language (APL). Create a chart in the same way you create a chart in the [Editor of the Query tab](/query-data/query-editor).
6. Optional: [Configure chart options](/dashboard-elements/configure).
7. Optional: Set a custom time range that’s different from the dashboard’s time range.
8. Click **Save**.
The new element appears in your dashboard. At the bottom, click **Save** to save your changes to the dashboard.
## Create chart using visual query builder [#create-chart-using-visual-query-builder]
Use the query builder to create or edit queries for the selected dataset:
This component is a visual query builder that eases the process of building visualizations and segments of your data.
This guide walks you through the individual sections of the query builder.
### Time range [#time-range]
Every query has a start and end time and the time range component allows quick selection of common time ranges as well as the ability to input specific start and end timestamps:
* Use the **Quick Range** items to quickly select popular ranges
* Use the **Custom Start/End Date** inputs to select specific times
* Use the **Resolution** items to choose between various time bucket resolutions
### Against [#against]
When a time series visualization is selected, such as `count`, the **Against** menu is enabled and it’s possible to select a historical time to compare the results of your time range too.
For example, to compare the last hour’s average response time to the same time yesterday, select `1 hr` in the time range menu, and then select `-1D` from the **Against** menu:
The results look like this:
The dotted line represents results from the base date, and the totals table includes the comparative totals.
When you add `field` to the `group by` clause, the **time range against** values are attached to each `events`.
### Visualizations [#visualizations]
Axiom provides powerful visualizations that display the output of running aggregate functions across your dataset. The Visualization menu allows you to add these visualizations and, where required, input their arguments:
You can select a visualization to add it to the query. If a visualization requires an argument (such as the field and/or other parameters), the menu allows you to select eligible fields and input those arguments. Press Enter to complete the addition.
Click Visualization in the query builder to edit it at any time.
[Learn about supported visualizations](/query-data/visualizations)
### Filters [#filters]
Use the filter menu to attach filter clauses to your search.
Axiom supports AND/OR operators at the top-level as well as one level deep. This means you can create filters that would read as `status == 200 AND (method == get OR method == head) AND (user-agent contains Mozilla or user-agent contains Webkit)`.
Filters are divided up by the field type they operate on, but some may apply to more than one field type.
#### List of filters [#list-of-filters]
*String Fields*
* `==`
* `!=`
* `exists`
* `not-exists`
* `starts-with`
* `not-starts-with`
* `ends-with`
* `not-ends-with`
* `contains`
* `not-contains`
* `regexp`
* `not-regexp`
*Number Fields*
* `==`
* `!=`
* `exists`
* `not-exists`
* `>`
* `>=`
* `<`
* `<=`
*Boolean Fields*
* `==`
* `!=`
* `exists`
* `not-exists`
*Array Fields*
* `contains`
* `not-contains`
* `exists`
* `not-exists`
### Group by (segmentation) [#group-by-segmentation]
When visualizing data, it can be useful to segment data into specific groups to more clearly understand how the data behaves.
The Group By component enables you to add one or more fields to group events by:
### Other options [#other-options]
#### Order [#order]
By default, Axiom automatically chooses the best ordering for results. However, you can manually set the desired order through this menu.
#### Limit [#limit]
By default, Axiom chooses a reasonable limit for the query that has been passed in. However, you can control that limit manually through this component.
## Change element’s position [#change-elements-position]
To change element’s position on the dashboard, drag the title bar of the chart.
## Change element size [#change-element-size]
To change the size of the element, drag the bottom-right corner.
## Set custom time range [#set-custom-time-range]
You can set a custom time range for individual dashboard elements that’s different from the dashboard’s time range. For example, the dashboard displays data about the last 30 minutes but individual dashboard elements display data for different time ranges. This can be useful for visualizing the same chart or statistic for different time periods, among others.
To set a custom time range for a dashboard element:
1. In the top right of the dashboard element, click **More >** **Edit**.
2. In the top right above the chart, click .
3. Click **Custom**.
4. Choose one of the following options:
* Use the **Quick range** items to quickly select popular time ranges.
* Use the **Custom start/end date** fields to select specific times.
5. Click **Save**.
Axiom displays the new time range in the top left of the dashboard element.
### Set custom time range in APL [#set-custom-time-range-in-apl]
To set a custom time range for dashboard elements created with APL, you can use the [procedure above](#set-custom-time-range) or define the time range in the APL query:
1. In the top right of the dashboard element, click **More >** **Edit**.
2. In the APL query, specify the custom time range using the [where](/apl/tabular-operators/where-operator) operator. For example:
```kusto
| where _time > now(-6h)
```
3. Click **Run query** to preview the result.
4. Click **Save**.
Axiom displays in the top left of the dashboard element to indicate that its time range is defined in the APL query and might be different from the dashboard’s time range.
## Set custom comparison period [#set-custom-comparison-period]
You can set a custom comparison time period for individual dashboard elements that’s different from the dashboard’s. For example, the dashboard compares against data from yesterday but individual dashboard elements display data for different comparison periods.
To set a custom comparison period for a dashboard element:
1. In the top right of the dashboard element, click **More >** **Edit**.
2. In the top right above the chart, click **Compare period**.
3. Click **Custom**.
4. Choose one of the following options:
* Use the **Quick range** items to quickly select popular comparison periods.
* Use the **Custom time** field to select specific comparison periods.
5. Click **Save**.
Axiom displays the new comparison period in the top left of the dashboard element.
---
# Gauge
Source: https://axiom.co/docs/dashboard-elements/gauge
Gauge dashboard elements compare a single numeric value with colored segments. Use a gauge to show whether a current value, such as an error count or average response time, is within an expected range.
## Configure gauge segments [#configure-gauge-segments]
Use the segment rail to configure the ranges:
1. Enter exact boundary values in the inputs above the rail, or drag a boundary handle.
2. Click the scissors control inside a segment to split that segment.
3. Click the remove control below a shared boundary to merge the adjacent segments.
For a row-based view, expand **Edit segment values**. Enter the **From** and **To** values for each segment, or use **Split segment** and **Remove**. Each segment starts where the previous segment ends.
The selected color scale assigns a color to each segment.
## Configure gauge display [#configure-gauge-display]
Configure the gauge with the following options:
* **Sparkline**: Display the value over time inside the gauge.
* **Color scale**: Apply colors from green to red or from red to green.
* **Labels**: Display evenly spaced **Intervals**, segment **Boundaries**, or no labels. **Intervals** is the default.
* **Scale to time range**: Scale segment values in proportion to changes in the dashboard time range. Enable this option for count and sum thresholds that represent the chart's saved time range.
* **Custom units**: Display a unit after the gauge value.
## Query requirements [#query-requirements]
Gauge queries return one numeric series. In Builder, add exactly one aggregation and leave **Group by** empty. In APL, use a `summarize` or `count` statement. If the query contains `summarize`, return one expression from the last `summarize` statement and group only by `_time`, if at all.
## Example with Builder [#example-with-builder]
In Builder, summarize `req_duration_ms` with the `avg` aggregation.
## Example with APL [#example-with-apl]
```kusto
['sample-http-logs']
| summarize avg(req_duration_ms) by bin_auto(_time)
```
---
# Heatmap
Source: https://axiom.co/docs/dashboard-elements/heatmap
Heatmaps represent the distribution of numerical data by grouping values into ranges or buckets. Each bucket reflects a frequency count of data points that fall within its range. Instead of showing individual events or measurements, heatmaps give a clear view of the overall distribution patterns. This allows you to identify performance bottlenecks, outliers, or shifts in behavior. For instance, you can use heatmaps to track response times, latency, or error rates.
## Example with Builder [#example-with-builder]
## Example with APL [#example-with-apl]
```kusto
['sample-http-logs']
| summarize histogram(req_duration_ms, 15) by bin_auto(_time)
```
---
# Log stream
Source: https://axiom.co/docs/dashboard-elements/log-stream
The log stream dashboard element displays your logs as they come in real-time. Each log appears as a separate line with various details. The benefit of a log stream is that it provides immediate visibility into your system’s operations. When you debug an issue or trying to understand an ongoing event, the log stream allows you to see exactly what’s happening as it occurs.
## Example with Builder [#example-with-builder]
## Example with APL [#example-with-apl]
```kusto
['sample-http-logs']
| project method, status, content_type
```
---
# Monitor list
Source: https://axiom.co/docs/dashboard-elements/monitor-list
The monitor list dashboard element provides a visual overview of the monitors you specify. It offers a quick glance into important developments about the monitors such as their status and history.
* [Create a monitor](/monitor-data/monitors).
## Create monitor list [#create-monitor-list]
1. Go to the Dashboards tab and open the dashboard to which you want to add the monitor list.
2. Click **Edit dashboard**.
3. Click **Add element** in the top right corner.
4. Click **Monitor list** from the list.
5. In **Columns**, select the type of information you want to display for each monitor:
* **Status** displays if the monitor state is normal, triggered, or turned off.
* **History** provides a visual overview of the recent runs of the monitor. Green squares mean normal operation and red squares mean triggered state.
* **Dataset** is the name of the dataset on which the monitor operates.
* **Type** is the type of the monitor.
* **Notifiers** displays the notifiers connected to the monitor.
6. From the list, select the monitors you want to display on the dashboard.
7. Click **Save**.
The new element appears in your dashboard. At the bottom, click **Save** to save your changes to the dashboard.
---
# Note
Source: https://axiom.co/docs/dashboard-elements/note
The note dashboard element adds a textbox to your dashboard that you can customise to your needs. For example, you can provide context in a note about the other dashboard elements.
## Create note [#create-note]
1. Go to the Dashboards tab and open the dashboard to which you want to add the note.
2. Click **Edit dashboard**.
3. Click **Add element** in the top right corner.
4. Click **Note** from the list.
5. Enter your text on the left in [GitHub Flavored Markdown](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) format. You see the preview of the note dashboard element on the right.
6. Click **Save**.
The new element appears in your dashboard. At the bottom, click **Save** to save your changes to the dashboard.
---
# Pie chart
Source: https://axiom.co/docs/dashboard-elements/pie-chart
Pie charts can illustrate the distribution of different types of event data. Each slice represents the proportion of a specific value relative to the total. For example, a pie chart can show the breakdown of status codes in HTTP logs. This helps quickly identify the dominant types of status responses and assess the system’s health at a glance.
## Example with Builder [#example-with-builder]
## Example with APL [#example-with-apl]
```kusto
['sample-http-logs']
| summarize count() by status
```
---
# Scatter plot
Source: https://axiom.co/docs/dashboard-elements/scatter-plot
Scatter plots are used to visualize the correlation or distribution between two distinct metrics or logs. Each point in the scatter plot could represent a log entry, with the X and Y axes showing different log attributes (like request time and response size). The scatter plot chart can be created using the simple query builder or advanced query builder.
For example, plot response size against response time for an API to see if larger responses are correlated with slower response times.
## Example with Builder [#example-with-builder]
## Example with APL [#example-with-apl]
```kusto
['sample-http-logs']
| summarize avg(req_duration_ms), avg(resp_header_size_bytes) by resp_body_size_bytes
```
---
# Spacer
Source: https://axiom.co/docs/dashboard-elements/spacer
The spacer dashboard element adds empty space to your dashboard layout. Use spacers to create visual separation between dashboard elements, improve the organization of your dashboard, and control the positioning of other elements.
## Create spacer [#create-spacer]
1. Go to the Dashboards tab and open the dashboard to which you want to add the spacer.
2. Click **Edit dashboard**.
3. Click **Add element** in the top right corner.
4. Click **Spacer** from the list.
5. Click **Save**.
The new element appears in your dashboard. At the bottom, click **Save** to save your changes to the dashboard.
You can resize and reposition the spacer element by dragging its edges or title bar, just like other dashboard elements.
---
# Statistic
Source: https://axiom.co/docs/dashboard-elements/statistic
Statistics dashboard elements display a summary of the selected metrics over a given time period. For example, you can use a statistic dashboard element to show the average, sum, min, max, and count of response times or error counts.
## Example with Builder [#example-with-builder]
## Example with APL [#example-with-apl]
```kusto
['sample-http-logs']
| summarize avg(resp_body_size_bytes)
```
---
# Table
Source: https://axiom.co/docs/dashboard-elements/table
The table dashboard element displays a summary of any attributes from your metrics, logs, or traces in a sortable table format. Each row in the table could represent a different service, host, or other entity, with columns showing various attributes or metrics for that entity.
## Example with Builder [#example-with-builder]
## Example with APL [#example-with-apl]
```kusto
['sample-http-logs']
| summarize avg(resp_body_size_bytes) by bin_auto(_time)
```
---
# Time series
Source: https://axiom.co/docs/dashboard-elements/time-series
Time series charts show the change in your data over time which can help identify infrastructure issues, spikes, or dips in the data. This can be a simple line chart, an area chart, or a bar chart. A time series chart might be used to show the change in the volume of log events, error rates, latency, or other time-sensitive data.
## Thresholds [#thresholds]
Add a threshold line to compare your data with a target value, such as a latency objective or an error limit. The chart displays the threshold as a dashed horizontal line. Line, area, bar, and percentile charts support threshold lines. Each chart displays one threshold line.
To add a threshold line:
1. In the chart editor, run the query. The threshold fields appear after the query returns results. Before that, the **Thresholds** section displays "Run the query to set a threshold."
2. In the settings panel on the right, expand **Thresholds**. This section is after **Y-axis**.
3. If the chart has more than one aggregation, select an aggregation in **Aggregation**. Each aggregation has its own threshold.
4. In **Value**, enter the threshold in the units of the chart's values. For more information, see [Threshold units](#threshold-units).
5. Optional: In **Color**, select a color for the line. The default color is red.
6. Optional: In **Highlight**, select **Above** or **Below** to shade the time intervals where the data crosses the threshold. The default is **None**.
To delete a threshold line, click **Remove threshold**.
Thresholds on dashboard charts are visual only. They don't send notifications. To get notified when a value crosses a threshold, create a [threshold monitor](/monitor-data/threshold-monitors).
### Threshold units [#threshold-units]
The **Value** field uses the units of the chart's values:
* **Time**: Select a unit from the list next to the field: ns, µs, ms, s, min, h, or d.
* **Data size**: Select a unit from the list next to the field. The list contains binary multiples (KiB, MiB, GiB) or decimal multiples (kB, MB, GB), depending on the unit of the field.
* **Percent**: Enter the percentage. For example, enter `95` for 95%.
* **Other units**: The field displays the unit, such as a currency symbol, before or after the value.
If the values have no unit, enter a number.
### How Axiom displays thresholds [#how-axiom-displays-thresholds]
* **Line**: Axiom displays the threshold as a dashed line in the selected color. Axiom extends the y-axis to show the line, even when your data doesn't reach the threshold.
* **Highlight**: Axiom shades each time interval where a series that the chart displays is above or below the threshold. Series from a time comparison don't count. In percentile charts, Axiom shades the time interval if any percentile crosses the threshold. Axiom doesn't shade the newest time interval while it's incomplete.
* **Tooltip**: The tooltip displays a **Threshold** row. If you select a highlight, the tooltip marks each series value that crosses the threshold.
In stacked charts (area and bar charts), Axiom compares the stack total with the threshold, not the individual series. The tooltip displays a **Total** row and marks the total if it crosses the threshold. The editor displays the hint "Stacked charts compare the stack total."
If the query uses automatic bin sizes and the aggregation is a count or a sum, the values depend on the bin size. The bin size changes with the time range. In this case, the editor displays the following warning: "The bin size changes with the time range, so a count or sum threshold only fits one bin size. Set a fixed bin size to compare against a constant value." To compare the data with a constant value, set a fixed bin size in the query.
## Example with Builder [#example-with-builder]
## Example with APL [#example-with-apl]
```kusto
['sample-http-logs']
| summarize count() by bin_auto(_time)
```
---
# Top list
Source: https://axiom.co/docs/dashboard-elements/top-list
The top list dashboard element displays the top results from your query, showing the most significant items based on your aggregation and grouping. It can display results as either a table of totals or as time series charts, depending on the aggregation type used.
## Example with Builder [#example-with-builder]
## Example with APL [#example-with-apl]
```kusto
['sample-http-logs']
| summarize count() by status
| top 10 by count_ desc
```
---
# Configure dashboards
Source: https://axiom.co/docs/dashboards/configure
## Select time range [#select-time-range]
When you select the time range, you specify the time interval for which you want to display data in the dashboard. Changing the time range affects the data displayed in all dashboard elements.
To select the time range:
1. In the top right, click **Time range**.
2. Choose one of the following options:
* Use the **Quick range** items to quickly select popular time ranges.
* Use the **Custom start/end date** fields to select specific times.
3. Click **Apply**.
## Select refresh rate [#select-refresh-rate]
Your dashboard regularly queries your data in the background to show the latest trends. The refresh rate is the time interval between these queries.
To select the refresh rate:
1. In the top right, click **Time range**.
2. Select one of the options in **Refresh rate**.
3. Click **Apply**.
Each time your dashboard refreshes, it runs a query on your data which results in query costs. Selecting a short refresh rate (such as 15 s) for a long time range (such as 90 days) means that your dashboard frequently runs large queries in the background. To optimize query costs, choose a refresh rate that’s appropriate for the time range of your dashboard.
## Share dashboards [#share-dashboards]
To specify who can access a dashboard:
{/* vale Google.FirstPerson = NO */}
1. In the top right, click **Share**.
2. Select one of the following:
* Select **Just Me** to make the dashboard private. Only you can access the dashboard.
* Select a group in your Axiom organization. Only members of the selected group can access the dashboard. For more information about groups, see [Access](/reference/settings).
* Select **Everyone** to make the dashboard accessible to all users in your Axiom organization.
3. At the bottom, click **Save** to save your changes to the dashboard.
{/* vale Google.FirstPerson = YES */}
The data that individual users see in the dashboard is determined by the datasets the users have access to. If a user has access to a dashboard but only to some of the datasets referenced in the dashboard’s charts, the user only sees data from the datasets they have access to.
### Share dashboards with time range [#share-dashboards-with-time-range]
To share a dashboard with a specific time range:
1. [Specify who can access a dashboard](#share-dashboards).
2. Determine the dashboard URL in your browser’s address bar.
3. Add time range parameters to the dashboard URL.
* For standard time ranges, add `?t_qr=RANGE` to the dashboard URL. Replace `RANGE` with the time range. For example, `?t_qr=7d` for the last 7 days.
* For custom time ranges, add `?t_ts=START&t_te=END` to the dashboard URL. Replace `START` and `END` with the start and end times in ISO 8601 format. For example, `?t_ts=2023-01-01T00:00:00.000Z&t_te=2023-01-07T23:59:59.999Z` for January 1-7, 2023.
* To compare your current time range against a previous period, add `?t_qr=RANGE&t_against=COMPARISON` or `?t_ts=START&t_te=END&t_against=COMPARISON` to the dashboard URL. Replace `COMPARISON` with the comparison period. For example, `?t_qr=24h&t_against=-1d` to compare the last 24 hours against the same time yesterday.
## Control display of annotations [#control-display-of-annotations]
To choose the annotation types to display:
1. In the dashboard toolbar, click **Annotations**.
2. Select the types to display.
For more information, see [Annotations](/annotations#show-and-hide-annotations-on-dashboards).
## Set dashboard as homepage [#set-dashboard-as-homepage]
To set a dashboard as the homepage of your browser, click **Set as homepage** in the top right.
## Enter full screen [#enter-full-screen]
Full-screen mode is useful for displaying the dashboard on a TV or shared monitor.
To enter full-screen mode, click **Full screen** in the top right.
---
# Create dashboards
Source: https://axiom.co/docs/dashboards/create
Dashboards provide a single view into your data. They visualize collections of queries across multiple datasets in one place. Dashboards are easy to share, benefit from collaboration, and bring separate datasets together in a single view.
## Dashboards tab [#dashboards-tab]
The Dashboards tab lists the dashboards you have access to.
* The **Integrations** section lists prebuilt dashboards. Axiom automatically built these dashboards as part of the [apps that enrich your Axiom experience](/apps/introduction). The integration dashboards are read-only and you can’t edit them. To create a copy of an integration dashboard that you can edit, [fork the original dashboard](#fork-dashboards).
* The sections below list the private and shared dashboards you can access.
To open a dashboard, click a dashboard in the list.
## Create dashboards [#create-dashboards]
To create a dashboard, choose one of the following:
* [Generate a dashboard](#generate-dashboards-using-ai) using AI based on a natural-language prompt.
* [Create an empty dashboard](#create-empty-dashboards).
* [Fork an existing dashboard](#fork-dashboards). This is how you make a copy of prebuilt integration dashboards that you can’t directly edit.
* [Duplicate an existing dashboard](#duplicate-dashboards). This is how you make a copy of dashboards other than prebuilt integration dashboards.
After creating a dashboard:
* [Add dashboard elements](/dashboard-elements/create). For example, add a table or a time series chart.
* [Configure the dashboard](/dashboards/configure). For example, control who can access the dashboard and change the time range.
## Generate dashboards using AI [#generate-dashboards-using-ai]
Explain in your own words what you want to see in your dashboard and Axiom’s AI generates it in seconds.
1. Click the Dashboards tab.
2. In the top right corner, click **New dashboard**.
3. In Type, click **Generate dashboard**.
4. In Dataset, select the dataset from which you want to generate the dashboard.
5. Add a name and a description. Explain in detail what you want to see in your dashboard. The more specific you are, the closer the generated dashboard matches your expectations.
6. Click **Create dashboard**.
You can currently generate dashboards based on a single dataset. After generating the dashboard, you can edit it and add dashboard elements that rely on data from other datasets.
Axiom samples events in your dataset to understand the data schema and generate dashboards using AI. For the sampling to be meaningful, your dataset needs to have a minimum number of events. The exact number varies, but around 3,000 events in the last 7 days is usually sufficient.
For more flexibility, use an AI coding assistant with the [Build dashboards skill](/console/intelligence/skills/build-dashboards). This approach supports multiple data sources, iterative follow-up prompts, and using screenshots of existing dashboards from other tools as context.
## Create empty dashboards [#create-empty-dashboards]
1. Click the Dashboards tab.
2. In the top right corner, click **New dashboard**.
3. In Type, select **Empty dashboard**.
4. Add a name and a description.
5. Click **Create dashboard**.
## Fork dashboards [#fork-dashboards]
1. Click the Dashboards tab.
2. Find the dashboard in the list and right-click it.
3. Click **Fork dashboard**.
## Duplicate dashboards [#duplicate-dashboards]
1. Click the Dashboards tab.
2. Find the dashboard in the list and right-click it.
3. Click **Duplicate dashboard**.
## Delete dashboard [#delete-dashboard]
1. Click the Dashboards tab.
2. Find the dashboard in the list and right-click it.
3. Click **Delete dashboard**.
4. Click **Delete**.
---
# Dashboard sections
Source: https://axiom.co/docs/dashboards/sections
Sections group related dashboard elements under a shared header. Use sections to divide a large dashboard. Each section expands and collapses independently. When you collapse a section, Axiom stops running queries for the elements inside it. Expand the section to load the elements again.
## Create section [#create-section]
1. Go to the Dashboards tab and open the dashboard where you want to add the section.
2. Click **Edit dashboard**.
3. Click **Add element** in the top right corner.
4. In **Section**, click **Add section**.
5. Enter a name for the section.
6. Click **Add**.
7. Click **Save dashboard**.
The new section appears below dashboard elements that aren't assigned to a section.
## Add dashboard elements to section [#add-dashboard-elements-to-section]
To create a dashboard element directly in a section:
1. Click **Edit dashboard**.
2. In the section header, click **Add element to section**.
3. Select the type of dashboard element to add.
4. Configure the dashboard element, and then click **Save**.
5. Click **Save dashboard**.
To move an existing dashboard element into a section, enter edit mode and drag the element by its title bar into the section. Drag elements between sections in the same way. To remove an element from a section, drag it to the area above the first section.
Filter bars remain outside sections because they apply to the entire dashboard.
## Expand and collapse section [#expand-and-collapse-section]
Click the section header to expand or collapse the section. Collapsing a section stops the queries for its dashboard elements. Expanding the section runs the queries and displays the elements again.
Axiom remembers the expanded or collapsed state for each section in the current browser. This state doesn't change the dashboard for other users.
## Configure section [#configure-section]
To configure a section:
1. Click **Edit dashboard**.
2. In the section header, click **Section options**.
3. Choose one of the following options:
* Click **Rename** to change the section name.
* Click **Collapse by default** to initially display the section as collapsed. Viewers can still expand it.
* Click **Expand by default** to initially display the section as expanded. Viewers can still collapse it.
4. Click **Save dashboard**.
To change the order of sections, enter edit mode and drag the handle to the left of the section name. Sections always appear below dashboard elements that aren't assigned to a section.
## Delete section [#delete-section]
1. Click **Edit dashboard**.
2. In the section header, click **Section options**.
3. Choose one of the following options:
* Click **Delete section, keep charts** to remove the section and move its dashboard elements outside all sections.
* Click **Delete section and charts** to remove the section and all its dashboard elements from the dashboard.
4. Confirm the deletion.
5. Click **Save dashboard**.
**Delete section and charts** removes every dashboard element in the section when you save the dashboard.
---
# Frequently asked questions
Source: https://axiom.co/docs/get-help/faq
{/* vale off */}
This page aims to offer a deeper understanding of Axiom. If you can’t find an answer to your questions, please feel free to [contact our team](https://axiom.co/contact).
## What’s Axiom? [#whats-axiom]
Axiom is a log management and analytics solution that reduces the cost and management overhead of logging as much data as you want.
With Axiom, organizations no longer need to choose between their data and their costs. Axiom has been built from the ground up to allow for highly efficient data ingestion and storage, and then a zero-to-infinite query scaling that allows you to query all your data, all the time.
Organizations use Axiom for continuous monitoring and observability, as well as an event store for running analytics and deriving insights from all their event data.
Axiom consists of a datastore and a user experience that work in tandem to provide a completely unique log-management and analytics experience.
## How is Axiom deployed? [#how-is-axiom-deployed]
Axiom offers Axiom Cloud, a fully managed cloud service with usage-based pricing.
## How is Axiom different than other logging solutions? [#how-is-axiom-different-than-other-logging-solutions]
At Axiom, our goal is that no organization has to ignore or delete a single piece of data no matter its source: logs, events, frontend, backends, audits, etc.
We found that existing solutions would place restrictions on how much data can be collected either on purpose or as a side-effect of their architectures.
For example, state of the art in logging is running stateful clusters that need shared knowledge of ingestion and will use a mixture of local SSD-based storage and remote object storage.
### Side-effects of legacy vendors [#side-effects-of-legacy-vendors]
1. There is a non-trivial cost in increasing your data ingest as clusters need to be scaled and more SSD storage and IOPs need to be provided
2. The choice needs to be made between hot and cold data, and also what is archived. Now your data is in 2-3 different places and queries can be fast or slow depending on where the data is
The end result is needing to carefully consider all data that’s ingested, and putting limits and/or sampling to control the DevOps and cost burden.
### The ways Axiom is different [#the-ways-axiom-is-different]
1. Decoupled ingest and querying pipelines
2. Stateless ingest pipeline that requires minimal compute/memory to storage as much as 1.5 TB/day per vCPU
3. Ingests all data into object storage, enabling the cheapest storage possible for all ingested data
4. Enables querying scale-out with cloud functions, requiring no constantly running servers waiting for a query to be processed. Instead, enjoy zero-to-infinity querying instantly
### The benefits of Axiom’s approach [#the-benefits-of-axioms-approach]
1. The most efficient ingestion pipeline for massive amounts of data
2. Store more data for less by exclusively using inexpensive object storage for all data
3. Query data that’s 10 milliseconds or 10 years old at any time
4. Reduce the total cost of ownership of your log management and analytics pipelines with simple scale and maintenance that Axiom provides
5. Free your organization to do more with it’s data
## How long can I retain data with Axiom? [#how-long-can-i-retain-data-with-axiom]
The free forever Personal plan provides a generous 30 days of retention.
The Axiom Cloud and the Bring Your Own Cloud plans allow you to customize the data retention period to your needs, with the option for “Forever” retention so your organization has access to all its data, all the time.
For more information, see [Pricing](https://axiom.co/pricing).
## Can I try Axiom for free? [#can-i-try-axiom-for-free]
Yes. The Personal plan is free forever with a generous allowance. It’s available to all customers.
With unlimited users included, the Axiom Cloud plan starting at $25/month is a great choice for growing companies and for enterprise organizations who want to run a proof-of-concept.
For more information, see [Pricing](https://axiom.co/pricing).
## How is Axiom licensed? [#how-is-axiom-licensed]
The Axiom Cloud plan is billed on a monthly basis.
For the Bring Your Own Cloud plan, the platform fee is billed on an annual basis.
For more information, see [Pricing](https://axiom.co/pricing).
---
# Glossary of key Axiom terms
Source: https://axiom.co/docs/getting-started-guide/glossary
{/* vale off */}
[A](#a) B [C](#c) [D](#d) [E](#e) F G H [I](#i) K [L](#l) [M](#m) [N](#n) [O](#o) [P](#p) [Q](#q) [R](#r) [S](#s) [T](#t) U [V](#v) W X Y Z
{/* vale on */}
## A [#a]
### Annotation [#annotation]
Annotations mark a point or interval in time on charts in Query, dashboards, and monitors. They add context to trends and help you investigate issues. For more information, see [Annotations](/annotations).
### Anomaly monitor [#anomaly-monitor]
Anomaly monitors allow you to aggregate your event data and compare the results of this aggregation to what can be considered normal for the query. When the results are too much above or below the value that Axiom expects based on the event history, the monitor enters the alert state. The monitor remains in the alert state until the results no longer deviate from the expected value. This can happen without the results returning to their previous level if they stabilize around a new value. An anomaly monitor sends you a notification each time it enters or exits the alert state.
For more information, see [Anomaly monitors](/monitor-data/anomaly-monitors).
### API [#api]
The Axiom API allows you to ingest structured data logs, handle queries, and manage your deployments.
For more information, see [Introduction to Axiom API](/restapi/introduction).
### API token [#api-token]
See [Tokens](#token).
### App [#app]
Axiom's dedicated apps enrich your Axiom organization by integrating into popular external services and providing out-of-the-box features such as prebuilt dashboards.
For more information, see [Introduction to apps](/apps/introduction).
### Axiom [#axiom]
Axiom represents the next generation of business intelligence. Designed and built for the cloud, Axiom is an event platform for logs, traces, and all technical data.
Axiom efficiently ingests, stores, and queries vast amounts of event data from any source at a fraction of the cost. The Axiom platform is built for unmatched efficiency, scalability, and performance.
### Axiom Cloud [#axiom-cloud]
Axiom Cloud is a deployment option and pricing plan with a fully managed cloud service and usage-based pricing.
### Axiom MCP Server [#axiom-mcp-server]
Axiom MCP Server is a Model Context Protocol (MCP) server implementation that enables AI agents to query your data using Axiom Processing Language (APL). It supports MCP tools for executing queries, listing datasets, retrieving schemas, and accessing dashboards and monitors. Axiom MCP Server allows AI agents like Claude and Cursor to interact directly with your Axiom data.
For more information, see [Axiom MCP Server](/console/intelligence/mcp-server).
### Axiom Processing Language (APL) [#axiom-processing-language-apl]
Axiom Processing Language (APL) is a query language that's perfect for getting deeper insights from your data. Whether logs, events, analytics, or similar, APL provides the flexibility to filter, manipulate, and summarize your data exactly the way you need it.
For more information, see [Introduction to APL](/apl/introduction).
## C [#c]
### CLI [#cli]
Axiom's command line interface (CLI) is an Axiom tool that lets you test, manage, and build your Axiom organizations by typing commands on the command-line. You can use the command line to ingest data, manage authentication state, and configure multiple organizations.
For more information, see [Introduction to CLI](/reference/cli).
### Console [#console]
Axiom Console is the web user interface for data management, querying, dashboarding, monitoring, and user administration. It provides tools for exploring data, building queries, creating dashboards, configuring monitors, and managing access controls.
## D [#d]
### Dashboard [#dashboard]
Dashboards allow you to visualize collections of queries across multiple datasets in one place. Dashboards are easy to share, benefit from collaboration, and bring separate datasets together in a single view.
For more information, see [Create dashboards](/dashboards/create).
### Dashboard element [#dashboard-element]
Dashboard elements are the different visual elements that you can include in your dashboard to display your data and other information. For example, you can track key metrics, logs, and traces, and monitor real-time data flow.
For more information, see [Create dashboard elements](/dashboard-elements/create).
### Dataset [#dataset]
Axiom's datastore is tuned for the efficient collection, storage, and analysis of timestamped event data. An individual piece of data is an event, and a dataset is a collection of related events. Datasets contain incoming event data.
For more information, see [Datasets](/reference/datasets).
## E [#e]
### Edge deployment [#edge-deployment]
An edge deployment is an infrastructure location where Axiom stores your event data at rest. When you create an organization, you choose a primary edge deployment. This determines the default location where your data is ingested, stored, and queried. Edge deployments will provide flexibility for data jurisdiction requirements while maintaining unified management through Axiom's Console.
For more information, see [Edge deployments](/reference/edge-deployments).
### Event [#event]
An event is a granular record capturing a specific action or interaction within a system, often represented as key-value pairs. It's the smallest unit of information detailing what occurred, who, or what was involved, and potentially when and where it took place. In Axiom's context, events are timestamped records, originating from human, machine, or sensor interactions, providing a foundational data point that informs a broader view of activities across different business units, from product, through security, to marketing, and more.
### EventDB [#eventdb]
EventDB is the foundation of Axiom's platform for ingesting, storing, and querying timestamped event data at scale. It features a multi-layered ingestion system, custom block-based storage format on object storage with extreme compression, and serverless ephemeral runtimes for query execution.
For more information, see [Architecture](/platform-overview/architecture).
## I [#i]
### Intelligence [#intelligence]
Intelligence refers to Axiom's suite of AI-powered features that accelerate insights and automate data analysis. This includes Spotlight for automatic root cause analysis, natural language querying, AI-powered dashboard generation, and the Axiom MCP Server for AI agent integration.
For more information, see [Intelligence](/console/intelligence).
## L [#l]
### Log [#log]
A log is a structured or semi-structured data record typically used to document actions or system states over time, primarily for monitoring, debugging, and auditing. Traditionally formatted as text entries with timestamps and message content, logs have evolved to include standardized key-value structures, making them easier to search, interpret, and correlate across distributed systems. In Axiom, logs represent historical records designed for consistent capture, storage, and collaborative analysis, allowing for real-time visibility and troubleshooting across services.
For more information, see [Axiom for observability](/getting-started-guide/observability).
## M [#m]
### Match monitor [#match-monitor]
Match monitors allow you to continuously filter your log data and send you matching events. Axiom sends a notification for each matching event. By default, the notification message contains the entire matching event in JSON format. When you define your match monitor using APL, you can control which event attributes to include in the notification message.
For more information, see [Match monitors](/monitor-data/match-monitors).
### Metric [#metric]
A metric is a quantitative measurement collected at specific time intervals, reflecting the state or performance of a system or component. Metrics focus on numeric values, such as CPU usage or memory consumption, enabling aggregation, trend analysis, and alerting based on thresholds. Within Axiom, metrics are data points associated with timestamps, labels, and values, designed to monitor resource utilization or performance. Metrics enable predictive insights by identifying patterns over time, offering foresight into system health and potential issues before they escalate.
For more information, see [Axiom for observability](/getting-started-guide/observability).
### MetricsDB [#metricsdb]
MetricsDB is Axiom's dedicated metrics datastore purpose-built for high-cardinality time-series data. Unlike traditional metrics datastores that struggle with dimensional complexity, MetricsDB is designed to handle high numbers of unique tag combinations efficiently without performance degradation or cost penalties.
For more information, see [Architecture](/platform-overview/architecture).
### Model Context Protocol (MCP) [#model-context-protocol-mcp]
Model Context Protocol (MCP) is an open standard that enables AI agents to interact with external data sources and tools. Axiom implements MCP through the Axiom MCP Server, allowing AI agents to query datasets, list resources, and execute APL queries programmatically.
For more information, see [Axiom MCP Server](/console/intelligence/mcp-server).
### Monitor [#monitor]
A monitor is a background task that periodically runs a query that you define. For example, it counts the number of error messages in your logs over the previous 5 minutes. A notifier defines how Axiom notifies you about the monitor output. For example, Axiom can send you an email.
You can use the following types of monitor:
* [Anomaly monitors](#anomaly-monitor) aggregate event data over time and look for values that are unexpected based on the event history. When the results of the aggregation are too high or low compared to the expected value, Axiom sends you an alert.
* [Match monitors](#match-monitor) filter for key events and send them to you.
* [New values monitors](#new-values-monitor) watch a column of your query results. When the column holds a value that Axiom hasn’t seen recently, Axiom sends you an alert.
* [Threshold monitors](#threshold-monitor) aggregate event data over time. When the results of the aggregation cross a threshold, Axiom sends you an alert.
For more information, see [Introduction to monitors](/monitor-data/monitors).
## N [#n]
### New values monitor [#new-values-monitor]
New values monitors watch a column of your query results and record the values it holds. When the column holds a value that the monitor hasn’t seen during the lookback period, Axiom sends a notification. Axiom sends one notification for each new value.
For more information, see [New values monitors](/monitor-data/new-values-monitors).
### Notifier [#notifier]
A monitor is a background task that periodically runs a query that you define. For example, it counts the number of error messages in your logs over the previous 5 minutes. A notifier defines how Axiom notifies you about the monitor output. For example, Axiom can send you an email.
For more information, see [Introduction to notifiers](/monitor-data/notifiers-overview).
## O [#o]
### Observability [#observability]
Observability is a principle in software engineering and systems monitoring that focuses on the ability to understand and diagnose the internal state of a system by examining the data it generates, such as logs, metrics, and traces. It goes beyond traditional monitoring by giving teams the power to pinpoint and resolve issues, optimize performance, and understand user behaviors across complex, interconnected services. Observability leverages various types of [event data](#event) to provide granular insights that span everything from simple log messages to multi-service transactions (traces) and performance metrics.
Traditionally, observability has been associated with three pillars:
* Logs capture individual events or errors.
* Metrics provide quantitative data over time, like CPU usage.
* Traces represent workflows across microservices.
However, modern observability expands on this by aggregating diverse data types from engineering, product, marketing, and security functions, all of which contribute to understanding the deeper "why" behind user interactions and system behaviors. This holistic view, in turn, enables real-time diagnostics, predictive analyses, and proactive issue resolution.
In essence, observability transforms raw event data into actionable insights, helping organizations not only to answer "what happened?" but also to delve into "why it happened" and "what might happen next."
For more information, see [Axiom for observability](/getting-started-guide/observability).
### OpenTelemetry [#opentelemetry]
OpenTelemetry (OTel) is an open-source observability framework for cloud-native software. It provides a standardized way to collect and export telemetry data (logs, traces, and metrics) from applications. Axiom supports OpenTelemetry and allows you to send data from any existing OpenTelemetry shipper, library, or tool.
For more information, see [Send OpenTelemetry data to Axiom](/send-data/opentelemetry).
## P [#p]
### Personal access token (PAT) [#personal-access-token-pat]
See [Tokens](#token).
### Playground [#playground]
Axiom Playground is an interactive sandbox environment where you can quickly try out Axiom's capabilities.
To try out Axiom, go to the [Axiom Playground](https://play.axiom.co/).
## Q [#q]
### Query [#query]
In Axiom, a query is a specific, structured request used to get deeper insights into your data. It typically involves looking for information based on defined parameters like keywords, date ranges, or specific fields. The intent of a query is precision: to locate, analyze, or manipulate specific subsets of data within vast data structures, enhancing insights into various operational aspects or user behaviors.
Querying enables you to filter, manipulate, extend, and summarize your data.
### Query-hours [#query-hours]
When you run queries, your usage of the Axiom platform is measured in query-hours. The unit of this measurement is GB-hours which reflects the duration (measured in milliseconds) serverless functions are running to execute your query multiplied by the amount of memory (GB) allocated to execution. This metric is important for monitoring and managing your usage against the monthly allowance included in your plan.
For more information, see [Optimize usage](/reference/optimize-usage).
## R [#r]
### Role-Based Access Control (RBAC) [#role-based-access-control-rbac]
Role-Based Access Control (RBAC) allows you to manage and restrict access to your data and resources efficiently.
For more information, see [Access](/reference/settings).
## S [#s]
### Span [#span]
A span represents an individual action or operation within a trace. Spans capture the duration and metadata of specific operations as a request flows through a distributed system. Related spans are grouped together using trace IDs to form complete traces that show the full path of a request.
For more information, see [Trace](#trace).
### Spotlight [#spotlight]
Spotlight is an interactive analysis feature that helps you find the root cause of issues faster. It allows you to highlight a region of event data and automatically identifies how it deviates from baseline across different fields. Instead of manually crafting queries to investigate anomalies, Spotlight analyzes every field in your data and presents the most significant differences.
For more information, see [Spotlight](/console/intelligence/spotlight).
### Stream [#stream]
The Stream tab in Axiom Console allows you to inspect individual events and watch as they're ingested live. It provides real-time visibility into your data, enabling you to filter events, view event details, and investigate issues as they happen.
For more information, see [Stream data](/query-data/stream).
## T [#t]
### Threshold monitor [#threshold-monitor]
Threshold monitors allow you to periodically aggregate your event data and compare the results of this aggregation to a threshold that you define. When the results cross the threshold, the monitor enters the alert state. The monitor remains in the alert state until the results no longer cross the threshold. A threshold monitor sends you a notification each time it enters or exits the alert state.
For more information, see [Threshold monitors](/monitor-data/threshold-monitors).
### Token [#token]
You can use the Axiom API and CLI to programmatically ingest and query data, and manage settings and resources. For example, you can create new API tokens and change existing datasets with API requests. To prove that these requests come from you, you must include forms of authentication called tokens in your API requests. Axiom offers two types of tokens:
* API tokens let you control the actions that can be performed with the token. For example, you can specify that requests authenticated with a certain API token can only query data from a particular dataset.
* Personal access tokens (PATs) provide full control over your Axiom account. Requests authenticated with a PAT can perform every action you can perform in Axiom.
For more information, see [Tokens](/reference/tokens).
### Trace [#trace]
A trace is a sequence of events that captures the path and flow of a single request as it navigates through multiple services or components within a distributed system. Utilizing trace IDs to group-related spans (individual actions or operations within a request), traces enable visibility into the lifecycle of a request, illustrating how it progresses, where delays or errors may occur, and how components interact. By connecting each event in the request journey, traces provide insights into system performance, pinpointing bottlenecks and latency.
## V [#v]
### Virtual fields [#virtual-fields]
Virtual fields allow you to derive new values from your data in real time, eliminating the need for up-front data structuring. Instead of transforming data during ingestion, you can use virtual fields to manipulate data during queries using APL expressions. Virtual fields can be used for filtering, visualization, and segmentation.
Virtual fields are query-time representations only. They don't create new data in storage.
For more information, see [Virtual fields](/query-data/virtual-fields).
---
# Axiom for observability
Source: https://axiom.co/docs/getting-started-guide/observability
Axiom helps you leverage the power of timestamped machine data. A common use case of machine data is observability (o11y) in the field of software engineering. Observability is the ability to explain what’s happening inside a software system by observing it from the outside. It allows you to understand the behavior of systems based on their outputs such as telemetry data, which is a type of machine data.
Software engineers most often work with timestamped machine data in the form of logs, metrics, and traces. However, Axiom believes that machine data reflects a much broader range of interactions, crossing boundaries from engineering to product management, security, and beyond.
## Types of machine data in observability [#types-of-machine-data-in-observability]
Traditionally, observability has been associated with three pillars, each effectively a specialized view of machine data:
* **Logs**: Logs record discrete events, such as error messages or access requests, typically associated with engineering or security.
* **Traces**: Traces track the path of requests through a system, capturing each step’s duration. By linking related spans within a trace, developers can identify bottlenecks and dependencies.
* **Metrics**: Metrics quantify state over time, recording data like CPU usage or user count at intervals. Product or engineering teams can then monitor and aggregate these values for performance insights.
Axiom supports all three types of data, allowing for fine-grained, efficient tracking across the three pillars.
## Logs, traces, and events [#logs-traces-and-events]
Axiom excels at collecting, storing, and analyzing timestamped event data.
For logs and traces, Axiom offers unparalleled efficiency and query performance. You can send logs and traces to Axiom from a wide range of popular sources. For more information, see [Send data to Axiom](/send-data/methods).
## Metrics [#metrics]
For metrics, Axiom offers a dedicated metrics datastore with query performance optimized for high-cardinality time-series data. You can send OpenTelemetry metrics to Axiom and query them using MPL (Metrics Processing Language). For more information, see [Metrics](/query-data/metrics).
---
# Axiom for product analytics
Source: https://axiom.co/docs/getting-started-guide/product-analytics
Axiom helps you leverage the power of timestamped event data. Axiom believes that event data reflects a broad range of interactions, crossing boundaries from engineering to product management, security, and beyond.
This page explains how you can leverage the power of event data for the product analytics use case.
In product analytics, the ability to harness and interpret data effectively can determine the success of a product. Axiom allows product analytics to leverage the power of timestamped event data and easily read every single event. Your organization can gain actionable insights, optimize user experiences, and drive product innovation.
## Why event data matters in product analytics [#why-event-data-matters-in-product-analytics]
Event data captures the actions and interactions users have with a product over time. From button clicks and page views to error events and feature usage, every timestamped event tells a story about user behavior. Axiom’s platform is specifically designed to process and analyze these granular datasets, making it an indispensable tool for product teams aiming to do the following:
* **Understand user behavior:** By tracking and analyzing event streams, Axiom provides a clear picture of how users engage with your product.
* **Identify trends and patterns:** Time-series analysis reveals emerging trends, helping teams anticipate user needs and adjust strategies proactively.
* **Optimize product features:** Pinpoint which features drive the most value and identify friction points that need improvement.
## Key features of Axiom for product analytics [#key-features-of-axiom-for-product-analytics]
The following key features make Axiom perfect for product analytics:
* **Real-time event monitoring:** Axiom’s ability to ingest and process data in real-time means you can monitor user activity as it happens. This empowers product managers to act quickly in response to anomalies or unexpected usage patterns, reducing downtime and improving user satisfaction. For example:
* Track whether feature flags are toggling as expected.
* Watch for broken signup flows or onboarding drop-offs immediately after a deploy.
* Monitor if newly launched features are generating engagement.
* **Unified data platform:** Axiom eliminates data silos by integrating event data from diverse sources into a single, cohesive platform. Axiom stores system telemetry alongside product analytics data. This eliminates the traditional separation between “user behavior” tools and “engineering” tools, and this convergence unlocks powerful debugging and insight scenarios:
* Correlate frontend feature usage with backend latency.
* View conversion funnel stages alongside HTTP error logs.
* Link user drop-off to infrastructure anomalies.
* **Advanced query capabilities:** With a robust query language, Axiom enables product teams to dive deep into data analysis. Perform detailed segmentation, drill down into specific user journeys, and uncover insights that would otherwise remain hidden.
* **Custom dashboards and visualizations:** Intuitive dashboards and customizable visualizations make it easy for product managers to communicate insights to stakeholders. Axiom’s visual tools enhance collaboration and decision-making.
* **Scalable infrastructure:** As your product grows, so does the volume of event data. Axiom’s architecture is built to scale effortlessly, ensuring that your analytics remain robust and reliable, even with massive datasets.
## Standard patterns for product data: Segment compatibility [#standard-patterns-for-product-data-segment-compatibility]
Axiom supports event ingestion via widely adopted patterns such as the [Segment specification](https://segment.com/docs/connections/spec/):
* **`identify`** associates events with known users.
* **`track`** records user interactions like button clicks or page views.
* **`group`** associates users with organizations or accounts.
These event types are foundational to many analytics workflows and are supported by tools like Mixpanel, Amplitude, June, and RudderStack. Axiom’s compatibility with this ecosystem enables product teams to reuse existing instrumentation patterns and schemas with minimal changes.
### How Axiom receives Segment events [#how-axiom-receives-segment-events]
To send Segment data to Axiom:
1. In Axiom, [create a dataset](/reference/datasets) for the Segment events and [generate an API token](/reference/tokens) with permission to ingest into that dataset.
2. In Segment, add a [webhook destination](https://segment.com/docs/connections/destinations/catalog/webhooks/) with the following settings:
* **Webhook URL**: `https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME`
* **Header** `Authorization`: `Bearer API_TOKEN`
* **Header** `Content-Type`: `application/x-ndjson`
For more details on the ingest endpoint, see [Send data via the REST API](/restapi/ingest).
Segment sends event payloads to Axiom in JSON format. Axiom stores each incoming payload as a structured event, preserving keys such as `event`, `userId`, `traits`, `properties`, and `_time` (automatically inferred or provided). No custom transformation is required. Segment’s default schema maps naturally into Axiom’s JSON ingestion pipeline.
After sending events to Axiom, query them using APL. For example, to count “Button Clicked” events per user by hour:
```kusto
['segment-frontend-prod']
| where event == "Button Clicked"
| summarize count() by userId, bin(_time, 1h)
```
## Use cases: from funnels to retention [#use-cases-from-funnels-to-retention]
Here are some ways product teams use Axiom:
### Feature adoption tracking [#feature-adoption-tracking]
Measure which users are engaging with newly released features.
```kusto
['segment-frontend-prod']
| where event == "AI Chat Created" and properties.featureName == "AI Chat"
| summarize count() by userId, bin(_time, 1h)
```
### Retention and churn analysis [#retention-and-churn-analysis]
Analyze returning users over time:
```kusto
['segment-frontend-prod']
| where event == "Logged In"
| summarize sessions = count(), users = dcount(userId) by bin(_time, 1w)
```
### Data for funnel diagnostics [#data-for-funnel-diagnostics]
Trace where users drop off between signup, onboarding, and first value.
```kusto
['segment-frontend-prod']
| where event in ("Signed Up", "Completed Onboarding", "Created Project")
| project userId, event, _time
| sort by userId, _time
```
### A/B test measurement [#ab-test-measurement]
Compare experiment cohorts based on downstream engagement:
```kusto
['segment-frontend-prod']
| where properties.experimentGroup == "variant_a"
| where event == "Clicked Upgrade"
| summarize conversions = dcount(userId)
```
## Why choose Axiom for product analytics [#why-choose-axiom-for-product-analytics]
Axiom’s focus on timestamped event data makes it perfect for product analytics. By crossing boundaries from engineering to product management and security, Axiom empowers cross-functional teams to collaborate effectively. Its comprehensive feature set ensures that organizations can unlock the full potential of their data, driving smarter decisions and fostering innovation.
In competitive markets, understanding your users is paramount. With Axiom, you gain a trusted partner in turning event data into actionable insights that propel your product to new heights. Experience the future of product analytics with Axiom and transform how you build, analyze, and optimize your product.
---
# Axiom Go adapter for Apex
Source: https://axiom.co/docs/guides/apex
Use the adapter of the Axiom Go SDK to send logs generated by the [apex/log](https://github.com/apex/log) library to Axiom.
The Axiom Go SDK is an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/axiom-go).
## Set up SDK [#set-up-sdk]
1. Install the Axiom Go SDK and configure your environment as explained in [Send data from Go app to Axiom](/guides/go).
2. In your Go app, import the `apex` package. It’s imported as an `adapter` so that it doesn’t conflict with the `apex/log` package.
```go
import adapter "github.com/axiomhq/axiom-go/adapters/apex"
```
Alternatively, configure the adapter using [options](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/apex#Option) passed to the [New](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/apex#New) function:
```go
handler, err := adapter.New(
adapter.SetDataset("DATASET_NAME"),
)
```
## Configure client [#configure-client]
To configure the underlying client manually, choose one of the following:
* Use [SetClient](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/apex#SetClient) to pass in the client you have previously created with [Send data from Go app to Axiom](/guides/go).
* Use [SetClientOptions](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/apex#SetClientOptions) to pass [client options](https://pkg.go.dev/github.com/axiomhq/axiom-go/axiom#Option) to the adapter.
```go
import (
"github.com/axiomhq/axiom-go/axiom"
adapter "github.com/axiomhq/axiom-go/adapters/apex"
)
// ...
handler, err := adapter.New(
adapter.SetClientOptions(
axiom.SetPersonalTokenConfig("AXIOM_TOKEN", "AXIOM_ORG_ID"),
),
)
```
### Configure region [#configure-region]
By default, the adapter sends data to `api.axiom.co`. To target a specific edge region, pass `axiom.SetEdge` through `SetClientOptions` with the edge domain that matches the region your dataset lives in:
```go EU Central 1
handler, err := adapter.New(
adapter.SetClientOptions(
axiom.SetAPITokenConfig("xaat-your-api-token"),
axiom.SetEdge("eu-central-1.aws.edge.axiom.co"),
),
)
```
```go US East 1
handler, err := adapter.New(
adapter.SetClientOptions(
axiom.SetAPITokenConfig("xaat-your-api-token"),
axiom.SetEdge("us-east-1.aws.edge.axiom.co"),
),
)
```
The following edge domains are available:
| Edge deployment | Base domain for ingest and query |
| ------------------ | -------------------------------- |
| US East 1 (AWS) | `us-east-1.aws.edge.axiom.co` |
| EU Central 1 (AWS) | `eu-central-1.aws.edge.axiom.co` |
Edge endpoints require an API token (`xaat-`), not a personal token (`xapt-`). Use `axiom.SetAPITokenConfig` when targeting an edge region. You can also set `AXIOM_EDGE` or `AXIOM_EDGE_URL` in the environment instead of `axiom.SetEdge`. For a full edge URL such as a proxy, use `axiom.SetEdgeURL`, which takes precedence over `axiom.SetEdge`.
The adapter uses a buffer to batch events before sending them to Axiom. Flush this buffer explicitly by calling [Close](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/apex#Handler.Close). For more information, see the [example in GitHub](https://github.com/axiomhq/axiom-go/blob/main/examples/apex/main.go).
## Reference [#reference]
For a full reference of the adapter’s functions, see the [Go Packages page](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/apex).
---
# Send data from Flutter app
Source: https://axiom.co/docs/guides/flutter
This page explains how to send structured logs from Flutter apps to Axiom using a custom logging library built with the [Dio HTTP client](https://pub.dev/packages/dio).
* [Install Flutter SDK](https://docs.flutter.dev/install) version 3.0.0 or higher.
## Install required dependencies [#install-required-dependencies]
To install the required Flutter dependencies, add these lines to your `pubspec.yaml` file:
```yaml
dependencies:
dio: ^5.4.0
intl: ^0.19.0
```
Then run the following code in your terminal to install dependencies:
```bash
flutter pub get
```
* **dio**: A powerful HTTP client for Dart that handles network requests to send logs to Axiom.
* **intl**: Provides internationalization and date/time formatting utilities for creating properly formatted timestamps.
## Create axiom\_logger.dart file [#create-axiom_loggerdart-file]
Create a `lib/axiom_logger.dart` file with the following content. This file defines the logger configuration, log levels, and the main logging functionality that sends structured logs to Axiom.
The logger implementation below includes the following key features:
* **Log Levels**: Five severity levels (debug, info, warning, error, critical) for categorizing log entries.
* **Batching**: Logs are buffered and sent in batches to reduce network overhead and improve performance.
* **Immediate Sending**: Critical logs are sent immediately to ensure important events are captured right away.
* **Metadata Support**: Attach custom metadata to logs for richer context and easier filtering.
* **Automatic Timestamps**: Logs are automatically timestamped in ISO 8601 format.
```dart lib/axiom_logger.dart expandable
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:intl/intl.dart';
/// Log level enumeration
enum LogLevel {
debug,
info,
warning,
error,
critical,
}
/// Extension to convert LogLevel to string
extension LogLevelExtension on LogLevel {
String get name {
switch (this) {
case LogLevel.debug:
return 'DEBUG';
case LogLevel.info:
return 'INFO';
case LogLevel.warning:
return 'WARNING';
case LogLevel.error:
return 'ERROR';
case LogLevel.critical:
return 'CRITICAL';
}
}
}
/// Configuration for the Axiom Logger
class AxiomLoggerConfig {
final String domain;
final String dataset;
final String apiToken;
final Duration timeout;
final bool enableDebugLogs;
AxiomLoggerConfig({
required this.domain,
required this.dataset,
required this.apiToken,
this.timeout = const Duration(seconds: 10),
this.enableDebugLogs = false,
});
String get ingestUrl => '$domain/v1/ingest/$dataset';
}
/// Main Axiom Logger class
class AxiomLogger {
final AxiomLoggerConfig config;
late final Dio _dio;
final List> _logBuffer = [];
final int _batchSize;
final Duration _flushInterval;
bool _isInitialized = false;
AxiomLogger({
required this.config,
int batchSize = 10,
Duration flushInterval = const Duration(seconds: 5),
}) : _batchSize = batchSize,
_flushInterval = flushInterval {
_initializeDio();
}
void _initializeDio() {
_dio = Dio(
BaseOptions(
baseUrl: config.domain,
connectTimeout: config.timeout,
receiveTimeout: config.timeout,
headers: {
'Authorization': 'Bearer ${config.apiToken}',
'Content-Type': 'application/json',
},
),
);
if (config.enableDebugLogs) {
_dio.interceptors.add(
LogInterceptor(
requestBody: true,
responseBody: true,
error: true,
requestHeader: true,
responseHeader: false,
),
);
}
_isInitialized = true;
}
/// Log a message with specified level
Future log(
LogLevel level,
String message, {
Map? metadata,
bool sendImmediately = false,
}) async {
if (!_isInitialized) {
print('AxiomLogger: Logger not initialized');
return;
}
final logEntry = _createLogEntry(level, message, metadata);
if (sendImmediately) {
await _sendLogs([logEntry]);
} else {
_logBuffer.add(logEntry);
if (_logBuffer.length >= _batchSize) {
await flush();
}
}
}
/// Create a structured log entry
Map _createLogEntry(
LogLevel level,
String message,
Map? metadata,
) {
final now = DateTime.now().toUtc();
final timestamp = DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(now);
return {
'_time': timestamp,
'level': level.name,
'message': message,
if (metadata != null) ...metadata,
};
}
/// Flush all buffered logs to Axiom
Future flush() async {
if (_logBuffer.isEmpty) {
return true;
}
final logsToSend = List>.from(_logBuffer);
_logBuffer.clear();
return await _sendLogs(logsToSend);
}
/// Send logs to Axiom
Future _sendLogs(List> logs) async {
try {
final response = await _dio.post(
config.ingestUrl,
data: jsonEncode(logs),
);
if (response.statusCode == 200 || response.statusCode == 204) {
if (config.enableDebugLogs) {
print('AxiomLogger: Successfully sent ${logs.length} log(s) to Axiom');
}
return true;
} else {
print('AxiomLogger: Failed to send logs. Status: ${response.statusCode}');
return false;
}
} catch (e) {
print('AxiomLogger: Error sending logs to Axiom: $e');
return false;
}
}
/// Convenience methods for different log levels
Future debug(String message, {Map? metadata}) async {
await log(LogLevel.debug, message, metadata: metadata);
}
Future info(String message, {Map? metadata}) async {
await log(LogLevel.info, message, metadata: metadata);
}
Future warning(String message, {Map? metadata}) async {
await log(LogLevel.warning, message, metadata: metadata);
}
Future error(String message, {Map? metadata}) async {
await log(LogLevel.error, message, metadata: metadata);
}
Future critical(String message, {Map? metadata}) async {
await log(LogLevel.critical, message, metadata: metadata, sendImmediately: true);
}
/// Dispose resources
Future dispose() async {
await flush();
_dio.close();
}
}
```
## Create main.dart file [#create-maindart-file]
Create an `example/main.dart` file with the following content. This file demonstrates how to use the Axiom Logger with different log levels and metadata.
```dart example/main.dart expandable
import 'package:flutter_logging/axiom_logger.dart';
/// Example usage of the Axiom Logger
Future main() async {
print('=== Flutter Axiom Logger Test ===\n');
// Initialize the logger with your Axiom configuration
final config = AxiomLoggerConfig(
domain: 'AXIOM_DOMAIN',
dataset: 'DATASET_NAME',
apiToken: 'API_TOKEN',
enableDebugLogs: true, // Enable to see HTTP requests/responses
);
final logger = AxiomLogger(
config: config,
batchSize: 5, // Send logs in batches of 5
flushInterval: Duration(seconds: 3),
);
print('Logger initialized. Sending test logs to Axiom...\n');
try {
// Test 1: Simple info log
print('Test 1: Sending INFO log...');
await logger.info(
'Application started successfully',
metadata: {
'app_name': 'Flutter Logging Demo',
'version': '1.0.0',
'environment': 'development',
},
);
// Test 2: Debug log with metadata
print('Test 2: Sending DEBUG log with metadata...');
await logger.debug(
'User authentication flow initiated',
metadata: {
'user_id': 'user_12345',
'session_id': 'session_abc123',
'ip_address': '192.168.1.100',
},
);
// Test 3: Warning log
print('Test 3: Sending WARNING log...');
await logger.warning(
'High memory usage detected',
metadata: {
'memory_mb': 512,
'threshold_mb': 400,
'process': 'main_app',
},
);
// Test 4: Error log
print('Test 4: Sending ERROR log...');
await logger.error(
'Failed to connect to database',
metadata: {
'error_code': 'DB_CONN_001',
'database': 'production_db',
'retry_count': 3,
'last_error': 'Connection timeout after 30s',
},
);
// Test 5: Multiple logs to test batching
print('Test 5: Sending multiple logs to test batching...');
for (int i = 1; i <= 3; i++) {
await logger.info(
'Processing batch item $i',
metadata: {
'batch_id': 'batch_001',
'item_number': i,
'status': 'processing',
},
);
}
// Test 6: Critical log (sends immediately)
print('Test 6: Sending CRITICAL log (immediate send)...');
await logger.critical(
'System failure: Out of memory',
metadata: {
'available_memory_mb': 10,
'required_memory_mb': 500,
'action_taken': 'emergency_shutdown',
},
);
// Flush any remaining buffered logs
print('\nFlushing remaining logs...');
await logger.flush();
print('\n✅ All logs sent successfully!');
print('\nYou can now check your Axiom dashboard at:');
print('https://app.axiom.co/DATASET_NAME');
} catch (e) {
print('❌ Error during logging: $e');
} finally {
// Clean up resources
await logger.dispose();
print('\nLogger disposed. Test complete.');
}
}
```
## Run the app and observe logs in Axiom [#run-the-app-and-observe-logs-in-axiom]
1. Run the following code in your terminal to run the Flutter example:
```bash
dart run example/main.dart
```
The app sends logs with different severity levels to Axiom, demonstrating batching, immediate sending for critical logs, and the use of custom metadata.
2. In Axiom, go to the Stream tab, and then click your dataset. This page displays the logs sent to Axiom and enables you to monitor and analyze your app's behavior and performance.
## Send data from an existing Flutter project [#send-data-from-an-existing-flutter-project]
### Basic integration [#basic-integration]
To add Axiom logging to your existing Flutter app, follow these steps:
1. Add the Axiom Logger to your project by copying the `axiom_logger.dart` file to your `lib` directory.
2. Initialize the logger early in your app's lifecycle, typically in your `main()` function.
```dart
import 'package:your_app/axiom_logger.dart';
void main() async {
// Initialize logger
final config = AxiomLoggerConfig(
domain: 'https://your-axiom-domain.com',
dataset: 'your-dataset',
apiToken: 'your-api-token',
enableDebugLogs: false, // Set to true for development
);
final logger = AxiomLogger(config: config);
// Log app startup
await logger.info('App started', metadata: {
'version': '1.0.0',
'platform': 'Flutter',
});
runApp(MyApp(logger: logger));
}
```
3. Use the logger throughout your app to capture important events, errors, and debug information. For example:
```dart
// Log user actions
await logger.info('User logged in', metadata: {
'user_id': userId,
'login_method': 'email',
});
// Log errors with context
try {
await someOperation();
} catch (e, stackTrace) {
await logger.error('Operation failed', metadata: {
'error': e.toString(),
'stack_trace': stackTrace.toString(),
'operation': 'someOperation',
});
}
```
### Integration with Flutter error handling [#integration-with-flutter-error-handling]
Capture Flutter framework errors and send them to Axiom:
```dart
void main() async {
final config = AxiomLoggerConfig(
domain: 'https://your-axiom-domain.com',
dataset: 'your-dataset',
apiToken: 'your-api-token',
);
final logger = AxiomLogger(config: config);
// Capture Flutter framework errors
FlutterError.onError = (FlutterErrorDetails details) async {
await logger.error(
'Flutter framework error',
metadata: {
'exception': details.exception.toString(),
'stack_trace': details.stack.toString(),
'library': details.library ?? 'unknown',
'context': details.context?.toString(),
},
);
};
// Capture async errors
PlatformDispatcher.instance.onError = (error, stack) {
logger.error(
'Uncaught async error',
metadata: {
'error': error.toString(),
'stack_trace': stack.toString(),
},
);
return true;
};
runApp(MyApp(logger: logger));
}
```
### Logging user interactions [#logging-user-interactions]
Track user behavior and navigation patterns:
```dart
class MyHomePage extends StatefulWidget {
final AxiomLogger logger;
const MyHomePage({required this.logger});
@override
State createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
@override
void initState() {
super.initState();
widget.logger.info('User navigated to home page', metadata: {
'timestamp': DateTime.now().toIso8601String(),
'screen': 'home',
});
}
Future _handleButtonPress() async {
await widget.logger.debug('Button pressed', metadata: {
'button': 'submit',
'screen': 'home',
});
// Your button logic here
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Home')),
body: ElevatedButton(
onPressed: _handleButtonPress,
child: Text('Submit'),
),
);
}
}
```
### Performance monitoring [#performance-monitoring]
Log performance metrics to identify bottlenecks:
```dart
Future performExpensiveOperation(AxiomLogger logger) async {
final stopwatch = Stopwatch()..start();
try {
await someExpensiveTask();
stopwatch.stop();
await logger.info('Operation completed', metadata: {
'operation': 'expensive_task',
'duration_ms': stopwatch.elapsedMilliseconds,
'status': 'success',
});
} catch (e) {
stopwatch.stop();
await logger.error('Operation failed', metadata: {
'operation': 'expensive_task',
'duration_ms': stopwatch.elapsedMilliseconds,
'status': 'failed',
'error': e.toString(),
});
}
}
```
### Best practices [#best-practices]
* **Use appropriate log levels**: Reserve `critical` for system failures, `error` for recoverable errors, `warning` for potential issues, `info` for important events, and `debug` for development details.
* **Add contextual metadata**: Include relevant information like user IDs, session IDs, device info, and operation context to make logs more useful.
* **Dispose properly**: Always call `logger.dispose()` when your app closes to ensure buffered logs are sent.
* **Handle errors gracefully**: Wrap logging calls in try-catch blocks to prevent logging failures from crashing your app.
* **Use batching wisely**: Adjust `batchSize` and `flushInterval` based on your app's logging volume and network conditions.
## Reference [#reference]
### List of log fields [#list-of-log-fields]
| Field Category | Field Name | Description |
| ----------------- | ------------- | ----------------------------------------------------------- |
| Core Fields | | |
| | \_time | ISO 8601 formatted timestamp when the log event occurred. |
| | level | Log severity level (DEBUG, INFO, WARNING, ERROR, CRITICAL). |
| | message | The main log message describing the event. |
| Custom Metadata | | |
| | app\_name | Name of the app generating the log. |
| | version | Application version number. |
| | environment | Deployment environment (development, staging, production). |
| | user\_id | Unique identifier for the user associated with the event. |
| | session\_id | Unique identifier for the user session. |
| | error\_code | Application-specific error code. |
| | duration\_ms | Duration of an operation in milliseconds. |
| | status | Status of an operation (success, failed, processing). |
| Device & Platform | | |
| | platform | Operating system or platform (iOS, Android, Web, Desktop). |
| | device\_model | Specific device model generating the log. |
| | os\_version | Operating system version. |
| Custom Fields | | |
| | \* | Any custom fields added via the metadata parameter. |
### Logger configuration options [#logger-configuration-options]
#### AxiomLoggerConfig [#axiomloggerconfig]
The `AxiomLoggerConfig` class configures how the logger connects to Axiom:
* **domain**: The base URL of your Axiom deployment (for example, `https://us-east-1.aws.edge.axiom.co`).
* **dataset**: The name of the Axiom dataset where logs are sent.
* **apiToken**: Your Axiom API token for authentication.
* **timeout**: Maximum time to wait for HTTP requests (default: 10 seconds).
* **enableDebugLogs**: Enable verbose HTTP logging for debugging (default: false).
#### AxiomLogger [#axiomlogger]
The `AxiomLogger` class manages log creation and transmission:
* **batchSize**: Number of logs to buffer before automatically flushing to Axiom (default: 10).
* **flushInterval**: Time interval for automatic flushing (default: 5 seconds). Note: Automatic interval-based flushing isn't yet implemented but can be added.
### Log levels [#log-levels]
The logger supports five log levels in increasing order of severity:
1. **DEBUG**: Detailed information for diagnosing problems, typically used during development.
2. **INFO**: Confirmation that things are working as expected, such as successful operations.
3. **WARNING**: Indication that something unexpected happened, but the app continues to work normally.
4. **ERROR**: A more serious problem that prevented a specific operation from completing.
5. **CRITICAL**: A severe error that may cause the app to fail or require immediate attention. Critical logs are sent immediately, bypassing the buffer.
### Key methods [#key-methods]
#### Logging methods [#logging-methods]
* `log(level, message, {metadata, sendImmediately})`: Core logging method that accepts any log level.
* `debug(message, {metadata})`: Convenience method for DEBUG level logs.
* `info(message, {metadata})`: Convenience method for INFO level logs.
* `warning(message, {metadata})`: Convenience method for WARNING level logs.
* `error(message, {metadata})`: Convenience method for ERROR level logs.
* `critical(message, {metadata})`: Convenience method for CRITICAL level logs (sends immediately).
#### Management methods [#management-methods]
* `flush()`: Manually send all buffered logs to Axiom. Returns a boolean indicating success.
* `dispose()`: Clean up resources, flush remaining logs, and close HTTP connections. Call this when shutting down the logger.
### Dependencies [#dependencies]
#### dio [#dio]
The [Dio package](https://pub.dev/packages/dio) is a powerful HTTP client for Dart that provides:
* Request and response interceptors for debugging and modifying HTTP traffic.
* Support for timeouts, custom headers, and authentication.
* Error handling and retry mechanisms.
* FormData, file uploading, and downloading capabilities.
In this logger, Dio handles all HTTP communication with Axiom's ingest API, including authentication via Bearer tokens and proper JSON serialization of log batches.
#### intl [#intl]
The [intl package](https://pub.dev/packages/intl) provides internationalization and localization support, including:
* Date and time formatting using standard patterns.
* Number formatting for different locales.
* Message translation support.
In this logger, intl is used to format timestamps in ISO 8601 format (`yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`), ensuring consistent and parseable timestamp strings across all log entries.
### Error handling [#error-handling]
The logger includes built-in error handling:
* Network failures are caught and logged to the console without crashing the app.
* Failed log sends return `false` from the `flush()` method, allowing you to implement retry logic.
* Uninitialized logger calls are safely ignored with console warnings.
### Thread safety [#thread-safety]
The logger is designed for use in Flutter's single-threaded Dart environment. All async operations use Dart's `Future` API, ensuring proper sequencing of log operations without race conditions.
---
# Send data from Go app to Axiom
Source: https://axiom.co/docs/guides/go
To send data from a Go app to Axiom, use the Axiom Go SDK.
The Axiom Go SDK is an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/axiom-go).
## Install SDK [#install-sdk]
To install the SDK, run the following:
```shell
go get github.com/axiomhq/axiom-go/axiom
```
Import the package:
```go
import "github.com/axiomhq/axiom-go/axiom"
```
If you use the [Axiom CLI](/reference/cli), run `eval $(axiom config export -f)` to configure your environment variables. Otherwise, [create an API token](/reference/tokens) and export it as `AXIOM_TOKEN`.
Alternatively, configure the client using [options](https://pkg.go.dev/github.com/axiomhq/axiom-go/axiom#Option) passed to the `axiom.NewClient` function:
```go
client, err := axiom.NewClient(
axiom.SetPersonalTokenConfig("AXIOM_TOKEN", "AXIOM_ORG_ID"),
)
```
## Use client [#use-client]
Create and use a client in the following way:
```go
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/axiomhq/axiom-go/axiom"
"github.com/axiomhq/axiom-go/axiom/ingest"
)
func main() {
ctx := context.Background()
client, err := axiom.NewClient()
if err != nil {
log.Fatal(err)
}
if _, err = client.IngestEvents(ctx, "my-dataset", []axiom.Event{
{ingest.TimestampField: time.Now(), "foo": "bar"},
{ingest.TimestampField: time.Now(), "bar": "foo"},
}); err != nil {
log.Fatal(err)
}
res, err := client.Query(ctx, "['my-dataset'] | where foo == 'bar' | limit 100")
if err != nil {
log.Fatal(err)
} else if res.Status.RowsMatched == 0 {
log.Fatal("No matches found")
}
for row := range res.Tables[0].Rows() {
fmt.Println(row)
}
}
```
For more examples, see the [examples in GitHub](https://github.com/axiomhq/axiom-go/tree/main/examples).
## Configure region [#configure-region]
By default, the client sends data to `api.axiom.co`. To target a specific edge region, pass the `SetEdge` option with the edge domain that matches the region your dataset lives in:
```go EU Central 1
client, err := axiom.NewClient(
axiom.SetEdge("eu-central-1.aws.edge.axiom.co"),
)
```
```go US East 1
client, err := axiom.NewClient(
axiom.SetEdge("us-east-1.aws.edge.axiom.co"),
)
```
This relies on `AXIOM_TOKEN` being set in your environment. To set the token in code as well, add `axiom.SetToken("xaat-...")`.
The following edge domains are available:
| Edge deployment | Base domain for ingest and query |
| ------------------ | -------------------------------- |
| US East 1 (AWS) | `us-east-1.aws.edge.axiom.co` |
| EU Central 1 (AWS) | `eu-central-1.aws.edge.axiom.co` |
For more information about edge deployments, see [Edge deployments](/reference/edge-deployments).
You can also configure the region without changing code by exporting environment variables:
```sh
export AXIOM_EDGE="eu-central-1.aws.edge.axiom.co"
# or, for a full URL (takes precedence over AXIOM_EDGE):
export AXIOM_EDGE_URL="https://eu-central-1.aws.edge.axiom.co"
```
To point at a custom edge endpoint such as a proxy or load balancer, use `axiom.SetEdgeURL("https://your-edge-host")`. `SetEdgeURL` takes precedence over `SetEdge` if both are set.
Edge endpoints require an API token (`xaat-`), not a personal token (`xapt-`). Ingest and query calls with a personal token against an edge endpoint return `personal tokens are not supported for edge operations, use an API token (xaat-)`.
## Adapters [#adapters]
To use a logging package, see the following adapters:
* [Apex](/guides/apex)
* [Logrus](/guides/logrus)
* [Zap](/guides/zap)
---
# Send data from JavaScript app to Axiom
Source: https://axiom.co/docs/guides/javascript
JavaScript is a versatile, high-level programming language primarily used for creating dynamic and interactive web content.
To send data from a JavaScript app to Axiom, use one of the following libraries of the Axiom JavaScript SDK:
*
@axiomhq/js
*
@axiomhq/logging
The choice between these options depends on your individual requirements:
| Capabilities | @axiomhq/js | @axiomhq/logging |
| --------------------------------------------------- | ----------- | ---------------- |
| Send data to Axiom | Yes | Yes |
| Query data | Yes | No |
| Capture errors | Yes | No |
| Create annotations | Yes | No |
| Transports | No | Yes |
| Structured logging by default | No | Yes |
| Send data to multiple places from a single function | No | Yes |
The `@axiomhq/logging` library is a logging solution that also serves as the base for other libraries like `@axiomhq/react` and `@axiomhq/nextjs`.
The @axiomhq/js and the @axiomhq/logging libraries are part of the Axiom JavaScript SDK, an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/axiom-js).
## Use @axiomhq/js [#use-axiomhqjs]
### Install @axiomhq/js [#install-axiomhqjs]
In your terminal, go to the root folder of your JavaScript app and run the following command:
```shell
npm install @axiomhq/js
```
### Configure environment variables [#configure-environment-variables]
Configure the environment variables in one of the following ways:
* Export the API token as `AXIOM_TOKEN`.
* Pass the API token to the constructor of the client:
```ts
import { Axiom } from '@axiomhq/js';
const axiom = new Axiom({
token: process.env.AXIOM_TOKEN,
});
```
* Install the [Axiom CLI](/reference/cli), and then run the following command:
```sh
eval $(axiom config export -f)
```
### Configure region [#configure-region]
By default, the client sends data to `api.axiom.co`. To target a specific edge region, set the `edge` option to the edge domain that matches the region your dataset lives in:
```ts EU Central 1
import { Axiom } from '@axiomhq/js';
const axiom = new Axiom({
token: process.env.AXIOM_TOKEN,
edge: 'eu-central-1.aws.edge.axiom.co',
});
```
```ts US East 1
import { Axiom } from '@axiomhq/js';
const axiom = new Axiom({
token: process.env.AXIOM_TOKEN,
edge: 'us-east-1.aws.edge.axiom.co',
});
```
The following edge domains are available:
| Edge deployment | Base domain for ingest and query |
| ------------------ | -------------------------------- |
| US East 1 (AWS) | `us-east-1.aws.edge.axiom.co` |
| EU Central 1 (AWS) | `eu-central-1.aws.edge.axiom.co` |
For more information about edge deployments, see [Edge deployments](/reference/edge-deployments).
Always use the `edge` option to target a region. Don't put a regional hostname in `url` — `url` is reserved for non-ingest API operations and won't route ingest correctly.
Edge endpoints require an API token (`xaat-`). Personal tokens (`xapt-`) are deprecated and aren't supported for edge routing.
### Client options [#client-options]
| Option | Required | Description |
| --------- | -------- | ------------------------------------------------------------------------------------------------------------------------- |
| `token` | yes | An Axiom API token with `ingest` permission for the dataset. |
| `orgId` | no | Organization ID. Required when using a personal token. |
| `edge` | no | Edge domain for ingest and query, without scheme. Example: `eu-central-1.aws.edge.axiom.co`. Use this to target a region. |
| `edgeUrl` | no | Full edge URL with scheme. Takes precedence over `edge` if both are set. Useful for self-hosted or proxy setups. |
| `url` | no | Base URL for non-ingest API operations. Only needed if you call other Axiom APIs from the same client. |
| `onError` | no | Callback invoked when sending data fails. Defaults to `console.error`. |
### Send data to Axiom [#send-data-to-axiom]
The following example sends data to Axiom:
```ts
axiom.ingest('DATASET_NAME', [{ foo: 'bar' }]);
await axiom.flush();
```
The client automatically batches events in the background. In most cases, call `flush()` only before your app exits.
### Query data [#query-data]
The following example queries data from Axiom:
```ts
const res = await axiom.query(`['DATASET_NAME'] | where foo == 'bar' | limit 100`);
console.log(res);
```
For more examples, see the [examples in GitHub](https://github.com/axiomhq/axiom-js/tree/main/examples).
### Capture errors [#capture-errors]
To capture errors, pass a method `onError` to the client:
```ts
let client = new Axiom({
token: '',
...,
onError: (err) => {
console.error('ERROR:', err);
}
});
```
By default, `onError` is set to `console.error`.
### Create annotations [#create-annotations]
The following example creates an annotation:
```ts
import { annotations } from '@axiomhq/js';
const client = new annotations.Service({ token: process.env.AXIOM_TOKEN || '' });
await client.create({
type: 'deployment',
datasets: ['DATASET_NAME'],
title: 'New deployment',
description: 'Deployed version 1.0.0',
});
```
## Use @axiomhq/logging [#use-axiomhqlogging]
### Install @axiomhq/logging [#install-axiomhqlogging]
In your terminal, go to the root folder of your JavaScript app and run the following command:
```bash
npm install @axiomhq/logging
```
### Send data to Axiom [#send-data-to-axiom-1]
The following example sends data to Axiom:
```ts
import { Logger, AxiomJSTransport, ConsoleTransport } from "@axiomhq/logging";
import { Axiom } from "@axiomhq/js";
const axiom = new Axiom({
token: process.env.AXIOM_TOKEN,
});
const logger = new Logger(
{
transports: [
new AxiomJSTransport({
axiom,
dataset: process.env.AXIOM_DATASET,
}),
new ConsoleTransport(),
],
}
);
logger.info("Hello, world!");
```
Because `AxiomJSTransport` sends data through the `@axiomhq/js` client, set the region by passing the `edge` option to the `Axiom` constructor. For the full list of edge domains, see [Configure region](#configure-region).
#### Transports [#transports]
The `@axiomhq/logging` library includes the following transports:
* `ConsoleTransport`: Logs to the console.
```ts
import { ConsoleTransport } from "@axiomhq/logging";
const transport = new ConsoleTransport({
logLevel: "warn",
prettyPrint: true,
});
```
* `AxiomJSTransport`: Sends logs to Axiom using the @axiomhq/js library.
```ts
import { Axiom } from "@axiomhq/js";
import { AxiomJSTransport } from "@axiomhq/logging";
const axiom = new Axiom({
token: process.env.AXIOM_TOKEN,
});
const transport = new AxiomJSTransport({
axiom,
dataset: process.env.AXIOM_DATASET,
logLevel: "warn",
});
```
* `ProxyTransport`: Sends logs the [proxy server function](/send-data/nextjs#proxy-for-client-side-usage) that acts as a proxy between your app and Axiom. It’s particularly useful when your app runs on top of a server-enabled framework like Next.js or Remix.
```ts
import { ProxyTransport } from "@axiomhq/logging";
const transport = new ProxyTransport({
url: "/proxy",
logLevel: "warn",
autoFlush: { durationMs: 1000 },
});
```
Alternatively, create your own transports by implementing the `Transport` interface:
```ts
import { Transport } from "@axiomhq/logging";
class MyTransport implements Transport {
log(log: Transport['log']) {
console.log(log);
}
flush() {
console.log("Flushing logs");
}
}
```
#### Logging levels [#logging-levels]
The `@axiomhq/logging` library includes the following logging levels:
* `debug`: Debug-level logs.
* `info`: Informational logs.
* `warn`: Warning logs.
* `error`: Error logs.
#### Formatters [#formatters]
Formatters are used to change the content of a log before sending it to a transport. For example:
```ts
import { Logger, LogEvent } from "@axiomhq/logging";
const myCustomFormatter = (event: LogEvent) => {
const upperCaseKeys = {
...event,
fields: Object.fromEntries(
Object.entries(event.fields).map(([key, value]) => [key.toUpperCase(), value])
),
};
return upperCaseKeys;
};
const logger = new Logger({
formatters: [myCustomFormatter],
});
logger.info("Hello, world!");
```
## Related logging options [#related-logging-options]
### Send data from JavaScript libraries and frameworks [#send-data-from-javascript-libraries-and-frameworks]
To send data to Axiom from JavaScript libraries and frameworks, see the following:
* [Send data from React app](/send-data/react)
* [Send data from Next.js app](/send-data/nextjs)
### Send data from Node.js [#send-data-from-nodejs]
While the Axiom JavaScript SDK works on both the backend and the browsers, Axiom provides transports for some of the popular loggers:
* [Pino](/guides/pino)
* [Winston](/guides/winston)
---
# Axiom Go adapter for Logrus
Source: https://axiom.co/docs/guides/logrus
Use the adapter of the Axiom Go SDK to send logs generated by the [sirupsen/logrus](https://github.com/sirupsen/logrus) library to Axiom.
The Axiom Go SDK is an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/axiom-go).
## Set up SDK [#set-up-sdk]
1. Install the Axiom Go SDK and configure your environment as explained in [Send data from Go app to Axiom](/guides/go).
2. In your Go app, import the `logrus` package. It’s imported as an `adapter` so that it doesn’t conflict with the `sirupsen/logrus` package.
```go
import adapter "github.com/axiomhq/axiom-go/adapters/logrus"
```
Alternatively, configure the adapter using [options](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/logrus#Option) passed to the [New](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/logrus#New) function:
```go
hook, err := adapter.New(
adapter.SetDataset("DATASET_NAME"),
)
```
## Configure client [#configure-client]
To configure the underlying client manually, choose one of the following:
* Use [SetClient](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/logrus#SetClient) to pass in the client you have previously created with [Send data from Go app to Axiom](/guides/go).
* Use [SetClientOptions](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/logrus#SetClientOptions) to pass [client options](https://pkg.go.dev/github.com/axiomhq/axiom-go/axiom#Option) to the adapter.
```go
import (
"github.com/axiomhq/axiom-go/axiom"
adapter "github.com/axiomhq/axiom-go/adapters/logrus"
)
// ...
hook, err := adapter.New(
adapter.SetClientOptions(
axiom.SetPersonalTokenConfig("AXIOM_TOKEN", "AXIOM_ORG_ID"),
),
)
```
### Configure region [#configure-region]
By default, the adapter sends data to `api.axiom.co`. To target a specific edge region, pass `axiom.SetEdge` through `SetClientOptions` with the edge domain that matches the region your dataset lives in:
```go EU Central 1
hook, err := adapter.New(
adapter.SetClientOptions(
axiom.SetAPITokenConfig("xaat-your-api-token"),
axiom.SetEdge("eu-central-1.aws.edge.axiom.co"),
),
)
```
```go US East 1
hook, err := adapter.New(
adapter.SetClientOptions(
axiom.SetAPITokenConfig("xaat-your-api-token"),
axiom.SetEdge("us-east-1.aws.edge.axiom.co"),
),
)
```
The following edge domains are available:
| Edge deployment | Base domain for ingest and query |
| ------------------ | -------------------------------- |
| US East 1 (AWS) | `us-east-1.aws.edge.axiom.co` |
| EU Central 1 (AWS) | `eu-central-1.aws.edge.axiom.co` |
Edge endpoints require an API token (`xaat-`), not a personal token (`xapt-`). Use `axiom.SetAPITokenConfig` when targeting an edge region. You can also set `AXIOM_EDGE` or `AXIOM_EDGE_URL` in the environment instead of `axiom.SetEdge`. For a full edge URL such as a proxy, use `axiom.SetEdgeURL`, which takes precedence over `axiom.SetEdge`.
The adapter uses a buffer to batch events before sending them to Axiom. Flush this buffer explicitly by calling [Close](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/logrus#Hook.Close). For more information, see the [example in GitHub](https://github.com/axiomhq/axiom-go/blob/main/examples/logrus/main.go).
## Reference [#reference]
For a full reference of the adapter’s functions, see the [Go Packages page](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/logrus).
---
# Monitor Claude Code with Axiom
Source: https://axiom.co/docs/guides/opentelemetry-claude-code
Claude Code has built-in [OpenTelemetry support](https://code.claude.com/docs/en/monitoring-usage) that exports metrics, logs, and traces (trace export is in beta). Axiom natively ingests OTLP data, making the two a natural fit. This guide covers the Axiom-specific configuration to connect Claude Code telemetry to Axiom.
## Prerequisites [#prerequisites]
* [Create an Axiom account](https://app.axiom.co/register).
* Create three datasets for metrics, logs, and traces in a [correlation group](/query-data/correlations). To create all three at once, go to **Datasets > Correlations > New correlation group**, select **From new datasets**, and enter a prefix such as `claude`. Axiom creates `claude-metrics`, `claude-logs`, and `claude-traces`.
* [Create an API token in Axiom](/reference/tokens) with ingest permissions for the three datasets only.
## How Axiom routes OpenTelemetry data [#how-axiom-routes-opentelemetry-data]
Axiom routes data to datasets via headers, and the header differs by signal type:
* Logs and traces use `x-axiom-dataset`
* Metrics use `x-axiom-metrics-dataset`
This means signal-specific header configuration is required rather than a single shared `OTEL_EXPORTER_OTLP_HEADERS` value.
## Configure environment variables [#configure-environment-variables]
Create a file named `setup-otel.sh` with the following content:
Don't execute the script directly. Source the script instead. The exported variables must exist in the current shell where Claude inherits them.
```bash setup-otel.sh
#!/bin/bash
# Claude Code OpenTelemetry configuration for Axiom
# Usage: source ./setup-otel.sh && claude
# Replace these with your own values
AXIOM_API_TOKEN="API_TOKEN"
AXIOM_HOST="AXIOM_DOMAIN"
AXIOM_METRICS_DATASET="METRICS_DATASET_NAME"
AXIOM_LOGS_DATASET="LOGS_DATASET_NAME"
AXIOM_TRACES_DATASET="TRACES_DATASET_NAME"
# Enable telemetry and configure the exporters
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=otlp
# Enable trace export (beta)
export CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1
export OTEL_TRACES_EXPORTER=otlp
# Use http/protobuf for all signals
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
# Separate endpoints per signal type
export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://${AXIOM_HOST}/v1/metrics
export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://${AXIOM_HOST}/v1/logs
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://${AXIOM_HOST}/v1/traces
# Separate headers per signal type (Axiom routes to datasets via different headers)
export OTEL_EXPORTER_OTLP_METRICS_HEADERS="Authorization=Bearer ${AXIOM_API_TOKEN},x-axiom-metrics-dataset=${AXIOM_METRICS_DATASET}"
export OTEL_EXPORTER_OTLP_LOGS_HEADERS="Authorization=Bearer ${AXIOM_API_TOKEN},x-axiom-dataset=${AXIOM_LOGS_DATASET}"
export OTEL_EXPORTER_OTLP_TRACES_HEADERS="Authorization=Bearer ${AXIOM_API_TOKEN},x-axiom-dataset=${AXIOM_TRACES_DATASET}"
# Shorter intervals for testing (default: 60s metrics, 5s logs)
export OTEL_METRIC_EXPORT_INTERVAL=10000
export OTEL_LOGS_EXPORT_INTERVAL=5000
# Optional: log full prompt content and tool/MCP details
export OTEL_LOG_USER_PROMPTS=1
export OTEL_LOG_TOOL_DETAILS=1
echo "Axiom OTel configured: metrics -> ${AXIOM_METRICS_DATASET}, logs -> ${AXIOM_LOGS_DATASET}, traces -> ${AXIOM_TRACES_DATASET}"
```
Replace `METRICS_DATASET_NAME` with the name of the Axiom dataset for metrics.
Replace `LOGS_DATASET_NAME` with the name of the Axiom dataset for logs.
Replace `TRACES_DATASET_NAME` with the name of the Axiom dataset for traces.
## Verify the integration [#verify-the-integration]
Run the following command in your terminal:
```bash
source ./setup-otel.sh && claude
```
Use Claude Code for 15 to 20 seconds to generate telemetry data. Ask questions, run commands, or perform any typical tasks.
In Axiom, go to your datasets and observe the telemetry data:
* The logs dataset shows events like `claude_code.user_prompt`, `claude_code.tool_result`, and `claude_code.api_request`.
* The metrics dataset shows counters like `claude_code.session.count` and `claude_code.token.usage`, updating on the 10-second interval configured above.
* The traces dataset shows spans like `claude_code.interaction` and `claude_code.llm_request`.
In the logs dataset, click an event, and then click **View trace**. Because the datasets are in a correlation group, Axiom opens the trace of the prompt that produced the event.
If one signal arrives but the other doesn't, double-check the headers. The most common mistake is using `x-axiom-dataset` for metrics instead of `x-axiom-metrics-dataset`.
## Production considerations [#production-considerations]
When moving from testing to production, consider these adjustments:
* **Disable prompt logging**: Remove `OTEL_LOG_USER_PROMPTS=1` unless prompt content is needed in your observability backend. This reduces the volume of sensitive data stored.
* **Limit content logging**: `OTEL_LOG_TOOL_DETAILS`, `OTEL_LOG_TOOL_CONTENT`, and `OTEL_LOG_RAW_API_BODIES` add commands, file contents, and full conversations to your telemetry. This content can include source code and secrets. Enable only the flags you need.
* **Use managed settings for teams**: For team deployments, administrators can set these variables in Claude Code's [managed settings file](https://code.claude.com/docs/en/monitoring-usage#administrator-configuration) instead of relying on each developer to source a script.
* **Add resource attributes**: Use `OTEL_RESOURCE_ATTRIBUTES` to tag all telemetry with department, team, or cost center identifiers for filtering and alerting in Axiom.
```bash
export OTEL_RESOURCE_ATTRIBUTES="team=platform,cost_center=engineering,environment=production"
```
* **Adjust export intervals**: For production, consider using longer intervals to reduce overhead:
```bash
export OTEL_METRIC_EXPORT_INTERVAL=60000 # 60 seconds
export OTEL_LOGS_EXPORT_INTERVAL=30000 # 30 seconds
```
## Reference [#reference]
### Environment variables [#environment-variables]
| Variable | Description |
| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `CLAUDE_CODE_ENABLE_TELEMETRY` | Set to `1` to enable OpenTelemetry export. |
| `OTEL_METRICS_EXPORTER` | Set to `otlp` to enable OTLP metrics export. |
| `OTEL_LOGS_EXPORTER` | Set to `otlp` to enable OTLP logs export. |
| `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA` | Set to `1` to enable trace export, which is in beta. |
| `OTEL_TRACES_EXPORTER` | Set to `otlp` to enable OTLP traces export. |
| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for all signals. Use `http/protobuf` for Axiom. |
| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | Axiom metrics endpoint URL. |
| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | Axiom logs endpoint URL. |
| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | Axiom traces endpoint URL. |
| `OTEL_EXPORTER_OTLP_METRICS_HEADERS` | Headers for metrics including authorization and dataset. |
| `OTEL_EXPORTER_OTLP_LOGS_HEADERS` | Headers for logs including authorization and dataset. |
| `OTEL_EXPORTER_OTLP_TRACES_HEADERS` | Headers for traces including authorization and dataset. |
| `OTEL_METRIC_EXPORT_INTERVAL` | Metrics export interval in milliseconds. Default: 60000. |
| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds. Default: 5000. |
| `OTEL_LOG_USER_PROMPTS` | Set to `1` to log full prompt content. |
| `OTEL_LOG_TOOL_DETAILS` | Set to `1` to log tool and MCP details. |
| `OTEL_LOG_TOOL_CONTENT` | Set to `1` to log tool output, such as file contents and command output, in trace spans. Requires trace export. |
| `OTEL_LOG_RAW_API_BODIES` | Set to `1` to log the full API request and response bodies, which include the conversation history. |
| `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH` | Maximum length of content attributes, such as tool output and API bodies, in UTF-16 code units. Default: 61440. The [maximum field size in Axiom](/reference/limits) is 1 MB, and `262144` stays under it for any text. |
| `OTEL_RESOURCE_ATTRIBUTES` | Comma-separated key=value pairs for resource attributes. |
### Expected telemetry data [#expected-telemetry-data]
Claude Code exports the following telemetry:
**Logs:**
* `claude_code.user_prompt`: User prompts sent to Claude Code.
* `claude_code.tool_result`: Results from tool executions.
* `claude_code.api_request`: API requests made by Claude Code.
**Metrics:**
* `claude_code.session.count`: Number of Claude Code sessions.
* `claude_code.token.usage`: Token usage counters.
**Traces:**
* `claude_code.interaction`: Root span for each user prompt.
* `claude_code.llm_request`: API requests made by Claude Code.
* `claude_code.tool`: Tool executions.
---
# OpenTelemetry using Cloudflare Workers
Source: https://axiom.co/docs/guides/opentelemetry-cloudflare-workers
This guide demonstrates how to configure OpenTelemetry in Cloudflare Workers to send telemetry data to Axiom using the [OTel CF Worker package](https://github.com/evanderkoogh/otel-cf-workers).
This guide also applies to web frameworks that run on Cloudflare Workers. For example, you can use the same OpenTelemetry configuration described below for [Hono](https://hono.dev/) apps deployed to Cloudflare Workers.
* Create a Cloudflare account.
* [Install Wrangler](https://developers.cloudflare.com/workers/wrangler/install-and-update/), the CLI tool for Cloudflare.
## Setting up your Cloudflare Workers environment [#setting-up-your-cloudflare-workers-environment]
Create a new directory for your project and navigate into it:
```bash
mkdir my-axiom-worker && cd my-axiom-worker
```
Initialize a new Wrangler project using this command:
```bash
wrangler init --type="javascript"
```
## Cloudflare Workers Script Configuration (index.ts) [#cloudflare-workers-script-configuration-indexts]
Configure and implement your Workers script by integrating OpenTelemetry with the `@microlabs/otel-cf-workers` package to send telemetry data to Axiom, as illustrated in the example `index.ts` below:
```js
// index.ts
import { trace } from '@opentelemetry/api';
import { instrument, ResolveConfigFn } from '@microlabs/otel-cf-workers';
export interface Env {
AXIOM_TOKEN: string,
AXIOM_DATASET: string
}
const handler = {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise {
await fetch('https://cloudflare.com');
const greeting = "Welcome to Axiom Cloudflare instrumentation";
trace.getActiveSpan()?.setAttribute('greeting', greeting);
ctx.waitUntil(fetch('https://workers.dev'));
return new Response(`${greeting}!`);
},
};
const config: ResolveConfigFn = (env: Env, _trigger) => {
return {
exporter: {
url: 'https://AXIOM_DOMAIN/v1/traces',
headers: {
'Authorization': `Bearer ${env.AXIOM_TOKEN}`,
'X-Axiom-Dataset': `${env.AXIOM_DATASET}`
},
},
service: { name: 'axiom-cloudflare-workers' },
};
};
export default instrument(handler, config);
```
## Wrangler Configuration (`wrangler.toml`) [#wrangler-configuration-wranglertoml]
Configure **`wrangler.toml`** with your Cloudflare account details and set environment variables for the Axiom API token and dataset.
```toml
name = "my-axiom-worker"
type = "javascript"
account_id = "$YOUR_CLOUDFLARE_ACCOUNT_ID" # Replace with your actual Cloudflare account ID
workers_dev = true
compatibility_date = "2023-03-27"
compatibility_flags = ["nodejs_compat"]
main = "index.ts"
# Define environment variables here
[vars]
AXIOM_TOKEN = "API_TOKEN"
AXIOM_DATASET = "DATASET_NAME"
```
## Install Dependencies [#install-dependencies]
Navigate to the root directory of your project and add `@microlabs/otel-cf-workers` and other OTel packages to the `package.json` file.
```json
{
"name": "my-axiom-worker",
"version": "1.0.0",
"description": "A template for kick-starting a Cloudflare Workers project",
"main": "index.ts",
"scripts": {
"start": "wrangler dev",
"deploy": "wrangler publish"
},
"dependencies": {
"@microlabs/otel-cf-workers": "^1.0.0-rc.20",
"@opentelemetry/api": "^1.6.0",
"@opentelemetry/core": "^1.17.1",
"@opentelemetry/exporter-trace-otlp-http": "^0.43.0",
"@opentelemetry/otlp-exporter-base": "^0.43.0",
"@opentelemetry/otlp-transformer": "^0.43.0",
"@opentelemetry/resources": "^1.17.1",
"@opentelemetry/sdk-trace-base": "^1.17.1",
"@opentelemetry/semantic-conventions": "^1.17.1",
"deepmerge": "^4.3.1",
"husky": "^8.0.3",
"lint-staged": "^15.0.2",
"ts-checked-fsm": "^1.1.0"
},
"devDependencies": {
"@changesets/cli": "^2.26.2",
"@cloudflare/workers-types": "^4.20231016.0",
"prettier": "^3.0.3",
"rimraf": "^4.4.1",
"typescript": "^5.2.2",
"wrangler": "2.13.0"
},
"private": true
}
```
Run `npm install` to install the packages. This command will install all the necessary packages listed in your `package.json` file.
## Running the instrumented app [#running-the-instrumented-app]
To run your Cloudflare Workers app with OpenTelemetry instrumentation, ensure your API token and dataset are correctly set in your `wrangler.toml` file. As outlined in the `package.json` file, you have two primary scripts to manage your app’s lifecycle.
### In development mode [#in-development-mode]
For local development and testing, you can start a local development server by running:
```bash
npm run start
```
This command runs `wrangler dev` allowing you to preview and test your app locally.
### Deploying to production [#deploying-to-production]
Deploy your app to the Cloudflare Workers environment by running:
```bash
npm run deploy
```
This command runs **`wrangler publish`**, deploying your project to Cloudflare Workers.
### Alternative: Use Wrangler directly [#alternative-use-wrangler-directly]
If you prefer not to use **`npm`** commands or want more direct control over the deployment process, you can use Wrangler commands directly in your terminal.
For local development:
```bash
wrangler dev
```
For deploying to Cloudflare Workers:
```bash
wrangler deploy
```
## View your app in Cloudflare Workers [#view-your-app-in-cloudflare-workers]
Once you’ve deployed your app using Wrangler, view and manage it through the Cloudflare dashboard. To see your Cloudflare Workers app, follow these steps:
* In your [Cloudflare dashboard](https://dash.cloudflare.com/), click **Workers & Pages** to access the Workers section. You see a list of your deployed apps.
* Locate your app by its name. For this tutorial, look for `my-axiom-worker`.
* Click your app’s name to view its details. Within the app’s page, select the triggers tab to review the triggers associated with your app.
* Under the routes section of the triggers tab, you will find the URL route assigned to your Worker. This is where your Cloudflare Worker responds to incoming requests. Vist the [Cloudflare Workers documentation](https://developers.cloudflare.com/workers/get-started/guide/) to learn how to configure routes
## Observe the telemetry data in Axiom [#observe-the-telemetry-data-in-axiom]
As you interact with your app, traces will be collected and exported to Axiom, allowing you to monitor, analyze, and gain insights into your app’s performance and behavior.
## Dynamic OpenTelemetry traces dashboard [#dynamic-opentelemetry-traces-dashboard]
This data can then be further viewed and analyzed in Axiom’s dashboard, offering a deeper understanding of your app’s performance and behavior.
**Working with Cloudflare Pages Functions:** Integration with OpenTelemetry is similar to Workers but uses the Cloudflare Dashboard for configuration, bypassing **`wrangler.toml`**. This simplifies setup through the Cloudflare dashboard web interface.
## Manual Instrumentation [#manual-instrumentation]
Manual instrumentation requires adding code into your Worker’s script to create and manage spans around the code blocks you want to trace.
1. Initialize Tracer:
Use the OpenTelemetry API to create a tracer instance at the beginning of your script using the **`@microlabs/otel-cf-workers`** package.
```js
import { trace } from '@opentelemetry/api';
const tracer = trace.getTracer('your-service-name');
```
2. Create start and end Spans:
Manually start spans before the operations or events you want to trace and ensure you end them afterward to complete the tracing lifecycle.
```js
const span = tracer.startSpan('operationName');
try {
// Your operation code here
} finally {
span.end();
}
```
3. Annotate Spans:
Add important metadata to spans to provide additional context. This can include setting attributes or adding events within the span.
```js
span.setAttribute('key', 'value');
span.addEvent('eventName', { 'eventAttribute': 'value' });
```
## Automatic Instrumentation [#automatic-instrumentation]
Automatic instrumentation uses the **`@microlabs/otel-cf-workers`** package to automatically trace incoming requests and outbound fetch calls without manual span management.
1. Instrument your Worker:
Wrap your Cloudflare Workers script with the `instrument` function from the **`@microlabs/otel-cf-workers`** package. This automatically instruments incoming requests and outbound fetch calls.
```js
import { instrument } from '@microlabs/otel-cf-workers';
export default instrument(yourHandler, yourConfig);
```
2. Configuration: Provide configuration details, including how to export telemetry data and service metadata to Axiom as part of the `instrument` function call.
```js
const config = (env) => ({
exporter: {
url: 'https://AXIOM_DOMAIN/v1/traces',
headers: {
'Authorization': `Bearer ${env.AXIOM_TOKEN}`,
'X-Axiom-Dataset': `${env.AXIOM_DATASET}`
},
},
service: { name: 'axiom-cloudflare-workers' },
});
```
After instrumenting your Worker script, the `@microlabs/otel-cf-workers` package takes care of tracing automatically.
## Reference [#reference]
### List of OpenTelemetry trace fields [#list-of-opentelemetry-trace-fields]
| Field Category | Field Name | Description |
| ---------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------- |
| **Unique Identifiers** | | |
| | \_rowid | Unique identifier for each row in the trace data. |
| | span\_id | Unique identifier for the span within the trace. |
| | trace\_id | Unique identifier for the entire trace. |
| **Timestamps** | | |
| | \_systime | System timestamp when the trace data was recorded. |
| | \_time | Timestamp when the actual event being traced occurred. |
| **HTTP Attributes** | | |
| | attributes.custom\["http.host"] | Host information where the HTTP request was sent. |
| | attributes.custom\["http.server\_name"] | Server name for the HTTP request. |
| | attributes.http.flavor | HTTP protocol version used. |
| | attributes.http.method | HTTP method used for the request. |
| | attributes.http.route | Route accessed during the HTTP request. |
| | attributes.http.scheme | Protocol scheme (HTTP/HTTPS). |
| | attributes.http.status\_code | HTTP response status code. |
| | attributes.http.target | Specific target of the HTTP request. |
| | attributes.http.user\_agent | User agent string of the client. |
| | attributes.custom.user\_agent.original | Original user agent string, providing client software and OS. |
| | attributes.custom\["http.accepts"] | Accepted content types for the HTTP request. |
| | attributes.custom\["http.mime\_type"] | MIME type of the HTTP response. |
| | attributes.custom.http.wrote\_bytes | Number of bytes written in the HTTP response. |
| | attributes.http.request.method | HTTP request method used. |
| | attributes.http.response.status\_code | HTTP status code returned in response. |
| **Network Attributes** | | |
| | attributes.net.host.port | Port number on the host receiving the request. |
| | attributes.net.peer.port | Port number on the peer (client) side. |
| | attributes.custom\["net.peer.ip"] | IP address of the peer in the network interaction. |
| | attributes.net.sock.peer.addr | Socket peer address, indicating the IP version used. |
| | attributes.net.sock.peer.port | Socket peer port number. |
| | attributes.custom.net.protocol.version | Protocol version used in the network interaction. |
| | attributes.network.protocol.name | Name of the network protocol used. |
| | attributes.network.protocol.version | Version of the network protocol used. |
| | attributes.server.address | Address of the server handling the request. |
| | attributes.url.full | Full URL accessed in the request. |
| | attributes.url.path | Path component of the URL accessed. |
| | attributes.url.query | Query component of the URL accessed. |
| | attributes.url.scheme | Scheme component of the URL accessed. |
| **Operational Details** | | |
| | duration | Time taken for the operation. |
| | kind | Type of span (for example,, server, client). |
| | name | Name of the span. |
| | scope | Instrumentation scope. |
| | scope.name | Name of the scope for the operation. |
| | service.name | Name of the service generating the trace. |
| | service.version | Version of the service generating the trace. |
| **Resource Attributes** | | |
| | resource.environment | Environment where the trace was captured, for example,, production. |
| | resource.cloud.platform | Platform of the cloud provider, for example,, cloudflare.workers. |
| | resource.cloud.provider | Name of the cloud provider, for example,, cloudflare. |
| | resource.cloud.region | Cloud region where the service is located, for example,, earth. |
| | resource.faas.max\_memory | Maximum memory allocated for the function as a service (FaaS). |
| **Telemetry SDK Attributes** | | |
| | telemetry.sdk.language | Language of the telemetry SDK, for example,, js. |
| | telemetry.sdk.name | Name of the telemetry SDK, for example,, @microlabs/otel-workers-sdk. |
| | telemetry.sdk.version | Version of the telemetry SDK. |
| **Custom Attributes** | | |
| | attributes.custom.greeting | Custom greeting message, for example,, "Welcome to Axiom Cloudflare instrumentation." |
| | attributes.custom\["http.accepts"] | Specifies acceptable response formats for HTTP request. |
| | attributes.custom\["net.asn"] | Autonomous System Number representing the hosting entity. |
| | attributes.custom\["net.colo"] | Colocation center where the request was processed. |
| | attributes.custom\["net.country"] | Country where the request was processed. |
| | attributes.custom\["net.request\_priority"] | Priority of the request processing. |
| | attributes.custom\["net.tcp\_rtt"] | Round Trip Time of the TCP connection. |
| | attributes.custom\["net.tls\_cipher"] | TLS cipher suite used for the connection. |
| | attributes.custom\["net.tls\_version"] | Version of the TLS protocol used for the connection. |
| | attributes.faas.coldstart | Indicates if the function execution was a cold start. |
| | attributes.faas.invocation\_id | Unique identifier for the function invocation. |
| | attributes.faas.trigger | Trigger that initiated the function execution. |
### List of imported libraries [#list-of-imported-libraries]
**`@microlabs/otel-cf-workers`**
This package is designed for integrating OpenTelemetry within Cloudflare Workers. It provides automatic instrumentation capabilities, making it easier to collect telemetry data from your Workers apps without extensive manual instrumentation. This package simplifies tracing HTTP requests and other asynchronous operations within Workers.
**`@opentelemetry/api`**
The core API for OpenTelemetry in JavaScript, providing the necessary interfaces and utilities for tracing, metrics, and context propagation. In the context of Cloudflare Workers, it allows developers to manually instrument custom spans, manipulate context, and access the active span if needed.
**`@opentelemetry/exporter-trace-otlp-http`**
This exporter enables your Cloudflare Workers app to send trace data over HTTP to any backend that supports the OTLP (OpenTelemetry Protocol), such as Axiom. Using OTLP ensures compatibility with a wide range of observability tools and standardizes the data export process.
**`@opentelemetry/otlp-exporter-base`**, **`@opentelemetry/otlp-transformer`**
These packages provide the foundational elements for OTLP exporters, including the transformation of telemetry data into the OTLP format and base classes for implementing OTLP exporters. They're important for ensuring that the data exported from Cloudflare Workers adheres to the OTLP specification.
**`@opentelemetry/resources`**
Defines the Resource, which represents the entity producing telemetry. In Cloudflare Workers, Resources can be used to describe the worker (for example,, service name, version) and are attached to all exported telemetry, aiding in identifying data in backend systems.
---
# Send OpenTelemetry data from a Django app to Axiom
Source: https://axiom.co/docs/guides/opentelemetry-django
* [Install Python version 3.7 or higher](https://www.python.org/downloads/).
## Install required dependencies [#install-required-dependencies]
Install the necessary Python dependencies by running the following command in your terminal:
```bash
pip install django opentelemetry-api opentelemetry-sdk opentelemetry-exporter-otlp-proto-http opentelemetry-instrumentation-django
```
Alternatively, you can add these dependencies to your `requirements.txt` file:
```bash
django
opentelemetry-api
opentelemetry-sdk
opentelemetry-exporter-otlp-proto-http
opentelemetry-instrumentation-django
```
Then, install them using the command:
```bash
pip install -r requirements.txt
```
## Get started with a Django project [#get-started-with-a-django-project]
1. Create a new Django project if you don’t have one already:
```bash
django-admin startproject your_project_name
```
2. Go to your project directory:
```bash
cd your_project_name
```
3. Create a Django app:
```bash
python manage.py startapp your_app_name
```
## Set up OpenTelemetry Tracing [#set-up-opentelemetry-tracing]
### Update `manage.py` to initialize tracing [#update-managepy-to-initialize-tracing]
This code initializes OpenTelemetry instrumentation for Django when the project is run. Adding `DjangoInstrumentor().instrument()` ensures that all incoming HTTP requests are automatically traced, which helps in monitoring the app’s performance and behavior without manually adding trace points in every view.
```py
# manage.py
#!/usr/bin/env python
import os
import sys
from opentelemetry.instrumentation.django import DjangoInstrumentor
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project_name.settings')
# Initialize OpenTelemetry instrumentation
DjangoInstrumentor().instrument()
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
```
### Create `exporter.py` for tracer configuration [#create-exporterpy-for-tracer-configuration]
This file configures the OpenTelemetry tracing provider and exporter. By setting up a `TracerProvider` and configuring the `OTLPSpanExporter`, you define how and where the trace data is sent. The `BatchSpanProcessor` is used to batch and send trace spans efficiently. The tracer created at the end is used throughout the app to create new spans.
```py
# exporter.py
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.resources import Resource, SERVICE_NAME
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
# Define the service name resource
resource = Resource(attributes={
SERVICE_NAME: "your-service-name" # Replace with your actual service name
})
# Create a TracerProvider with the defined resource
provider = TracerProvider(resource=resource)
# Configure the OTLP/HTTP Span Exporter with necessary headers and endpoint
otlp_exporter = OTLPSpanExporter(
endpoint="https://AXIOM_DOMAIN/v1/traces",
headers={
"Authorization": "Bearer API_TOKEN", # Replace with your actual API token
"X-Axiom-Dataset": "DATASET_NAME" # Replace with your dataset name
}
)
# Create a BatchSpanProcessor with the OTLP exporter
processor = BatchSpanProcessor(otlp_exporter)
provider.add_span_processor(processor)
# Set the TracerProvider as the global tracer provider
trace.set_tracer_provider(provider)
# Define a tracer for external use
tracer = trace.get_tracer("your-service-name")
```
### Use the tracer in your views [#use-the-tracer-in-your-views]
In this step, modify the Django views to use the tracer defined in `exporter.py`. By wrapping the view logic within `tracer.start_as_current_span`, you create spans that capture the execution of these views. This provides detailed insights into the performance of individual request handlers, helping to identify slow operations or errors.
```py
# views.py
from django.http import HttpResponse
from .exporter import tracer # Import the tracer
def roll_dice(request):
with tracer.start_as_current_span("roll_dice_span"):
# Your logic here
return HttpResponse("Dice rolled!")
def home(request):
with tracer.start_as_current_span("home_span"):
return HttpResponse("Welcome to the homepage!")
```
### Update `settings.py` for OpenTelemetry instrumentation [#update-settingspy-for-opentelemetry-instrumentation]
In your Django project’s `settings.py`, add the OpenTelemetry Django instrumentation. This setup automatically creates spans for HTTP requests handled by Django:
```py
# settings.py
from pathlib import Path
from opentelemetry.instrumentation.django import DjangoInstrumentor
DjangoInstrumentor().instrument()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
```
### Update the app’s `urls.py` to include the views [#update-the-apps-urlspy-to-include-the-views]
Include your views in the URL routing by updating `urls.py`. Updating `urls.py` with these entries sets up the URL routing for the Django app. It connects the URL paths to the corresponding view functions. This ensures that when users visit the specified paths, the corresponding views are executed, and their spans are created and sent to Axiom for monitoring.
```python urls.py
from django.urls import path
from .views import roll_dice, home
urlpatterns = [
path('', home, name='home'),
path('rolldice/', roll_dice, name='roll_dice'),
]
```
## Run the project [#run-the-project]
Run the command to start the Django project:
```bash
python3 manage.py runserver
```
In your browser, go to `http://127.0.0.1:8000/rolldice` to interact with your Django app. Each time you load the page, the app displays a message and sends the collected traces to Axiom.
## Send data from an existing Django project [#send-data-from-an-existing-django-project]
### Manual instrumentation [#manual-instrumentation]
Manual instrumentation in Python with OpenTelemetry involves adding code to create and manage spans around the blocks of code you want to trace. This approach allows for precise control over the trace data.
1. Install necessary OpenTelemetry packages to enable manual tracing capabilities in your Django app.
```py
pip install django opentelemetry-api opentelemetry-sdk opentelemetry-exporter-otlp-proto-http opentelemetry-instrumentation-django
```
2. Set up OpenTelemetry in your Django project to manually trace app activities.
```py
# otel_config.py
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
def configure_opentelemetry():
resource = Resource(attributes={"service.name": "your-django-app"})
trace.set_tracer_provider(TracerProvider(resource=resource))
otlp_exporter = OTLPSpanExporter(
endpoint="https://AXIOM_DOMAIN/v1/traces",
headers={"Authorization": "Bearer API_TOKEN", "X-Axiom-Dataset": "DATASET_NAME"}
)
span_processor = BatchSpanProcessor(otlp_exporter)
trace.get_tracer_provider().add_span_processor(span_processor)
return trace.get_tracer(__name__)
tracer = configure_opentelemetry()
```
3. Configure OpenTelemetry to your Django settings to capture telemetry data upon app startup.
```py
# settings.py
from otel_config import configure_opentelemetry
configure_opentelemetry()
```
4. Manually instrument views to create custom spans that trace specific operations within your Django app.
```py
# views.py
from django.http import HttpResponse
from otel_config import tracer
def home_view(request):
with tracer.start_as_current_span("home_view") as span:
span.set_attribute("http.method", request.method)
span.set_attribute("http.url", request.build_absolute_uri())
response = HttpResponse("Welcome to the home page!")
span.set_attribute("http.status_code", response.status_code)
return response
```
5. Apply manual tracing to database operations by wrapping database cursor executions with OpenTelemetry spans.
```py
# db_tracing.py
from django.db import connections
from otel_config import tracer
class TracingCursorWrapper:
def __init__(self, cursor):
self.cursor = cursor
def execute(self, sql, params=None):
with tracer.start_as_current_span("database_query") as span:
span.set_attribute("db.statement", sql)
span.set_attribute("db.type", "sql")
return self.cursor.execute(sql, params)
def __getattr__(self, attr):
return getattr(self.cursor, attr)
def patch_database():
for connection in connections.all():
connection.cursor_wrapper = TracingCursorWrapper
# settings.py
from db_tracing import patch_database
patch_database()
```
### Automatic instrumentation [#automatic-instrumentation]
Automatic instrumentation in Django with OpenTelemetry simplifies the process of adding telemetry data to your app. It uses pre-built libraries that automatically instrument the frameworks and libraries.
1. Install required packages that support automatic instrumentation.
```bash
pip install django opentelemetry-api opentelemetry-sdk opentelemetry-exporter-otlp-proto-http opentelemetry-instrumentation-django
```
2. Automatically configure OpenTelemetry to trace Django app operations without manual span management.
```py
# otel_config.py
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.django import DjangoInstrumentor
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
def configure_opentelemetry():
resource = Resource(attributes={"service.name": "your-django-app"})
trace.set_tracer_provider(TracerProvider(resource=resource))
otlp_exporter = OTLPSpanExporter(
endpoint="https://AXIOM_DOMAIN/v1/traces",
headers={"Authorization": "Bearer API_TOKEN", "X-Axiom-Dataset": "DATASET_NAME"}
)
span_processor = BatchSpanProcessor(otlp_exporter)
trace.get_tracer_provider().add_span_processor(span_processor)
DjangoInstrumentor().instrument()
```
3. Initialize OpenTelemetry in Django to capture telemetry data from all HTTP requests automatically.
```py
# settings.py
from otel_config import configure_opentelemetry
configure_opentelemetry()
```
4. Update `manage.py` to include OpenTelemetry initialization, ensuring that tracing is active before the Django app fully starts.
```py
#!/usr/bin/env python
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project.settings')
from otel_config import configure_opentelemetry
configure_opentelemetry()
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError("Couldn't import Django.") from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
```
5. (Optional) Combine automatic and custom manual spans in Django views to enhance trace details for specific complex operations.
```py
# views.py
from opentelemetry import trace
tracer = trace.get_tracer(__name__)
def complex_view(request):
with tracer.start_as_current_span("complex_operation"):
result = perform_complex_operation()
return HttpResponse(result)
```
## Reference [#reference]
### List of OpenTelemetry trace fields [#list-of-opentelemetry-trace-fields]
| Field Category | Field Name | Description |
| ------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------- |
| General Trace Information | | |
| | \_rowId | Unique identifier for each row in the trace data. |
| | \_sysTime | System timestamp when the trace data was recorded. |
| | \_time | Timestamp when the actual event being traced occurred. |
| | trace\_id | Unique identifier for the entire trace. |
| | span\_id | Unique identifier for the span within the trace. |
| | parent\_span\_id | Unique identifier for the parent span within the trace. |
| HTTP Attributes | | |
| | attributes.http.method | HTTP method used for the request. |
| | attributes.http.status\_code | HTTP status code returned in response. |
| | attributes.http.route | Route accessed during the HTTP request. |
| | attributes.http.scheme | Protocol scheme (HTTP/HTTPS). |
| | attributes.http.url | Full URL accessed during the HTTP request. |
| User Agent | | |
| | attributes.http.user\_agent | User agent string, providing client software and OS. |
| Custom Attributes | | |
| | attributes.custom\["http.host"] | Host information where the HTTP request was sent. |
| | attributes.custom\["http.server\_name"] | Server name for the HTTP request. |
| | attributes.custom\["net.peer.ip"] | IP address of the peer in the network interaction. |
| Network Attributes | | |
| | attributes.net.host.port | Port number on the host receiving the request. |
| Operational Details | | |
| | duration | Time taken for the operation, typically in microseconds or milliseconds. |
| | kind | Type of span (For example, server, internal). |
| | name | Name of the span, often a high-level title for the operation. |
| Scope and Instrumentation | | |
| | scope | Instrumentation scope, (For example., opentelemetry.instrumentation.django.) |
| Service Attributes | | |
| | service.name | Name of the service generating the trace, typically set as the app or service name. |
| Telemetry SDK Attributes | | |
| | telemetry.sdk.language | Programming language of the SDK used for telemetry, typically 'python' for Django. |
| | telemetry.sdk.name | Name of the telemetry SDK, for example., OpenTelemetry. |
| | telemetry.sdk.version | Version of the telemetry SDK used in the tracing setup. |
### List of imported libraries [#list-of-imported-libraries]
The `exporter.py` file and other relevant parts of the Django OpenTelemetry setup import the following libraries:
### `exporter.py` [#exporterpy]
This module creates and manages trace data in your app. It creates spans and tracers which track the execution flow and performance of your app.
```py
from opentelemetry import trace
```
TracerProvider acts as a container for the configuration of your app’s tracing behavior. It allows you to define how spans are generated and processed, essentially serving as the central point for managing trace creation and propagation in your app.
```py
from opentelemetry.sdk.trace import TracerProvider
```
BatchSpanProcessor is responsible for batching spans before they’re exported. This is an important aspect of efficient trace data management as it aggregates multiple spans into fewer network requests, reducing the overhead on your app’s performance and the tracing backend.
```py
from opentelemetry.sdk.trace.export import BatchSpanProcessor
```
The Resource class is used to describe your app’s service attributes, such as its name, version, and environment. This contextual information is attached to the traces and helps in identifying and categorizing trace data, making it easier to filter and analyze in your monitoring setup.
```py
from opentelemetry.sdk.resources import Resource, SERVICE_NAME
```
The OTLPSpanExporter is responsible for sending your app’s trace data to a backend that supports the OTLP such as Axiom. It formats the trace data according to the OTLP standards and transmits it over HTTP, ensuring compatibility and standardization in how telemetry data is sent across different systems and services.
```py
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
```
### `manage.py` [#managepy]
The DjangoInstrumentor module is used to automatically instrument Django applications. It integrates OpenTelemetry with Django, enabling automatic creation of spans for incoming HTTP requests handled by Django, and simplifying the process of adding telemetry to your app.
```py
from opentelemetry.instrumentation.django import DjangoInstrumentor
```
### `views.py` [#viewspy]
This import brings in the tracer instance defined in `exporter.py`, which is used to create spans for tracing the execution of Django views. By wrapping view logic within `tracer.start_as_current_span`, it captures detailed insights into the performance of individual request handlers.
```py
from .exporter import tracer
```
---
# OpenTelemetry using .NET
Source: https://axiom.co/docs/guides/opentelemetry-dotnet
OpenTelemetry provides a [unified approach to collecting telemetry data](https://opentelemetry.io/docs/languages/net/) from your .NET apps. This guide explains how to configure OpenTelemetry in a .NET app to send telemetry data to Axiom using the OpenTelemetry SDK.
* Install the .NET 6.0 SDK on your development machine.
* Use your existing .NET app or start with the sample provided in the `program.cs` below.
## Install dependencies [#install-dependencies]
Run the following command in your terminal to install the necessary NuGet packages:
```bash
dotnet add package OpenTelemetry --version 1.7.0
dotnet add package OpenTelemetry.Exporter.Console --version 1.7.0
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol --version 1.7.0
dotnet add package OpenTelemetry.Extensions.Hosting --version 1.7.0
dotnet add package OpenTelemetry.Instrumentation.AspNetCore --version 1.7.1
dotnet add package OpenTelemetry.Instrumentation.Http --version 1.6.0-rc.1
```
Replace the `dotnet.csproj` file in your project with the following:
```csharp
net6.0
enable
enable
```
The `dotnet.csproj` file is important for defining your project’s settings, including target framework, nullable reference types, and package references. It informs the .NET SDK and build tools about the components and configurations your project requires.
## Core app [#core-app]
`program.cs` is the core of the .NET app. It uses ASP.NET to create a simple web server. The server has an endpoint `/rolldice` that returns a random number, simulating a basic API.
```csharp
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Globalization;
// Set up the web app builder
var builder = WebApplication.CreateBuilder(args);
// Configure OpenTelemetry for detailed tracing information
TracingConfiguration.ConfigureOpenTelemetry();
var app = builder.Build();
// Map the GET request for '/rolldice/{player?}' to a handler
app.MapGet("/rolldice/{player?}", (ILogger logger, string? player) =>
{
// Start a manual tracing activity
using var activity = TracingConfiguration.StartActivity("HandleRollDice");
// Call the RollDice function to get a dice roll result
var result = RollDice();
if (activity != null)
{
// Add detailed information to the tracing activity for debugging and monitoring
activity.SetTag("player.name", player ?? "anonymous"); // Tag the player’s name, default to 'anonymous' if not provided
activity.SetTag("dice.rollResult", result); // Tag the result of the dice roll
activity.SetTag("operation.success", true); // Flag the operation as successful
activity.SetTag("custom.attribute", "Additional detail here"); // Add a custom attribute for potential further detail
}
// Log the dice roll event
LogRollDice(logger, player, result);
// Retur the dice roll result as a string
return result.ToString(CultureInfo.InvariantCulture);
});
// Start the web app
app.Run();
// Log function to log the result of a dice roll
void LogRollDice(ILogger logger, string? player, int result)
{
// Log message varies based on whether a player’s name is provided
if (string.IsNullOrEmpty(player))
{
// Log for an anonymous player
logger.LogInformation("Anonymous player is rolling the dice: {result}", result);
}
else
{
// Log for a named player
logger.LogInformation("{player} is rolling the dice: {result}", player, result);
}
}
// Function to roll a dice and return a random number between 1 and 6
int RollDice()
{
// Use the shared instance of Random for thread safety
return Random.Shared.Next(1, 7);
}
```
## Exporter [#exporter]
The `tracing.cs` file sets up the OpenTelemetry instrumentation. It configures the OTLP (OpenTelemetry Protocol) exporters for traces and initializes the ASP.NET SDK with automatic instrumentation capabilities.
```csharp
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using System;
using System.Diagnostics;
using System.Reflection;
// Class to configure OpenTelemetry tracing
public static class TracingConfiguration
{
// Declare an ActivitySource for creating tracing activities
private static readonly ActivitySource ActivitySource = new("MyCustomActivitySource");
// Configure OpenTelemetry with custom settings and instrumentation
public static void ConfigureOpenTelemetry()
{
// Retrieve the service name and version from the executing assembly metadata
var serviceName = Assembly.GetExecutingAssembly().GetName().Name ?? "UnknownService";
var serviceVersion = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "UnknownVersion";
// Set up the tracer provider with various configurations
Sdk.CreateTracerProviderBuilder()
.SetResourceBuilder(
// Set resource attributes including service name and version
ResourceBuilder.CreateDefault().AddService(serviceName, serviceVersion: serviceVersion)
.AddAttributes(new[] { new KeyValuePair("environment", "development") }) // Additional attributes
.AddTelemetrySdk() // Add telemetry SDK information to the traces
.AddEnvironmentVariableDetector()) // Detect resource attributes from environment variables
.AddSource(ActivitySource.Name) // Add the ActivitySource defined above
.AddAspNetCoreInstrumentation() // Add automatic instrumentation for ASP.NET Core
.AddHttpClientInstrumentation() // Add automatic instrumentation for HttpClient requests
.AddOtlpExporter(options => // Configure the OTLP exporter
{
options.Endpoint = new Uri("https://AXIOM_DOMAIN/v1/traces"); // Set the endpoint for the exporter
options.Protocol = OpenTelemetry.Exporter.OtlpExportProtocol.HttpProtobuf; // Set the protocol
options.Headers = "Authorization=Bearer API_TOKEN, X-Axiom-Dataset=DATASET_NAME"; // Update API token and dataset
})
.Build(); // Build the tracer provider
}
// Method to start a new tracing activity with an optional activity kind
public static Activity? StartActivity(string activityName, ActivityKind kind = ActivityKind.Internal)
{
// Starts and returns a new activity if sampling allows it, otherwise returns null
return ActivitySource.StartActivity(activityName, kind);
}
}
```
Replace the value of the `serviceName` variable with the name of the service you want to trace. This is used for identifying and categorizing trace data, particularly in systems with multiple services.
## Run the instrumented app [#run-the-instrumented-app]
1. Run in local development mode using the development settings in `appsettings.development.json`. Ensure your Axiom API token and dataset name are correctly set in `tracing.cs`.
2. Before deploying, run in production mode by switching to `appsettings.json` for production settings. Ensure your Axiom API token and dataset name are correctly set in `tracing.cs`.
3. Run your app with `dotnet run`. Your app starts and you can interact with it by sending requests to the `/rolldice` endpoint.
For example, if you are using port `8080`, your app is accessible locally at `http://localhost:8080/rolldice`. This URL will direct your requests to the `/rolldice` endpoint of your server running on your local machine.
## Observe the telemetry data [#observe-the-telemetry-data]
As you interact with your app, traces are collected and exported to Axiom where you can monitor and analyze your app’s performance and behavior.
1. Log into your Axiom account and click the **Datasets** or **Stream** tab.
2. Select your dataset from the list.
3. From the list of fields, click the **trace\_id**, to view your spans.
## Dynamic OpenTelemetry Traces dashboard [#dynamic-opentelemetry-traces-dashboard]
The data can then be further viewed and analyzed in the traces dashboard, providing insights into the performance and behavior of your app.
1. Log into your Axiom account, select **Dashboards**, and click the traces dashboard named after your dataset.
2. View the dashboard which displays your total traces, incoming spans, average span duration, errors, slowest operations, and top 10 span errors across services.
## Send data from an existing .NET project [#send-data-from-an-existing-net-project]
### Manual Instrumentation [#manual-instrumentation]
Manual instrumentation involves adding code to create, configure, and manage telemetry data, such as traces and spans, providing control over what data is collected.
1. Initialize ActivitySource. Define an `ActivitySource` to create activities (spans) for tracing specific operations within your app.
```csharp
private static readonly ActivitySource MyActivitySource = new ActivitySource("MyActivitySourceName");
```
2. Start and stop activities. Manually start activities (spans) at the beginning of the operations you want to trace and stop them when the operations complete. You can add custom attributes to these activities for more detailed tracing.
```csharp
using var activity = MyActivitySource.StartActivity("MyOperationName");
activity?.SetTag("key", "value");
// Perform the operation here
activity?.Stop();
```
3. Add custom attributes. Enhance activities with custom attributes to provide additional context, making it easier to analyze telemetry data.
```csharp
activity?.SetTag("UserId", userId);
activity?.SetTag("OperationDetail", "Detail about the operation");
```
### Automatic Instrumentation [#automatic-instrumentation]
Automatic instrumentation uses the OpenTelemetry SDK and additional libraries to automatically generate telemetry data for certain operations, such as incoming HTTP requests and database queries.
1. Configure OpenTelemetry SDK. Use the OpenTelemetry SDK to configure automatic instrumentation in your app. This typically involves setting up a `TracerProvider` in your `program.cs` or startup configuration, which automatically captures telemetry data from supported libraries.
```csharp
Sdk.CreateTracerProviderBuilder()
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddOtlpExporter(options =>
{
options.Endpoint = new Uri("https://AXIOM_DOMAIN/v1/traces");
options.Headers = $"Authorization=Bearer API_TOKEN, X-Axiom-Dataset=DATASET_NAME";
})
.Build();
```
2. Install and configure additional OpenTelemetry instrumentation packages as needed, based on the technologies your app uses. For example, to automatically trace SQL database queries, you might add the corresponding database instrumentation package.
3. With automatic instrumentation set up, no further code changes are required for tracing basic operations. The OpenTelemetry SDK and its instrumentation packages handle the creation and management of traces for supported operations.
## Reference [#reference]
### List of OpenTelemetry trace fields [#list-of-opentelemetry-trace-fields]
| Field Category | Field Name | Description |
| ----------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------- |
| **General Trace Information** | | |
| | \_rowId | Unique identifier for each row in the trace data. |
| | \_sysTime | System timestamp when the trace data was recorded. |
| | \_time | Timestamp when the actual event being traced occurred. |
| | trace\_id | Unique identifier for the entire trace. |
| | span\_id | Unique identifier for the span within the trace. |
| | parent\_span\_id | Unique identifier for the parent span within the trace. |
| **HTTP Attributes** | | |
| | attributes.http.request.method | HTTP method used for the request. |
| | attributes.http.response.status\_code | HTTP status code returned in response. |
| | attributes.http.route | Route accessed during the HTTP request. |
| | attributes.url.path | Path component of the URL accessed. |
| | attributes.url.scheme | Scheme component of the URL accessed. |
| | attributes.server.address | Address of the server handling the request. |
| | attributes.server.port | Port number on the server handling the request. |
| **Network Attributes** | | |
| | attributes.network.protocol.version | Version of the network protocol used. |
| **User Agent** | | |
| | attributes.user\_agent.original | Original user agent string, providing client software and OS. |
| **Custom Attributes** | | |
| | attributes.custom\["custom.attribute"] | Custom attribute provided in the trace. |
| | attributes.custom\["dice.rollResult"] | Result of a dice roll operation. |
| | attributes.custom\["operation.success"] | Indicates if the operation was successful. |
| | attributes.custom\["player.name"] | Name of the player in the operation. |
| **Operational Details** | | |
| | duration | Time taken for the operation. |
| | kind | Type of span (for example, server, client, internal). |
| | name | Name of the span. |
| **Resource Attributes** | | |
| | resource.custom.environment | Environment where the trace was captured, for example, development. |
| **Telemetry SDK Attributes** | | |
| | telemetry.sdk.language | Language of the telemetry SDK, for example, dotnet. |
| | telemetry.sdk.name | Name of the telemetry SDK, for example, opentelemetry. |
| | telemetry.sdk.version | Version of the telemetry SDK, for example, 1.7.0. |
| **Service Attributes** | | |
| | service.instance.id | Unique identifier for the instance of the service. |
| | service.name | Name of the service generating the trace, for example, dotnet. |
| | service.version | Version of the service generating the trace, for example, 1.0.0.0. |
| **Scope Attributes** | | |
| | scope.name | Name of the scope for the operation, for example, `OpenTelemetry.Instrumentation.AspNetCore`. |
| | scope.version | Version of the scope, for example, 1.0.0.0. |
### List of imported libraries [#list-of-imported-libraries]
### OpenTelemetry [#opentelemetry]
` `
This is the core SDK for OpenTelemetry in .NET. It provides the foundational tools needed to collect and manage telemetry data within your .NET apps. It’s the base upon which all other OpenTelemetry instrumentation and exporter packages build.
### `OpenTelemetry.Exporter.Console` [#opentelemetryexporterconsole]
` `
This package allows apps to export telemetry data to the console. It’s primarily useful for development and testing purposes, offering a simple way to view the telemetry data your app generates in real time.
### `OpenTelemetry.Exporter.OpenTelemetryProtocol` [#opentelemetryexporteropentelemetryprotocol]
` `
This package enables your app to export telemetry data using the OpenTelemetry Protocol (OTLP) over gRPC or HTTP. It’s vital for sending data to observability platforms that support OTLP, ensuring your telemetry data can be easily analyzed and monitored across different systems.
### `OpenTelemetry.Extensions.Hosting` [#opentelemetryextensionshosting]
` `
Designed for .NET apps, this package integrates OpenTelemetry with the .NET Generic Host. It simplifies the process of configuring and managing the lifecycle of OpenTelemetry resources such as TracerProvider, making it easier to collect telemetry data in apps that use the hosting model.
### `OpenTelemetry.Instrumentation.AspNetCore` [#opentelemetryinstrumentationaspnetcore]
` `
This package is designed for instrumenting ASP.NET Core apps. It automatically collects telemetry data about incoming requests and responses. This is important for monitoring the performance and reliability of web apps and APIs built with ASP.NET Core.
### `OpenTelemetry.Instrumentation.Http` [#opentelemetryinstrumentationhttp]
` `
This package provides automatic instrumentation for HTTP clients in .NET apps. It captures telemetry data about outbound HTTP requests, including details such as request and response headers, duration, success status, and more. It’s key for understanding external dependencies and interactions in your app.
---
# OpenTelemetry using Golang
Source: https://axiom.co/docs/guides/opentelemetry-go
OpenTelemetry offers a [single set of APIs and libraries](https://opentelemetry.io/docs/languages/go/instrumentation/) that standardize how you collect and transfer telemetry data. This guide focuses on setting up OpenTelemetry in a Go app to send traces to Axiom.
## Prerequisites [#prerequisites]
* Go 1.19 or higher: Ensure you have Go version 1.19 or higher installed in your environment.
* Go app: Use your own app written in Go or start with the provided `main.go` sample below.
* [Create an Axiom account](https://app.axiom.co/).
* [Create a dataset in Axiom](/reference/datasets) where you send your data.
* [Create an API token in Axiom](/reference/tokens) with permissions to create, read, update, and delete datasets.
## Installing Dependencies [#installing-dependencies]
First, run the following in your terminal to install the necessary Go packages:
```go
go get go.opentelemetry.io/otel
go get go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp
go get go.opentelemetry.io/otel/sdk/resource
go get go.opentelemetry.io/otel/sdk/trace
go get go.opentelemetry.io/otel/semconv/v1.24.0
go get go.opentelemetry.io/otel/trace
go get go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp
go get go.opentelemetry.io/otel/propagation
```
This installs the OpenTelemetry Go SDK, the OTLP (OpenTelemetry Protocol) trace exporter, and other necessary packages for instrumentation and resource definition.
## Initializing a Go module and managing dependencies [#initializing-a-go-module-and-managing-dependencies]
Before installing the OpenTelemetry dependencies, ensure your Go project is properly initialized as a module and all dependencies are correctly managed. This step is important for resolving import issues and managing your project’s dependencies effectively.
### Initialize a Go module [#initialize-a-go-module]
If your project isn’t already initialized as a Go module, run the following command in your project’s root directory. This step creates a `go.mod` file which tracks your project’s dependencies.
```bash
go mod init
```
Replace `` with your project’s name or the GitHub repository path if you plan to push the code to GitHub. For example, `go mod init github.com/yourusername/yourprojectname`.
### Manage dependencies [#manage-dependencies]
After initializing your Go module, tidy up your project’s dependencies. This ensures that your `go.mod` file accurately reflects the packages your project depends on, including the correct versions of the OpenTelemetry libraries you’ll be using.
Run the following command in your project’s root directory:
```bash
go mod tidy
```
This command will download the necessary dependencies and update your `go.mod` and `go.sum` files accordingly. It’s a good practice to run `go mod tidy` after adding new imports to your project or periodically to keep dependencies up to date.
## HTTP server configuration (main.go) [#http-server-configuration-maingo]
`main.go` is the entry point of the app. It invokes `InstallExportPipeline` from `exporter.go` to set up the tracing exporter. It also sets up a basic HTTP server with OpenTelemetry instrumentation to demonstrate how telemetry data can be collected and exported in a simple web app context. It also demonstrates the usage of span links to establish relationships between spans across different traces.
```go
// main.go
package main
import (
"context"
"fmt"
"log"
"math/rand"
"net"
"net/http"
"os"
"os/signal"
"time"
// OpenTelemetry imports for tracing and observability.
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
)
// main function starts the application and handles run function errors.
func main() {
if err := run(); err != nil {
log.Fatalln(err)
}
}
// run sets up signal handling, tracer initialization, and starts an HTTP server.
func run() error {
// Creating a context that listens for the interrupt signal from the OS.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
// Initializes tracing and returns a function to shut down OpenTelemetry cleanly.
otelShutdown, err := SetupTracer()
if err != nil {
return err
}
defer func() {
if shutdownErr := otelShutdown(ctx); shutdownErr != nil {
log.Printf("failed to shutdown OpenTelemetry: %v", shutdownErr) // Log fatal errors during server shutdown
}
}()
// Configuring the HTTP server settings.
srv := &http.Server{
Addr: ":8080", // Server address
BaseContext: func(_ net.Listener) context.Context { return ctx },
ReadTimeout: 5 * time.Second, // Server read timeout
WriteTimeout: 15 * time.Second, // Server write timeout
Handler: newHTTPHandler(), // HTTP handler
}
// Starting the HTTP server in a new goroutine.
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("HTTP server ListenAndServe: %v", err)
}
}()
// Wait for interrupt signal to gracefully shut down the server with a timeout context.
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel() // Ensures cancel function is called on exit
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Fatalf("HTTP server Shutdown: %v", err) // Log fatal errors during server shutdown
}
return nil
}
// newHTTPHandler configures the HTTP routes and integrates OpenTelemetry.
func newHTTPHandler() http.Handler {
mux := http.NewServeMux() // HTTP request multiplexer
// Wrapping the handler function with OpenTelemetry instrumentation.
handleFunc := func(pattern string, handlerFunc func(http.ResponseWriter, *http.Request)) {
handler := otelhttp.WithRouteTag(pattern, http.HandlerFunc(handlerFunc))
mux.Handle(pattern, handler) // Associate pattern with handler
}
// Registering route handlers with OpenTelemetry instrumentation
handleFunc("/rolldice", rolldice)
handleFunc("/roll_with_link", rollWithLink)
handler := otelhttp.NewHandler(mux, "/")
return handler
}
// rolldice handles the /rolldice route by generating a random dice roll.
func rolldice(w http.ResponseWriter, r *http.Request) {
_, span := otel.Tracer("example-tracer").Start(r.Context(), "rolldice")
defer span.End()
// Generating a random dice roll.
randGen := rand.New(rand.NewSource(time.Now().UnixNano()))
roll := 1 + randGen.Intn(6)
// Writing the dice roll to the response.
fmt.Fprintf(w, "Rolled a dice: %d\n", roll)
}
// rollWithLink handles the /roll_with_link route by creating a new span with a link to the parent span.
func rollWithLink(w http.ResponseWriter, r *http.Request) {
ctx, span := otel.Tracer("example-tracer").Start(r.Context(), "roll_with_link")
defer span.End()
/**
* Create a new span for rolldice with a link to the parent span.
* This link helps correlate events that are related but not directly a parent-child relationship.
*/
rollDiceCtx, rollDiceSpan := otel.Tracer("example-tracer").Start(ctx, "rolldice",
trace.WithLinks(trace.Link{
SpanContext: span.SpanContext(),
Attributes: nil,
}),
)
defer rollDiceSpan.End()
// Generating a random dice roll linked to the parent context.
randGen := rand.New(rand.NewSource(time.Now().UnixNano()))
roll := 1 + randGen.Intn(6)
// Writing the linked dice roll to the response.
fmt.Fprintf(w, "Dice roll result (with link): %d\n", roll)
// Use the rollDiceCtx if needed.
_ = rollDiceCtx
}
```
## Exporter configuration (exporter.go) [#exporter-configuration-exportergo]
`exporter.go` is responsible for setting up the OpenTelemetry tracing exporter. It defines the `resource attributes`, `initializes` the `tracer`, and configures the OTLP (OpenTelemetry Protocol) exporter with appropriate endpoints and headers, allowing your app to send telemetry data to Axiom.
```go
package main
import (
"context" // For managing request-scoped values, cancellation signals, and deadlines.
"crypto/tls" // For configuring TLS options, like certificates.
// OpenTelemetry imports for setting up tracing and exporting telemetry data.
"go.opentelemetry.io/otel" // Core OpenTelemetry APIs for managing tracers.
"go.opentelemetry.io/otel/attribute" // For creating and managing trace attributes.
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" // HTTP trace exporter for OpenTelemetry Protocol (OTLP).
"go.opentelemetry.io/otel/propagation" // For managing context propagation formats.
"go.opentelemetry.io/otel/sdk/resource" // For defining resources that describe an entity producing telemetry.
"go.opentelemetry.io/otel/sdk/trace" // For configuring tracing, like sampling and processors.
semconv "go.opentelemetry.io/otel/semconv/v1.24.0" // Semantic conventions for resource attributes.
)
const (
serviceName = "axiom-go-otel" // Name of the service for tracing.
serviceVersion = "0.1.0" // Version of the service.
otlpEndpoint = "AXIOM_DOMAIN" // OTLP collector endpoint.
bearerToken = "Bearer API_TOKEN" // Authorization token.
deploymentEnvironment = "production" // Deployment environment.
)
func SetupTracer() (func(context.Context) error, error) {
ctx := context.Background()
return InstallExportPipeline(ctx) // Setup and return the export pipeline for telemetry data.
}
func Resource() *resource.Resource {
// Defines resource with service name, version, and environment.
return resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceNameKey.String(serviceName),
semconv.ServiceVersionKey.String(serviceVersion),
attribute.String("environment", deploymentEnvironment),
)
}
func InstallExportPipeline(ctx context.Context) (func(context.Context) error, error) {
// Sets up OTLP HTTP exporter with endpoint, headers, and TLS config.
exporter, err := otlptracehttp.New(ctx,
otlptracehttp.WithEndpoint(otlpEndpoint),
otlptracehttp.WithHeaders(map[string]string{
"Authorization": bearerToken,
"X-AXIOM-DATASET": "DATASET_NAME",
}),
otlptracehttp.WithTLSClientConfig(&tls.Config{}),
)
if err != nil {
return nil, err
}
// Configures the tracer provider with the exporter and resource.
tracerProvider := trace.NewTracerProvider(
trace.WithBatcher(exporter),
trace.WithResource(Resource()),
)
otel.SetTracerProvider(tracerProvider)
// Sets global propagator to W3C Trace Context and Baggage.
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{},
propagation.Baggage{},
))
return tracerProvider.Shutdown, nil // Returns a function to shut down the tracer provider.
}
```
## Run the app [#run-the-app]
To run the app, execute both `exporter.go` and `main.go`. Use the command `go run main.go exporter.go` to start the app. Once your app is running, traces collected by your app are exported to Axiom. The server starts on the specified port, and you can interact with it by sending requests to the `/rolldice` endpoint.
For example, if you are using port `8080`, your app will be accessible locally at `http://localhost:8080/rolldice`. This URL will direct your requests to the `/rolldice` endpoint of your server running on your local machine.
## Observe the telemetry data in Axiom [#observe-the-telemetry-data-in-axiom]
After deploying your app, you can log into your Axiom account to view and analyze the telemetry data. As you interact with your app, traces will be collected and exported to Axiom, where you can monitor and analyze your app’s performance and behavior.
## Dynamic OpenTelemetry traces dashboard [#dynamic-opentelemetry-traces-dashboard]
This data can then be further viewed and analyzed in Axiom’s dashboard, providing insights into the performance and behavior of your app.
## Send data from an existing Golang project [#send-data-from-an-existing-golang-project]
### Manual Instrumentation [#manual-instrumentation]
Manual instrumentation in Go involves managing spans within your code to track operations and events. This method offers precise control over what is instrumented and how spans are configured.
1. Initialize the tracer:
Use the OpenTelemetry API to obtain a tracer instance. This tracer will be used to start and manage spans.
```go
tracer := otel.Tracer("serviceName")
```
2. Create and manage spans:
Manually start spans before the operations you want to trace and ensure they're ended after the operations complete.
```go
ctx, span := tracer.Start(context.Background(), "operationName")
defer span.End()
// Perform the operation here
```
3. Annotate spans:
Enhance spans with additional information using attributes or events to provide more context about the traced operation.
```go
span.SetAttributes(attribute.String("key", "value"))
span.AddEvent("eventName", trace.WithAttributes(attribute.String("key", "value")))
```
### Automatic Instrumentation [#automatic-instrumentation]
Automatic instrumentation in Go uses libraries and integrations that automatically create spans for operations, simplifying the addition of observability to your app.
1. Instrumentation libraries:
Use `OpenTelemetry-contrib` libraries designed for automatic instrumentation of standard Go frameworks and libraries, such as `net/http`.
```go
import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
```
2. Wrap handlers and clients:
Automatically instrument HTTP servers and clients by wrapping them with OpenTelemetry’s instrumentation. For HTTP servers, wrap your handlers with `otelhttp.NewHandler`.
```go
http.Handle("/path", otelhttp.NewHandler(handler, "operationName"))
```
3. Minimal code changes:
After setting up automatic instrumentation, no further changes are required for tracing standard operations. The instrumentation takes care of starting, managing, and ending spans.
## Reference [#reference]
### List of OpenTelemetry trace fields [#list-of-opentelemetry-trace-fields]
| Field Category | Field Name | Description |
| ---------------------------- | --------------------------------------- | ------------------------------------------------------------------- |
| **Unique Identifiers** | | |
| | \_rowid | Unique identifier for each row in the trace data. |
| | span\_id | Unique identifier for the span within the trace. |
| | trace\_id | Unique identifier for the entire trace. |
| **Timestamps** | | |
| | \_systime | System timestamp when the trace data was recorded. |
| | \_time | Timestamp when the actual event being traced occurred. |
| **HTTP Attributes** | | |
| | attributes.custom\["http.host"] | Host information where the HTTP request was sent. |
| | attributes.custom\["http.server\_name"] | Server name for the HTTP request. |
| | attributes.http.flavor | HTTP protocol version used. |
| | attributes.http.method | HTTP method used for the request. |
| | attributes.http.route | Route accessed during the HTTP request. |
| | attributes.http.scheme | Protocol scheme (HTTP/HTTPS). |
| | attributes.http.status\_code | HTTP response status code. |
| | attributes.http.target | Specific target of the HTTP request. |
| | attributes.http.user\_agent | User agent string of the client. |
| | attributes.custom.user\_agent.original | Original user agent string, providing client software and OS. |
| **Network Attributes** | | |
| | attributes.net.host.port | Port number on the host receiving the request. |
| | attributes.net.peer.port | Port number on the peer (client) side. |
| | attributes.custom\["net.peer.ip"] | IP address of the peer in the network interaction. |
| | attributes.net.sock.peer.addr | Socket peer address, indicating the IP version used. |
| | attributes.net.sock.peer.port | Socket peer port number. |
| | attributes.custom.net.protocol.version | Protocol version used in the network interaction. |
| **Operational Details** | | |
| | duration | Time taken for the operation. |
| | kind | Type of span (for example,, server, client). |
| | name | Name of the span. |
| | scope | Instrumentation scope. |
| | service.name | Name of the service generating the trace. |
| | service.version | Version of the service generating the trace. |
| **Resource Attributes** | | |
| | resource.environment | Environment where the trace was captured, for example,, production. |
| | attributes.custom.http.wrote\_bytes | Number of bytes written in the HTTP response. |
| **Telemetry SDK Attributes** | | |
| | telemetry.sdk.language | Language of the telemetry SDK (if previously not included). |
| | telemetry.sdk.name | Name of the telemetry SDK (if previously not included). |
| | telemetry.sdk.version | Version of the telemetry SDK (if previously not included). |
### List of imported libraries [#list-of-imported-libraries]
### OpenTelemetry Go SDK [#opentelemetry-go-sdk]
**`go.opentelemetry.io/otel`**
This is the core SDK for OpenTelemetry in Go. It provides the necessary tools to create and manage telemetry data (traces, metrics, and logs).
### OTLP Trace Exporter [#otlp-trace-exporter]
**`go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp`**
This package allows your app to export telemetry data over HTTP using the OpenTelemetry Protocol (OTLP). It’s important for sending data to Axiom or any other backend that supports OTLP.
### Resource and Trace Packages [#resource-and-trace-packages]
**`go.opentelemetry.io/otel/sdk/resource`** and **`go.opentelemetry.io/otel/sdk/trace`**
These packages help define the properties of your telemetry data, such as service name and version, and manage trace data within your app.
### Semantic Conventions [#semantic-conventions]
**`go.opentelemetry.io/otel/semconv/v1.24.0`**
This package provides standardized schema URLs and attributes, ensuring consistency across different OpenTelemetry implementations.
### Tracing API [#tracing-api]
**`go.opentelemetry.io/otel/trace`**
This package offers the API for tracing. It enables you to create spans, record events, and manage context propagation in your app.
### HTTP Instrumentation [#http-instrumentation]
**`go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp`**
Used for instrumenting HTTP clients and servers. It automatically records data about HTTP requests and responses, which is essential for web apps.
### Propagators [#propagators]
**`go.opentelemetry.io/otel/propagation`**
This package provides the ability to propagate context and trace information across service boundaries.
---
# Send data from Java app using OpenTelemetry
Source: https://axiom.co/docs/guides/opentelemetry-java
OpenTelemetry provides a unified approach to collecting telemetry data from your Java applications. This page demonstrates how to configure OpenTelemetry in a Java app to send telemetry data to Axiom using the OpenTelemetry SDK.
* [Install JDK 11](https://www.oracle.com/java/technologies/java-se-glance.html) or later
* [Install Maven](https://maven.apache.org/download.cgi)
* Use your own app written in Java or the provided `DiceRollerApp.java` sample.
## Create project [#create-project]
To create a Java project, run the Maven archetype command in the terminal:
```bash
mvn archetype:generate -DgroupId=com.example -DartifactId=MyProject -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
```
This command creates a new project in a directory named `MyProject` with a standard directory structure.
## Create core app [#create-core-app]
`DiceRollerApp.java` is the core of the sample app. It simulates rolling a dice and demonstrates the usage of OpenTelemetry for tracing. The app includes two methods: one for a simple dice roll and another that demonstrates the usage of span links to establish relationships between spans across different traces.
Create the `DiceRollerApp.java` in the `src/main/java/com/example` directory with the following content:
```java
package com.example;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import java.util.Random;
public class DiceRollerApp {
private static final Tracer tracer;
static {
OpenTelemetry openTelemetry = OtelConfiguration.initializeOpenTelemetry();
tracer = openTelemetry.getTracer(DiceRollerApp.class.getName());
}
public static void main(String[] args) {
rollDice();
rollDiceWithLink();
}
private static void rollDice() {
Span span = tracer.spanBuilder("rollDice").startSpan();
try (Scope scope = span.makeCurrent()) {
int roll = 1 + new Random().nextInt(6);
System.out.println("Rolled a dice: " + roll);
} finally {
span.end();
}
}
private static void rollDiceWithLink() {
Span parentSpan = tracer.spanBuilder("rollWithLink").startSpan();
try (Scope parentScope = parentSpan.makeCurrent()) {
Span childSpan = tracer.spanBuilder("rolldice")
.addLink(parentSpan.getSpanContext())
.startSpan();
try (Scope childScope = childSpan.makeCurrent()) {
int roll = 1 + new Random().nextInt(6);
System.out.println("Dice roll result (with link): " + roll);
} finally {
childSpan.end();
}
} finally {
parentSpan.end();
}
}
}
```
## Configure OpenTelemetry [#configure-opentelemetry]
`OtelConfiguration.java` sets up the OpenTelemetry SDK and configures the exporter to send data to Axiom. It initializes the tracer provider, sets up the Axiom exporter, and configures the resource attributes.
Create the `OtelConfiguration.java` file in the `src/main/java/com/example` directory with the following content:
```java
package com.example;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import java.util.concurrent.TimeUnit;
public class OtelConfiguration {
private static final String SERVICE_NAME = "YOUR_SERVICE_NAME";
private static final String SERVICE_VERSION = "YOUR_SERVICE_VERSION";
private static final String OTLP_ENDPOINT = "https://AXIOM_DOMAIN/v1/traces";
private static final String BEARER_TOKEN = "Bearer API_TOKEN";
private static final String AXIOM_DATASET = "DATASET_NAME";
public static OpenTelemetry initializeOpenTelemetry() {
Resource resource = Resource.getDefault()
.merge(Resource.create(Attributes.of(
AttributeKey.stringKey("service.name"), SERVICE_NAME,
AttributeKey.stringKey("service.version"), SERVICE_VERSION
)));
OtlpHttpSpanExporter spanExporter = OtlpHttpSpanExporter.builder()
.setEndpoint(OTLP_ENDPOINT)
.addHeader("Authorization", BEARER_TOKEN)
.addHeader("X-Axiom-Dataset", AXIOM_DATASET)
.build();
SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder()
.addSpanProcessor(BatchSpanProcessor.builder(spanExporter)
.setScheduleDelay(100, TimeUnit.MILLISECONDS)
.build())
.setResource(resource)
.build();
OpenTelemetrySdk openTelemetry = OpenTelemetrySdk.builder()
.setTracerProvider(sdkTracerProvider)
.buildAndRegisterGlobal();
Runtime.getRuntime().addShutdownHook(new Thread(sdkTracerProvider::close));
return openTelemetry;
}
}
```
## Configure project [#configure-project]
The `pom.xml` file defines the project structure and dependencies for Maven. It includes the necessary OpenTelemetry libraries and configures the build process.
Update the `pom.xml` file in the root of your project directory with the following content:
```xml
4.0.0
com.example
axiom-otel-java
1.0-SNAPSHOT
UTF-8
11
11
1.18.0
io.opentelemetry
opentelemetry-api
${opentelemetry.version}
io.opentelemetry
opentelemetry-sdk
${opentelemetry.version}
io.opentelemetry
opentelemetry-exporter-otlp
${opentelemetry.version}
junit
junit
4.13.2
test
org.apache.maven.plugins
maven-compiler-plugin
3.8.1
11
11
org.apache.maven.plugins
maven-surefire-plugin
3.0.0-M5
true
org.apache.maven.plugins
maven-shade-plugin
3.2.4
package
shade
com.example.DiceRollerApp
```
## Run the instrumented app [#run-the-instrumented-app]
To run your Java app with OpenTelemetry instrumentation, follow these steps:
1. Clean the project and download dependencies:
```bash
mvn clean
```
2. Compile the code:
```bash
mvn compile
```
3. Package the app:
```bash
mvn package
```
4. Run the app:
```bash
java -jar target/axiom-otel-java-1.0-SNAPSHOT.jar
```
The app executes the `rollDice()` and `rollDiceWithLink()` methods, generates telemetry data, and sends the data to Axiom.
## Observe telemetry data in Axiom [#observe-telemetry-data-in-axiom]
As the app runs, it sends traces to Axiom. To view the traces:
1. In Axiom, click the **Stream** tab.
2. Click your dataset.
Axiom provides a dynamic dashboard for visualizing and analyzing your OpenTelemetry traces. This dashboard offers insights into the performance and behavior of your app. To view the dashboard:
1. In Axiom, click the **Dashboards** tab.
2. Look for the OpenTelemetry traces dashboard or create a new one.
3. Customize the dashboard to show the event data and visualizations most relevant to the app.
## Send data from an existing Java project [#send-data-from-an-existing-java-project]
### Manual instrumentation [#manual-instrumentation]
Manual instrumentation gives fine-grained control over which parts of the app are traced and what information is included in the traces. It requires adding OpenTelemetry-specific code to the app.
Set up OpenTelemetry. Create a configuration class to initialize OpenTelemetry with necessary settings, exporters, and span processors.
```java
// OtelConfiguration.java
package com.example;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
public class OtelConfiguration {
public static OpenTelemetry initializeOpenTelemetry() {
OtlpHttpSpanExporter spanExporter = OtlpHttpSpanExporter.builder()
.setEndpoint("https://AXIOM_DOMAIN/v1/traces")
.addHeader("Authorization", "Bearer API_TOKEN")
.addHeader("X-Axiom-Dataset", "DATASET_NAME")
.build();
SdkTracerProvider tracerProvider = SdkTracerProvider.builder()
.addSpanProcessor(BatchSpanProcessor.builder(spanExporter).build())
.build();
return OpenTelemetrySdk.builder()
.setTracerProvider(tracerProvider)
.buildAndRegisterGlobal();
}
}
```
Spans represent units of work in the app. They have a start time and duration and can be nested.
```java
// DiceRollerApp.java
package com.example;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
public class DiceRollerApp {
private static final Tracer tracer;
static {
OpenTelemetry openTelemetry = OtelConfiguration.initializeOpenTelemetry();
tracer = openTelemetry.getTracer("com.example.DiceRollerApp");
}
public static void main(String[] args) {
try (Scope scope = tracer.spanBuilder("Main").startScopedSpan()) {
rollDice();
}
}
private static void rollDice() {
Span span = tracer.spanBuilder("rollDice").startSpan();
try (Scope scope = span.makeCurrent()) {
// Simulate dice roll
int result = new Random().nextInt(6) + 1;
System.out.println("Rolled a dice: " + result);
} finally {
span.end();
}
}
}
```
Custom spans are manually managed to provide detailed insights into specific functions or methods within the app.
Spans can be annotated with attributes and events to provide more context about the operation being performed.
```java
private static void rollDice() {
Span span = tracer.spanBuilder("rollDice").startSpan();
try (Scope scope = span.makeCurrent()) {
int roll = 1 + new Random().nextInt(6);
span.setAttribute("roll.value", roll);
span.addEvent("Dice rolled");
System.out.println("Rolled a dice: " + roll);
} finally {
span.end();
}
}
```
Span links allow association of spans that aren’t in a parent-child relationship.
```java
private static void rollDiceWithLink() {
Span parentSpan = tracer.spanBuilder("rollWithLink").startSpan();
try (Scope parentScope = parentSpan.makeCurrent()) {
Span childSpan = tracer.spanBuilder("rolldice")
.addLink(parentSpan.getSpanContext())
.startSpan();
try (Scope childScope = childSpan.makeCurrent()) {
int roll = 1 + new Random().nextInt(6);
System.out.println("Dice roll result (with link): " + roll);
} finally {
childSpan.end();
}
} finally {
parentSpan.end();
}
}
```
### Automatic instrumentation [#automatic-instrumentation]
Automatic instrumentation simplifies adding telemetry to a Java app by automatically capturing data from supported libraries and frameworks.
Ensure all necessary OpenTelemetry libraries are included in your Maven `pom.xml`.
```xml
io.opentelemetry
opentelemetry-api
{opentelemetry_version}
io.opentelemetry
opentelemetry-sdk
{opentelemetry_version}
io.opentelemetry.instrumentation
opentelemetry-instrumentation-httpclient
{instrumentation_version}
```
Dependencies include the OpenTelemetry SDK and instrumentation libraries that automatically capture data from common Java libraries.
Implement an initialization class to configure the OpenTelemetry SDK along with auto-instrumentation for frameworks used by the app.
```java
// AutoInstrumentationSetup.java
package com.example;
import io.opentelemetry.instrumentation.httpclient.HttpClientInstrumentation;
import io.opentelemetry.api.OpenTelemetry;
public class AutoInstrumentationSetup {
public static void setup() {
OpenTelemetry openTelemetry = OtelConfiguration.initializeOpenTelemetry();
HttpClientInstrumentation.instrument(openTelemetry);
}
}
```
Auto-instrumentation is initialized early in the app lifecycle to ensure all relevant activities are automatically captured.
```java
// Main.java
package com.example;
public class Main {
public static void main(String[] args) {
AutoInstrumentationSetup.setup(); // Initialize OpenTelemetry auto-instrumentation
DiceRollerApp.main(args); // Start the application logic
}
}
```
## Reference [#reference]
### List of OpenTelemetry trace fields [#list-of-opentelemetry-trace-fields]
| Field category | Field name | Description |
| ------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------- |
| General trace information | | |
| | \_rowId | Unique identifier for each row in the trace data. |
| | \_sysTime | System timestamp when the trace data was recorded. |
| | \_time | Timestamp when the actual event being traced occurred. |
| | trace\_id | Unique identifier for the entire trace. |
| | span\_id | Unique identifier for the span within the trace. |
| | parent\_span\_id | Unique identifier for the parent span within the trace. |
| Operational details | | |
| | duration | Time taken for the operation, typically in microseconds or milliseconds. |
| | kind | Type of span. For example, `server`, `internal`. |
| | name | Name of the span, often a high-level title for the operation. |
| Scope and instrumentation | | |
| | scope.name | Instrumentation scope, typically the Java package or app component. For example, `com.example.DiceRollerApp`. |
| Service attributes | | |
| | service.name | Name of the service generating the trace. For example, `axiom-java-otel`. |
| | service.version | Version of the service generating the trace. For example, `0.1.0`. |
| Telemetry SDK attributes | | |
| | telemetry.sdk.language | Programming language of the SDK used for telemetry, typically `java`. |
| | telemetry.sdk.name | Name of the telemetry SDK. For example, `opentelemetry`. |
| | telemetry.sdk.version | Version of the telemetry SDK used in the tracing setup. For example, `1.18.0`. |
### List of imported libraries [#list-of-imported-libraries]
The Java implementation of OpenTelemetry uses the following key libraries.
`io.opentelemetry:opentelemetry-api`
This package provides the core OpenTelemetry API for Java. It defines the interfaces and classes that developers use to instrument their apps manually. This includes the `Tracer`, `Span`, and `Context` classes, which are fundamental to creating and managing traces in your app. The API is designed to be stable and consistent, allowing developers to instrument their code without tying it to a specific implementation.
`io.opentelemetry:opentelemetry-sdk`
The opentelemetry-sdk package is the reference implementation of the OpenTelemetry API for Java. It provides the actual capability behind the API interfaces, including span creation, context propagation, and resource management. This SDK is highly configurable and extensible, allowing developers to customize how telemetry data is collected, processed, and exported. It’s the core component that brings OpenTelemetry to life in a Java app.
`io.opentelemetry:opentelemetry-exporter-otlp`
This package provides an exporter that sends telemetry data using the OpenTelemetry Protocol (OTLP). OTLP is the standard protocol for transmitting telemetry data in the OpenTelemetry ecosystem. This exporter allows Java applications to send their collected traces, metrics, and logs to any backend that supports OTLP, such as Axiom. The use of OTLP ensures broad compatibility and a standardized way of transmitting telemetry data across different systems and platforms.
`io.opentelemetry:opentelemetry-sdk-extension-autoconfigure`
This extension package provides auto-configuration capabilities for the OpenTelemetry SDK. It allows developers to configure the SDK using environment variables or system properties, making it easier to set up and deploy OpenTelemetry-instrumented applications in different environments. This is particularly useful for containerized applications or those running in cloud environments where configuration through environment variables is common.
`io.opentelemetry:opentelemetry-sdk-trace`
This package is part of the OpenTelemetry SDK and focuses specifically on tracing capability. It includes important classes like `SdkTracerProvider` and `BatchSpanProcessor`. The `SdkTracerProvider` is responsible for creating and managing tracers, while the `BatchSpanProcessor` efficiently processes and exports spans in batches, similar to its Node.js counterpart. This batching mechanism helps optimize the performance of trace data export in OpenTelemetry-instrumented Java applications.
`io.opentelemetry:opentelemetry-sdk-common`
This package provides common capability used across different parts of the OpenTelemetry SDK. It includes utilities for working with attributes, resources, and other shared concepts in OpenTelemetry. This package helps ensure consistency across the SDK and simplifies the implementation of cross-cutting concerns in telemetry data collection and processing.
---
# OpenTelemetry using Next.js
Source: https://axiom.co/docs/guides/opentelemetry-nextjs
OpenTelemetry provides a standardized way to collect and export telemetry data from your Next.js apps. This guide walks you through the process of configuring OpenTelemetry in a Next.js app to send traces to Axiom using the OpenTelemetry SDK.
## Prerequisites [#prerequisites]
* [Create an Axiom account](https://app.axiom.co/).
* [Create a dataset in Axiom](/reference/datasets) where you send your data.
* [Create an API token in Axiom](/reference/tokens) with permissions to create, read, update, and delete datasets.
* [Install Node.js version 14](https://nodejs.org/en/download/package-manager) or newer.
* An existing Next.js app. Alternatively, create a new app with the default settings using the [Next.js documentation](https://nextjs.org/learn/pages-router/create-nextjs-app-setup).
## Send data from new project [#send-data-from-new-project]
### Initial setup [#initial-setup]
1. Create a new app with the default settings using the [Next.js documentation](https://nextjs.org/learn/pages-router/create-nextjs-app-setup).
2. Run the following command to install the dependencies:
```bash
npm install @opentelemetry/exporter-trace-otlp-http @opentelemetry/sdk-trace-node @opentelemetry/resources
```
3. Create an `instrumentation.ts` file in the `src` folder of your project with the following content:
```ts /src/instrumentation.ts
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
import { SimpleSpanProcessor } from "@opentelemetry/sdk-trace-node";
import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
export function register() {
const provider = new NodeTracerProvider({
resource: resourceFromAttributes({
[ATTR_SERVICE_NAME]: "nextjs-otel-example",
}, {
// Use the latest schema version
// Info: https://opentelemetry.io/docs/specs/semconv/
schemaUrl: 'https://opentelemetry.io/schemas/1.37.0',
}),
spanProcessors: [new SimpleSpanProcessor(
new OTLPTraceExporter({
url: `https://${process.env.AXIOM_HOST}/v1/traces`,
headers: {
Authorization: `Bearer ${process.env.AXIOM_TOKEN}`,
"X-Axiom-Dataset": `${process.env.AXIOM_DATASET}`,
},
})
)],
});
provider.register();
}
```
4. Add the `AXIOM_DOMAIN`, `API_TOKEN`, and `DATASET_NAME` environment variables to your `.env` file. For example:
```bash
AXIOM_HOST="AXIOM_DOMAIN"
AXIOM_TOKEN="API_TOKEN"
AXIOM_DATASET="DATASET_NAME"
```
### Update root layout [#update-root-layout]
In the `/src/app/layout.tsx` file, import and call the `register` function from the `instrumentation` module:
```tsx /src/app/layout.tsx
import { register } from '../instrumentation';
register();
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
This file sets up the root layout for your Next.js app and initializes the OpenTelemetry instrumentation by calling the `register` function.
### Update compiler options [#update-compiler-options]
Add the following options to your `tsconfig.json` file to ensure compatibility with OpenTelemetry and Next.js:
```json /tsconfig.json
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
```
This file configures the TypeScript compiler options for your Next.js app.
### Observe traces in Axiom [#observe-traces-in-axiom]
Use the following command to run your Next.js app with OpenTelemetry instrumentation in development mode:
```bash
npm run dev
```
This command starts the Next.js development server, and the OpenTelemetry instrumentation automatically collects traces. As you interact with your app, traces are sent to Axiom where you can monitor and analyze your app’s performance and behavior.
In Axiom, go to the **Stream** tab and click your dataset. This page displays the traces sent to Axiom and lets you monitor and analyze your app’s performance and behavior.
Go to the **Dashboards** tab and click **OpenTelemetry Traces**. This pre-built traces dashboard provides further insights into the performance and behavior of your app.
## Send data from existing project [#send-data-from-existing-project]
### Manual instrumentation [#manual-instrumentation]
Manual instrumentation allows you to create, configure, and manage spans and traces, providing detailed control over telemetry data collection at specific points within the app.
1. Set up and retrieve a tracer from the OpenTelemetry API. This tracer starts and manages spans within your app components or API routes.
```js
import { trace } from '@opentelemetry/api';
const tracer = trace.getTracer('nextjs-app');
```
2. Manually start a span at the beginning of significant operations or transactions within your Next.js app and ensure you end it appropriately. This approach is for tracing specific custom events or operations not automatically captured by instrumentations.
```js
const span = tracer.startSpan('operationName');
try {
// Perform your operation here
} finally {
span.end();
}
```
3. Enhance the span with additional information such as user details or operation outcomes, which can provide deeper insights when analyzing telemetry data.
```js
span.setAttribute('user_id', userId);
span.setAttribute('operation_status', 'success');
```
### Automatic instrumentation [#automatic-instrumentation]
Automatic instrumentation uses the capabilities of OpenTelemetry to automatically capture telemetry data for standard operations such as HTTP requests and responses.
1. Use the OpenTelemetry Node SDK to configure your app to automatically instrument supported libraries and frameworks. Set up `NodeSDK` in an `instrumentation.ts` file in your project.
```ts /src/instrumentation.ts
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
export function register() {
const sdk = new NodeSDK({
resource: new Resource({ [SEM_RESOURCE_ATTRIBUTES.SERVICE_NAME]: 'nextjs-app' }),
spanProcessor: new BatchSpanProcessor(
new OTLPTraceExporter({
url: `https://${process.env.AXIOM_HOST}/v1/traces`,
headers: {
Authorization: `Bearer ${process.env.AXIOM_TOKEN}`,
'X-Axiom-Dataset': `${process.env.AXIOM_DATASET}`,
},
})
),
});
sdk.start();
}
```
2. Include necessary OpenTelemetry instrumentation packages to automatically capture telemetry from Node.js libraries like HTTP and any other middlewares used by Next.js.
3. Call the `register` function from the `instrumentation.ts` within your app startup file or before your app starts handling traffic to initialize the OpenTelemetry instrumentation.
```js
// In pages/_app.js or an equivalent entry point
import { register } from '../instrumentation';
register();
```
## Reference [#reference]
### List of OpenTelemetry trace fields [#list-of-opentelemetry-trace-fields]
| Field Category | Field Name | Description |
| --------------------------- | ------------------------------------- | ------------------------------------------------------------------ |
| General Trace Information | | |
| | \_rowId | Unique identifier for each row in the trace data. |
| | \_sysTime | System timestamp when the trace data was recorded. |
| | \_time | Timestamp when the actual event being traced occurred. |
| | trace\_id | Unique identifier for the entire trace. |
| | span\_id | Unique identifier for the span within the trace. |
| | parent\_span\_id | Unique identifier for the parent span within the trace. |
| HTTP Attributes | | |
| | attributes.http.method | HTTP method used for the request. |
| | attributes.http.status\_code | HTTP status code returned in response. |
| | attributes.http.route | Route accessed during the HTTP request. |
| | attributes.http.target | Specific target of the HTTP request. |
| Custom Attributes | | |
| | attributes.custom\["next.route"] | Custom attribute defining the Next.js route. |
| | attributes.custom\["next.rsc"] | Indicates if React Server Components are used. |
| | attributes.custom\["next.span\_name"] | Custom name of the span within Next.js context. |
| | attributes.custom\["next.span\_type"] | Type of the Next.js span, describing the operation context. |
| Resource Process Attributes | | |
| | resource.process.pid | Process ID of the Node.js app. |
| | resource.process.runtime.description | Description of the runtime environment. For example, Node.js. |
| | resource.process.runtime.name | Name of the runtime environment. For example, nodejs. |
| | resource.process.runtime.version | Version of the runtime environment For example, 18.17.0. |
| | resource.process.executable.name | Executable name running the process. For example, next-server. |
| Resource Host Attributes | | |
| | resource.host.arch | Architecture of the host machine. For example, arm64. |
| | resource.host.name | Name of the host machine. For example, MacBook-Pro.local. |
| Operational Details | | |
| | duration | Time taken for the operation. |
| | kind | Type of span (for example, server, internal). |
| | name | Name of the span, often a high-level title for the operation. |
| Scope Attributes | | |
| | scope.name | Name of the scope for the operation. For example, next.js. |
| | scope.version | Version of the scope. For example, 0.0.1. |
| Service Attributes | | |
| | service.name | Name of the service generating the trace. For example, nextjs-app. |
| Telemetry SDK Attributes | | |
| | telemetry.sdk.language | Language of the telemetry SDK. For example, nodejs. |
| | telemetry.sdk.name | Name of the telemetry SDK. For example, opentelemetry. |
| | telemetry.sdk.version | Version of the telemetry SDK. For example, 1.23.0. |
### List of imported libraries [#list-of-imported-libraries]
`@opentelemetry/api`
The core API for OpenTelemetry in JavaScript, providing the necessary interfaces and utilities for tracing, metrics, and context propagation. In the context of Next.js, it allows developers to manually instrument custom spans, manipulate context, and access the active span if needed.
`@opentelemetry/exporter-trace-otlp-http`
This exporter enables your Next.js app to send trace data over HTTP to any backend that supports the OTLP (OpenTelemetry Protocol), such as Axiom. Using OTLP ensures compatibility with a wide range of observability tools and standardizes the data export process.
`@opentelemetry/resources`
This defines the Resource which represents the entity producing telemetry. In Next.js, Resources can be used to describe the app (for example, service name, version) and are attached to all exported telemetry, aiding in identifying data in backend systems.
`@opentelemetry/sdk-node`
The OpenTelemetry SDK for Node.js which provides a comprehensive set of tools for instrumenting Node.js apps. It includes automatic instrumentation for popular libraries and frameworks, as well as APIs for manual instrumentation. In the Next.js setup, it’s used to configure and initialize the OpenTelemetry SDK.
`@opentelemetry/sdk-trace-node`
This package provides the Node.js-specific implementation of the OpenTelemetry Tracing SDK. It includes the core components needed to create and manage spans, as well as utilities for automatic and manual instrumentation in Node.js environments. In a Next.js app, it works alongside `@opentelemetry/sdk-node` to give finer control over the tracing pipeline. For example, configuring span processors, sampling strategies, or custom span exporters directly for trace data. It’s useful when you need more granular control over tracing behavior beyond the default SDK configuration.
`@opentelemetry/semantic-conventions`
A set of standard attributes and conventions for describing resources, spans, and metrics in OpenTelemetry. By adhering to these conventions, your Next.js app’s telemetry data becomes more consistent and interoperable with other OpenTelemetry-compatible tools and systems.
---
# OpenTelemetry using Node.js
Source: https://axiom.co/docs/guides/opentelemetry-nodejs
OpenTelemetry provides a [unified approach to collecting telemetry data](https://opentelemetry.io/docs/languages/js/instrumentation/) from your Node.js and TypeScript apps. This guide demonstrates how to configure OpenTelemetry in a Node.js app to send telemetry data to Axiom using OpenTelemetry SDK.
## Prerequisites [#prerequisites]
To configure OpenTelemetry in a Node.js app for sending telemetry data to Axiom, certain prerequisites are necessary. These include:
* Node:js: Node.js version 14 or newer.
* Node.js app: Use your own app written in Node.js, or you can start with the provided **`app.ts`** sample.
* [Create an Axiom account](https://app.axiom.co/).
* [Create a dataset in Axiom](/reference/datasets) where you send your data.
* [Create an API token in Axiom](/reference/tokens) with permissions to create, read, update, and delete datasets.
## Core Application (app.ts) [#core-application-appts]
`app.ts` is the core of the app. It uses Express.js to create a simple web server. The server has an endpoint `/rolldice` that returns a random number, simulating a basic API. It also demonstrates the usage of span links to establish relationships between spans across different traces.
```js
/*app.ts*/
// Importing OpenTelemetry instrumentation for tracing
import './instrumentation';
import { trace, context } from '@opentelemetry/api';
// Importing Express.js: A minimal and flexible Node.js web app framework
import express from 'express';
// Setting up the server port: Use the PORT environment variable or default to 8080
const PORT = parseInt(process.env.PORT || '8080');
const app = express();
// Get the tracer from the global tracer provider
const tracer = trace.getTracer('node-traces');
/**
* Function to generate a random number between min and max (inclusive).
* @param min - The minimum number (inclusive).
* @param max - The maximum number (exclusive).
* @returns A random number between min and max.
*/
function getRandomNumber(min: number, max: number): number {
return Math.floor(Math.random() * (max - min) + min);
}
// Defining a route handler for '/rolldice' that returns a random dice roll
app.get('/rolldice', (req, res) => {
const span = trace.getSpan(context.active());
/**
* Spans can be created with zero or more Links to other Spans that are related.
* Links allow creating connections between different traces
*/
const rollDiceSpan = tracer.startSpan('roll_dice_span', {
links: span ? [{ context: span.spanContext() }] : [],
});
// Set the rollDiceSpan as the currently active span
context.with(trace.setSpan(context.active(), rollDiceSpan), () => {
const diceRoll = getRandomNumber(1, 6).toString();
res.send(diceRoll);
rollDiceSpan.end();
});
});
// Defining a route handler for '/roll_with_link' that creates a parent span and calls '/rolldice'
app.get('/roll_with_link', (req, res) => {
/**
* A common scenario is to correlate one or more traces with the current span.
* This can help in tracing and debugging complex interactions across different parts of the app.
*/
const parentSpan = tracer.startSpan('parent_span');
// Set the parentSpan as the currently active span
context.with(trace.setSpan(context.active(), parentSpan), () => {
const diceRoll = getRandomNumber(1, 6).toString();
res.send(`Dice roll result (with link): ${diceRoll}`);
parentSpan.end();
});
});
// Starting the server on the specified PORT and logging the listening message
app.listen(PORT, () => {
console.log(`Listening for requests on http://localhost:${PORT}`);
});
```
## Exporter (instrumentation.ts) [#exporter-instrumentationts]
`instrumentation.ts` sets up the OpenTelemetry instrumentation. It configures the OTLP (OpenTelemetry Protocol) exporters for traces and initializes the Node SDK with automatic instrumentation capabilities.
```js
/*instrumentation.ts*/
// Importing necessary OpenTelemetry packages including the core SDK, auto-instrumentations, OTLP trace exporter, and batch span processor
import { NodeSDK } from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { Resource } from '@opentelemetry/resources';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
// Initialize OTLP trace exporter with the endpoint URL and headers
const traceExporter = new OTLPTraceExporter({
url: 'https://AXIOM_DOMAIN/v1/traces',
headers: {
'Authorization': 'Bearer API_TOKEN',
'X-Axiom-Dataset': 'DATASET_NAME'
},
});
// Creating a resource to identify your service in traces
const resource = new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: 'node traces',
});
// Configuring the OpenTelemetry Node SDK
const sdk = new NodeSDK({
// Adding a BatchSpanProcessor to batch and send traces
spanProcessor: new BatchSpanProcessor(traceExporter),
// Registering the resource to the SDK
resource: resource,
// Adding auto-instrumentations to automatically collect trace data
instrumentations: [getNodeAutoInstrumentations()],
});
// Starting the OpenTelemetry SDK to begin collecting telemetry data
sdk.start();
```
## Installing the Dependencies [#installing-the-dependencies]
Navigate to the root directory of your project and run the following command to install the required dependencies:
```bash
npm install
```
This command will install all the necessary packages listed in your `package.json` [below](/guides/opentelemetry-nodejs#setting-up-typescript-development-environment)
## Setting Up TypeScript Development Environment [#setting-up-typescript-development-environment]
To run the TypeScript app, you need to set up a TypeScript development environment. This includes adding a `package.json` file to manage your project’s dependencies and scripts, and a `tsconfig.json` file to manage TypeScript compiler options.
### Add `package.json` [#add-packagejson]
Create a `package.json` file in the root of your project with the following content:
```json
{
"name": "typescript-traces",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"build": "tsc",
"start": "ts-node app.ts",
"dev": "ts-node-dev --respawn app.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@opentelemetry/api": "^1.6.0",
"@opentelemetry/api-logs": "^0.46.0",
"@opentelemetry/auto-instrumentations-node": "^0.39.4",
"@opentelemetry/exporter-metrics-otlp-http": "^0.45.0",
"@opentelemetry/exporter-metrics-otlp-proto": "^0.45.1",
"@opentelemetry/exporter-trace-otlp-http": "^0.45.0",
"@opentelemetry/sdk-logs": "^0.46.0",
"@opentelemetry/sdk-metrics": "^1.20.0",
"@opentelemetry/sdk-node": "^0.45.1",
"express": "^4.18.2"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/node": "^16.18.71",
"ts-node": "^10.9.2",
"ts-node-dev": "^2.0.0",
"tsc-watch": "^4.6.2",
"typescript": "^4.9.5"
}
}
```
### Add `tsconfig.json` [#add-tsconfigjson]
Create a `tsconfig.json` file in the root of your project with the following content:
```json
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
```
This configuration file specifies how the TypeScript compiler should transpile TypeScript files into JavaScript.
## Running the Instrumented Application [#running-the-instrumented-application]
To run your Node.js app with OpenTelemetry instrumentation, make sure your API token, and dataset is set in the `instrumentation.ts` file.
### In Development Mode [#in-development-mode]
For development purposes, especially when you need automatic restarts upon file changes, use:
```bash
npm run dev
```
This command will start the OpenTelemetry instrumentation in development mode using `ts-node-dev`. It sets up the exporter for tracing and restarts the server automatically whenever you make changes to the files.
### In Production Mode [#in-production-mode]
To run the app in production mode, you need to first build the TypeScript files into JavaScript. Run the following command to build your app:
```bash
npm run build
```
This command compiles the TypeScript files to JavaScript based on the settings specified in `tsconfig.json`. Once the build process is complete, you can start your app in production mode with:
```bash
npm start
```
The server will start on the specified port, and you can interact with it by sending requests to the `/rolldice` endpoint.
## Observe the telemetry data in Axiom [#observe-the-telemetry-data-in-axiom]
As you interact with your app, traces will be collected and exported to Axiom, where you can monitor and analyze your app’s performance and behavior.
## Dynamic OpenTelemetry traces dashboard [#dynamic-opentelemetry-traces-dashboard]
This data can then be further viewed and analyzed in Axiom’s dashboard, providing insights into the performance and behaviour of your app.
## Send data from an existing Node project [#send-data-from-an-existing-node-project]
### Manual Instrumentation [#manual-instrumentation]
Manual instrumentation in Node.js requires adding code to create and manage spans around the code blocks you want to trace.
1. Initialize Tracer:
Import and configure a tracer in your Node.js app. Use the tracer configured in your instrumentation setup (instrumentation.ts).
```js
// Assuming OpenTelemetry SDK is already configured
const { trace } = require('@opentelemetry/api');
const tracer = trace.getTracer('example-tracer');
```
2. Create Spans:
Wrap the code blocks that you want to trace with spans. Start and end these spans within your code.
```js
const span = tracer.startSpan('operation_name');
try {
// Your code here
span.end();
} catch (error) {
span.recordException(error);
span.end();
}
```
3. Annotate Spans:
Add metadata and logs to your spans for the trace data.
```js
span.setAttribute('key', 'value');
span.addEvent('event name', { eventKey: 'eventValue' });
```
### Automatic Instrumentation [#automatic-instrumentation]
Automatic instrumentation in Node.js simplifies adding telemetry data to your app. It uses pre-built libraries to automatically instrument common frameworks and libraries.
1. Install Instrumentation Libraries:
Use OpenTelemetry packages that automatically instrument common Node.js frameworks and libraries.
```bash
npm install @opentelemetry/auto-instrumentations-node
```
2. Instrument Application:
Configure your app to use these libraries, which will automatically generate spans for standard operations.
```js
// In your instrumentation setup (instrumentation.ts)
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
const sdk = new NodeSDK({
// ... other configurations ...
instrumentations: [getNodeAutoInstrumentations()]
});
```
After you set them up, these libraries automatically trace relevant operations without additional code changes in your app.
## Reference [#reference]
### List of OpenTelemetry trace fields [#list-of-opentelemetry-trace-fields]
| Field Category | Field Name | Description |
| ------------------------------- | --------------------------------------- | ------------------------------------------------------------ |
| **Unique Identifiers** | | |
| | \_rowid | Unique identifier for each row in the trace data. |
| | span\_id | Unique identifier for the span within the trace. |
| | trace\_id | Unique identifier for the entire trace. |
| **Timestamps** | | |
| | \_systime | System timestamp when the trace data was recorded. |
| | \_time | Timestamp when the actual event being traced occurred. |
| **HTTP Attributes** | | |
| | attributes.custom\["http.host"] | Host information where the HTTP request was sent. |
| | attributes.custom\["http.server\_name"] | Server name for the HTTP request. |
| | attributes.http.flavor | HTTP protocol version used. |
| | attributes.http.method | HTTP method used for the request. |
| | attributes.http.route | Route accessed during the HTTP request. |
| | attributes.http.scheme | Protocol scheme (HTTP/HTTPS). |
| | attributes.http.status\_code | HTTP response status code. |
| | attributes.http.target | Specific target of the HTTP request. |
| | attributes.http.user\_agent | User agent string of the client. |
| **Network Attributes** | | |
| | attributes.net.host.port | Port number on the host receiving the request. |
| | attributes.net.peer.port | Port number on the peer (client) side. |
| | attributes.custom\["net.peer.ip"] | IP address of the peer in the network interaction. |
| **Operational Details** | | |
| | duration | Time taken for the operation. |
| | kind | Type of span (for example,, server, client). |
| | name | Name of the span. |
| | scope | Instrumentation scope. |
| | service.name | Name of the service generating the trace. |
| **Resource Process Attributes** | | |
| | resource.process.command | Command line string used to start the process. |
| | resource.process.command\_args | List of command line arguments used in starting the process. |
| | resource.process.executable.name | Name of the executable running the process. |
| | resource.process.executable.path | Path to the executable running the process. |
| | resource.process.owner | Owner of the process. |
| | resource.process.pid | Process ID. |
| | resource.process.runtime.description | Description of the runtime environment. |
| | resource.process.runtime.name | Name of the runtime environment. |
| | resource.process.runtime.version | Version of the runtime environment. |
| **Telemetry SDK Attributes** | | |
| | telemetry.sdk.language | Language of the telemetry SDK. |
| | telemetry.sdk.name | Name of the telemetry SDK. |
| | telemetry.sdk.version | Version of the telemetry SDK. |
### List of imported libraries [#list-of-imported-libraries]
The `instrumentation.ts` file imports the following libraries:
### **`@opentelemetry/sdk-node`** [#opentelemetrysdk-node]
This package is the core SDK for OpenTelemetry in Node.js. It provides the primary interface for configuring and initializing OpenTelemetry in a Node.js app. It includes functionalities for managing traces and context propagation. The SDK is designed to be extensible, allowing for custom configurations and integration with different telemetry backends like Axiom.
### **`@opentelemetry/auto-instrumentations-node`** [#opentelemetryauto-instrumentations-node]
This package offers automatic instrumentation for Node.js apps. It simplifies the process of instrumenting various common Node.js libraries and frameworks. By using this package, developers can automatically collect telemetry data (such as traces) from their apps without needing to manually instrument each library or API call. This is important for apps with complex dependencies, as it ensures comprehensive and consistent telemetry collection across the app.
### **`@opentelemetry/exporter-trace-otlp-proto`** [#opentelemetryexporter-trace-otlp-proto]
The **`@opentelemetry/exporter-trace-otlp-proto`** package provides an exporter that sends trace data using the OpenTelemetry Protocol (OTLP). OTLP is the standard protocol for transmitting telemetry data in the OpenTelemetry ecosystem. This exporter allows Node.js apps to send their collected traces to any backend that supports OTLP, such as Axiom. The use of OTLP ensures broad compatibility and a standardized way of transmitting telemetry data.
### **`@opentelemetry/sdk-trace-base`** [#opentelemetrysdk-trace-base]
Contained within this package is the **`BatchSpanProcessor`**, among other foundational elements for tracing in OpenTelemetry. The **`BatchSpanProcessor`** is a component that collects and processes spans (individual units of trace data). As the name suggests, it batches these spans before sending them to the configured exporter (in this case, the `OTLPTraceExporter`). This batching mechanism is efficient as it reduces the number of outbound requests by aggregating multiple spans into fewer batches. It helps in the performance and scalability of trace data export in an OpenTelemetry-instrumented app.
---
# OpenTelemetry using Nuxt.js
Source: https://axiom.co/docs/guides/opentelemetry-nuxtjs
OpenTelemetry provides a [unified approach to collecting telemetry data](https://opentelemetry.io/docs/languages/js/instrumentation/) from your Nuxt.js and TypeScript apps. This page demonstrates how to configure OpenTelemetry in a Nuxt.js app to send telemetry data to Axiom using OpenTelemetry SDK.
* [Install Node.js](https://nodejs.org/en/download/package-manager) version 18 or newer.
* Use your own app written in Nuxt.js, or follow this guide to create a new one.
## Create new Nuxt.js app [#create-new-nuxtjs-app]
Run the following command to create a new Nuxt.js app. Accept the default options during the initialization.
```bash
npx nuxi@latest init my-nuxt-app
cd my-nuxt-app
```
## Install dependencies [#install-dependencies]
Install the required OpenTelemetry packages:
```bash
npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node @opentelemetry/exporter-trace-otlp-proto @opentelemetry/sdk-trace-base @opentelemetry/resources @opentelemetry/semantic-conventions
```
## Configure environment variables [#configure-environment-variables]
Create a `.env` file in the root of your project to store your Axiom credentials:
```dotenv
AXIOM_TOKEN=API_TOKEN
AXIOM_DATASET=DATASET_NAME
```
## Configure Nuxt.js app [#configure-nuxtjs-app]
Configure your Nuxt app in `nuxt.config.ts` to expose the environment variables to the runtime:
```typescript nuxt.config.ts
export default defineNuxtConfig({
compatibilityDate: '2026-01-05',
devtools: { enabled: true },
runtimeConfig: {
axiomToken: process.env.AXIOM_TOKEN,
axiomDataset: process.env.AXIOM_DATASET,
},
nitro: {
experimental: {
openAPI: true
}
}
});
```
## Server setup [#server-setup]
### Create server directories [#create-server-directories]
Create the necessary directories for your server-side code:
```bash
mkdir -p server/api
mkdir -p server/plugins
```
### Instrumentation plugin [#instrumentation-plugin]
Create the OpenTelemetry instrumentation plugin in `server/plugins/instrumentation.ts`. This file sets up the OpenTelemetry SDK and configures it to send traces to Axiom.
In Nuxt.js, you must initialize OpenTelemetry in a Nitro plugin, not in the `nuxt.config.ts` hooks, because API endpoints run in the Nitro server runtime.
This example uses the `ATTR_SERVICE_NAME` constant instead of the deprecated `SemanticResourceAttributes.SERVICE_NAME`, and `resourceFromAttributes()` instead of `new Resource()` for compatibility with newer OpenTelemetry versions.
```ts server/plugins/instrumentation.ts expandable
import { NodeSDK } from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { resourceFromAttributes } from '@opentelemetry/resources';
import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
export default defineNitroPlugin((nitroApp) => {
console.log('Initializing OpenTelemetry in Nitro server...');
console.log('- AXIOM_TOKEN:', process.env.AXIOM_TOKEN ? `${process.env.AXIOM_TOKEN.substring(0, 10)}...` : 'NOT SET');
console.log('- AXIOM_DATASET:', process.env.AXIOM_DATASET || 'NOT SET');
const traceExporter = new OTLPTraceExporter({
url: 'https://api.axiom.co/v1/traces',
headers: {
'Authorization': `Bearer ${process.env.AXIOM_TOKEN}`,
'X-Axiom-Dataset': process.env.AXIOM_DATASET || ''
},
});
// Add export success/error logging for debugging
const originalExport = traceExporter.export.bind(traceExporter);
traceExporter.export = (spans, resultCallback) => {
console.log(`Exporting ${spans.length} span(s) to Axiom...`);
originalExport(spans, (result) => {
if (result.code === 0) {
console.log(' Spans exported successfully to Axiom');
} else {
console.error(' Export failed:', result.error);
}
resultCallback(result);
});
};
const resource = resourceFromAttributes({
[ATTR_SERVICE_NAME]: 'my-nuxt-app',
});
const sdk = new NodeSDK({
spanProcessor: new BatchSpanProcessor(traceExporter),
resource: resource,
instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();
console.log('OpenTelemetry started in Nitro server');
});
```
### Example API endpoint [#example-api-endpoint]
Create an example API endpoint in `server/api/hello.ts` to test your OpenTelemetry setup.
The example endpoint below demonstrates manual span creation. Each request to `/api/hello` creates a trace span and sends it to Axiom.
```ts server/api/hello.ts
import { trace } from '@opentelemetry/api';
export default defineEventHandler((event) => {
console.log('API endpoint hit: /api/hello');
// Get the tracer from the global tracer provider
const tracer = trace.getTracer('my-nuxt-app');
// Create a manual span for this API request
const span = tracer.startSpan('api.hello');
span.setAttribute('http.method', 'GET');
span.setAttribute('http.path', '/api/hello');
const response = {
message: 'Hello from Nuxt API!',
timestamp: new Date().toISOString(),
path: event.path
};
span.end();
console.log('Manual span created and ended');
return response;
});
```
## Run instrumented app [#run-instrumented-app]
### In development mode [#in-development-mode]
To run your Nuxt app with OpenTelemetry instrumentation in development mode:
```bash
npm run dev
```
You see the following output in the console:
```
Nuxt 4.2.2 (with Nitro 2.12.9, Vite 7.3.0 and Vue 3.5.26)
➜ Local: http://localhost:3000/
Initializing OpenTelemetry in Nitro server...
- AXIOM_TOKEN: xaat-xxxxx...
- AXIOM_DATASET: nuxt-traces
OpenTelemetry started in Nitro server
```
### Test setup [#test-setup]
Test your API endpoint to generate traces:
```bash
curl http://localhost:3000/api/hello
```
You get the following response from the API endpoint:
```json
{
"message": "Hello from Nuxt API!",
"timestamp": "2026-01-05T22:30:00.000Z",
"path": "/api/hello"
}
```
After making 5-10 requests, you see the following output in the console:
```
Exporting 5 span(s) to Axiom...
Spans exported successfully to Axiom
```
### In production mode [#in-production-mode]
To build and run in production:
```bash
# Build the application
npm run build
# Start the production server
npm run preview
```
After generating some traces by visiting your API endpoints, go to the **Stream** tab in Axiom, and then click your dataset. You see the traces appearing in the stream.
## Project directory structure [#project-directory-structure]
Your Nuxt.js project has the following structure:
```
my-nuxt-app/
├── server/
│ ├── api/
│ │ └── hello.ts # Example API endpoint
│ └── plugins/
│ └── instrumentation.ts # OpenTelemetry configuration
├── .env # Environment variables
├── nuxt.config.ts # Nuxt configuration
├── package.json # Dependencies and scripts
└── tsconfig.json # TypeScript configuration (auto-generated)
```
### Root-level files [#root-level-files]
* **`.env`**: Stores environment variables (API token, dataset name)
* **`nuxt.config.ts`**: Nuxt configuration file that exposes environment variables to the runtime
* **`package.json`**: Lists dependencies and npm scripts
* **`tsconfig.json`**: TypeScript configuration (auto-generated by Nuxt)
### Server directory [#server-directory]
The `server/` directory contains all server-side code that runs in Nitro, Nuxt's server engine.
* `server/api/` directory contains API route handlers. Each file becomes an API endpoint:
* `server/api/hello.ts` → `/api/hello`
* `server/api/users.ts` → `/api/users`
* `server/api/posts/[id].ts` → `/api/posts/:id`
* `server/plugins/` directory contains Nitro plugins that run when the server starts:
* `server/plugins/instrumentation.ts`: Initializes OpenTelemetry SDK
## Manual instrumentation [#manual-instrumentation]
Manual instrumentation in Nuxt.js allows you to create custom spans for specific operations.
### Initialize tracer [#initialize-tracer]
Import the OpenTelemetry API in any server file, such as `server/api/hello.ts`:
```ts server/api/hello.ts
import { trace } from '@opentelemetry/api';
const tracer = trace.getTracer('my-nuxt-app');
```
### Create spans [#create-spans]
Wrap operations you want to trace:
```ts
export default defineEventHandler(async (event) => {
const span = tracer.startSpan('database.query');
try {
// Your code here
const data = await fetchDataFromDatabase();
span.setStatus({ code: 0 }); // Success
span.end();
return data;
} catch (error) {
span.recordException(error);
span.setStatus({ code: 2, message: error.message }); // Error
span.end();
throw error;
}
});
```
### Annotate spans [#annotate-spans]
Add metadata to your spans, such as `order.id`, `user.id`, and `order.amount`:
```typescript
const span = tracer.startSpan('process.order');
span.setAttribute('order.id', orderId);
span.setAttribute('user.id', userId);
span.setAttribute('order.amount', amount);
span.addEvent('payment_processed', {
paymentMethod: 'credit_card',
processorResponse: 'approved'
});
span.end();
```
### Create nested spans [#create-nested-spans]
Create parent-child relationships between spans:
```ts
import { trace, context } from '@opentelemetry/api';
export default defineEventHandler(async (event) => {
const tracer = trace.getTracer('my-nuxt-app');
const parentSpan = tracer.startSpan('process.checkout');
// Make parentSpan the active span
await context.with(trace.setSpan(context.active(), parentSpan), async () => {
// This span will be a child of parentSpan
const childSpan = tracer.startSpan('validate.payment');
await validatePayment();
childSpan.end();
// Another child span
const childSpan2 = tracer.startSpan('create.order');
await createOrder();
childSpan2.end();
});
parentSpan.end();
});
```
## Automatic instrumentation [#automatic-instrumentation]
Automatic instrumentation is already set up in the `server/plugins/instrumentation.ts` file:
```ts server/plugins/instrumentation.ts
instrumentations: [getNodeAutoInstrumentations()]
```
This automatically traces:
* HTTP requests and responses
* Database queries (MySQL, PostgreSQL, MongoDB, etc.)
* Redis operations
* File system operations
* DNS lookups
* And many more Node.js operations
## Reference [#reference]
### List of OpenTelemetry Trace Fields [#list-of-opentelemetry-trace-fields]
| Field Category | Field Name | Description |
| ---------------------------- | -------------------------------- | ------------------------------------------------------------ |
| **Unique Identifiers** | | |
| | \_rowid | Unique identifier for each row in the trace data. |
| | span\_id | Unique identifier for the span within the trace. |
| | trace\_id | Unique identifier for the entire trace. |
| **Timestamps** | | |
| | \_systime | System timestamp when the trace data was recorded. |
| | \_time | Timestamp when the actual event being traced occurred. |
| **HTTP Attributes** | | |
| | attributes.http.method | HTTP method used for the request. |
| | attributes.http.path | The API path accessed during the request. |
| | attributes.http.status\_code | HTTP response status code. |
| | attributes.http.route | Route pattern (for example, /api/:id). |
| | attributes.http.scheme | Protocol scheme (HTTP/HTTPS). |
| | attributes.http.user\_agent | User agent string of the client. |
| **Network Attributes** | | |
| | attributes.net.host.port | Port number on the host receiving the request. |
| | attributes.net.peer.ip | IP address of the peer in the network interaction. |
| **Operational Details** | | |
| | duration | Time taken for the operation in nanoseconds. |
| | kind | Type of span (server, client, internal, producer, consumer). |
| | name | Name of the span (for example, 'api.hello'). |
| | scope | Instrumentation scope. |
| | service.name | Name of the service generating the trace. |
| **Resource Attributes** | | |
| | resource.process.pid | Process ID of the Nitro server. |
| | resource.process.runtime.name | Runtime name (for example, 'nodejs'). |
| | resource.process.runtime.version | Node.js version. |
| **Telemetry SDK Attributes** | | |
| | telemetry.sdk.language | Language of the telemetry SDK (javascript). |
| | telemetry.sdk.name | Name of the telemetry SDK (opentelemetry). |
| | telemetry.sdk.version | Version of the telemetry SDK. |
### List of Imported Libraries [#list-of-imported-libraries]
#### `@opentelemetry/sdk-node` [#opentelemetrysdk-node]
The core SDK for OpenTelemetry in Node.js. Provides the primary interface for configuring and initializing OpenTelemetry in a Node.js/Nuxt app. It includes functionalities for managing traces, metrics, and context propagation.
#### `@opentelemetry/auto-instrumentations-node` [#opentelemetryauto-instrumentations-node]
Offers automatic instrumentation for Node.js apps. Automatically collects telemetry data from common Node.js libraries and frameworks without manual instrumentation. Essential for Nuxt/Nitro server operations.
#### `@opentelemetry/exporter-trace-otlp-proto` [#opentelemetryexporter-trace-otlp-proto]
Provides an exporter that sends trace data using the OpenTelemetry Protocol (OTLP). Allows Nuxt apps to send collected traces to Axiom or any OTLP-compatible backend.
#### `@opentelemetry/sdk-trace-base` [#opentelemetrysdk-trace-base]
Contains the `BatchSpanProcessor` and other foundational elements for tracing. The `BatchSpanProcessor` batches spans before sending them to the exporter, improving performance and reducing network overhead.
#### `@opentelemetry/resources` [#opentelemetryresources]
Provides the `resourceFromAttributes()` function to create resource objects that identify your service in traces. Resources contain service metadata like service name, version, and environment.
#### `@opentelemetry/semantic-conventions` [#opentelemetrysemantic-conventions]
Provides standard attribute names like `ATTR_SERVICE_NAME` for consistent telemetry data. Ensures your traces follow OpenTelemetry semantic conventions for better interoperability.
#### `@opentelemetry/api` [#opentelemetryapi]
The OpenTelemetry API package that provides the `trace` and `context` APIs for manual instrumentation. This is a peer dependency that other OpenTelemetry packages rely on.
## Advanced configurations [#advanced-configurations]
### Custom span processor [#custom-span-processor]
For more control over span processing, use the `SimpleSpanProcessor` instead of the `BatchSpanProcessor`:
```typescript
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
const sdk = new NodeSDK({
spanProcessor: new SimpleSpanProcessor(traceExporter), // Exports immediately
resource: resource,
instrumentations: [getNodeAutoInstrumentations()],
});
```
### Sampling [#sampling]
To reduce the volume of traces, use the `TraceIdRatioBasedSampler` to sample a percentage of traces:
```typescript
import { TraceIdRatioBasedSampler } from '@opentelemetry/sdk-trace-base';
const sdk = new NodeSDK({
spanProcessor: new BatchSpanProcessor(traceExporter),
sampler: new TraceIdRatioBasedSampler(0.5), // Sample 50% of traces
resource: resource,
instrumentations: [getNodeAutoInstrumentations()],
});
```
### Custom resource attributes [#custom-resource-attributes]
Add custom attributes to all traces, such as `service.version` and `deployment.environment`:
```typescript
const resource = resourceFromAttributes({
[ATTR_SERVICE_NAME]: 'my-nuxt-app',
[ATTR_SERVICE_VERSION]: '1.0.0',
'deployment.environment': process.env.NODE_ENV || 'development',
'service.namespace': 'production',
});
```
---
# Send OpenTelemetry data from a Python app to Axiom
Source: https://axiom.co/docs/guides/opentelemetry-python
This guide explains how to send OpenTelemetry data from a Python app to Axiom using the [Python OpenTelemetry SDK](https://opentelemetry.io/docs/languages/python/instrumentation/).
## Prerequisites [#prerequisites]
* Install Python version 3.7 or higher.
## Install required dependencies [#install-required-dependencies]
To install the required Python dependencies, run the following code in your terminal:
```bash
pip install opentelemetry-api opentelemetry-sdk opentelemetry-instrumentation-flask opentelemetry-exporter-otlp Flask
```
### Install dependencies with requirements file [#install-dependencies-with-requirements-file]
Alternatively, if you use a `requirements.txt` file in your Python project, add these lines:
```txt
opentelemetry-api
opentelemetry-sdk
opentelemetry-instrumentation-flask
opentelemetry-exporter-otlp
Flask
```
Then run the following code in your terminal to install dependencies:
```bash
pip install -r requirements.txt
```
## Create an app.py file [#create-an-apppy-file]
Create an `app.py` file with the following content. This file creates a basic HTTP server using Flask. It also demonstrates the usage of span links to establish relationships between spans across different traces.
```python
# app.py
from flask import Flask
from opentelemetry.instrumentation.flask import FlaskInstrumentor
from opentelemetry import trace
from random import randint
import exporter
# Creating a Flask app instance
app = Flask(__name__)
# Automatically instruments Flask app to enable tracing
FlaskInstrumentor().instrument_app(app)
# Retrieving a tracer from the custom exporter
tracer = exporter.service1_tracer
@app.route("/rolldice")
def roll_dice(parent_span=None):
# Starting a new span for the dice roll. If a parent span is provided, link to its span context.
with tracer.start_as_current_span("roll_dice_span",
links=[trace.Link(parent_span.get_span_context())] if parent_span else None) as span:
# Spans can be created with zero or more Links to other Spans that are related.
# Links allow creating connections between different traces
return str(roll())
@app.route("/roll_with_link")
def roll_with_link():
# Starting a new 'parent_span' which may later link to other spans
with tracer.start_as_current_span("parent_span") as parent_span:
# A common scenario is to correlate one or more traces with the current span.
# This can help in tracing and debugging complex interactions across different parts of the app.
result = roll_dice(parent_span)
return f"Dice roll result (with link): {result}"
def roll():
# Function to generate a random number between 1 and 6
return randint(1, 6)
if __name__ == "__main__":
# Starting the Flask server on the specified PORT and enabling debug mode
app.run(port=8080, debug=True)
```
## Create an exporter.py file [#create-an-exporterpy-file]
Create an `exporter.py` file with the following content. This file establishes an OpenTelemetry configuration and sets up an exporter that sends trace data to Axiom.
```python
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.resources import Resource, SERVICE_NAME
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
# Define the service name resource for the tracer.
resource = Resource(attributes={
SERVICE_NAME: "NAME_OF_SERVICE" # Replace `NAME_OF_SERVICE` with the name of the service you want to trace.
})
# Create a TracerProvider with the defined resource for creating tracers.
provider = TracerProvider(resource=resource)
# Configure the OTLP/HTTP Span Exporter with Axiom headers and endpoint.
otlp_exporter = OTLPSpanExporter(
endpoint="https://AXIOM_DOMAIN/v1/traces",
headers={
"Authorization": "Bearer API_TOKEN",
"X-Axiom-Dataset": "DATASET_NAME"
}
)
# Create a BatchSpanProcessor with the OTLP exporter to batch and send trace spans.
processor = BatchSpanProcessor(otlp_exporter)
provider.add_span_processor(processor)
# Set the TracerProvider as the global tracer provider.
trace.set_tracer_provider(provider)
# Define a tracer for external use in different parts of the app.
service1_tracer = trace.get_tracer("service1")
```
Replace `NAME_OF_SERVICE` with the name of the service you want to trace. This is important for identifying and categorizing trace data, particularly in systems with multiple services.
For more information on the libraries imported by the `exporter.py` file, see the [Reference](#reference) below.
## Run the app [#run-the-app]
Run the following code in your terminal to run the Python project:
macOS/Linux
```bash
python3 app.py
```
Windows
```
py -3 app.py
```
In your browser, go to `http://127.0.0.1:8080/rolldice` to interact with your Python app. Each time you load the page, the app displays a random number and sends the collected traces to Axiom.
## Observe the telemetry data in Axiom [#observe-the-telemetry-data-in-axiom]
In Axiom, go the **Stream** tab and click your dataset. This page displays the traces sent to Axiom and enables you to monitor and analyze your app’s performance and behavior.
## Dynamic OpenTelemetry traces dashboard [#dynamic-opentelemetry-traces-dashboard]
In Axiom, go the **Dashboards** tab and click **OpenTelemetry Traces (python)**. This pre-built traces dashboard provides further insights into the performance and behavior of your app.
## Send data from an existing Python project [#send-data-from-an-existing-python-project]
### Manual instrumentation [#manual-instrumentation]
Manual instrumentation in Python with OpenTelemetry involves adding code to create and manage spans around the blocks of code you want to trace. This approach allows for precise control over the trace data.
1. Import and configure a tracer at the start of your main Python file. For example, use the tracer from the `exporter.py` configuration.
```python
import exporter
tracer = exporter.service1_tracer
```
2. Enclose the code blocks in your app that you want to trace within spans. Start and end these spans in your code.
```python
with tracer.start_as_current_span("operation_name"):
```
3. Add relevant metadata and logs to your spans to enrich the trace data, providing more context for your data.
```python
with tracer.start_as_current_span("operation_name") as span:
span.set_attribute("key", "value")
```
### Automatic instrumentation [#automatic-instrumentation]
Automatic instrumentation in Python with OpenTelemetry simplifies the process of adding telemetry data to your app. It uses pre-built libraries that automatically instrument the frameworks and libraries.
1. Install the OpenTelemetry packages designed for specific frameworks like Flask or Django.
```bash
pip install opentelemetry-instrumentation-flask
```
2. Configure your app to use these libraries that automatically generate spans for standard operations.
```python
from opentelemetry.instrumentation.flask import FlaskInstrumentor
# This assumes `app` is your Flask app.
FlaskInstrumentor().instrument_app(app)
```
After you set them up, these libraries automatically trace relevant operations without additional code changes in your app.
## Reference [#reference]
### List of OpenTelemetry trace fields [#list-of-opentelemetry-trace-fields]
| Field Category | Field Name | Description |
| ------------------- | --------------------------------------- | ------------------------------------------------------ |
| Unique Identifiers | | |
| | \_rowid | Unique identifier for each row in the trace data. |
| | span\_id | Unique identifier for the span within the trace. |
| | trace\_id | Unique identifier for the entire trace. |
| Timestamps | | |
| | \_systime | System timestamp when the trace data was recorded. |
| | \_time | Timestamp when the actual event being traced occurred. |
| HTTP Attributes | | |
| | attributes.custom\["http.host"] | Host information where the HTTP request was sent. |
| | attributes.custom\["http.server\_name"] | Server name for the HTTP request. |
| | attributes.http.flavor | HTTP protocol version used. |
| | attributes.http.method | HTTP method used for the request. |
| | attributes.http.route | Route accessed during the HTTP request. |
| | attributes.http.scheme | Protocol scheme (HTTP/HTTPS). |
| | attributes.http.status\_code | HTTP response status code. |
| | attributes.http.target | Specific target of the HTTP request. |
| | attributes.http.user\_agent | User agent string of the client. |
| Network Attributes | | |
| | attributes.net.host.port | Port number on the host receiving the request. |
| | attributes.net.peer.port | Port number on the peer (client) side. |
| | attributes.custom\["net.peer.ip"] | IP address of the peer in the network interaction. |
| Operational Details | | |
| | duration | Time taken for the operation. |
| | kind | Type of span (for example,, server, client). |
| | name | Name of the span. |
| | scope | Instrumentation scope. |
| | service.name | Name of the service generating the trace. |
### List of imported libraries [#list-of-imported-libraries]
The `exporter.py` file imports the following libraries:
from opentelemetry import trace
This module creates and manages trace data in your app. It creates spans and tracers which track the execution flow and performance of your app.
from opentelemetry.sdk.trace import TracerProvider
`TracerProvider` acts as a container for the configuration of your app’s tracing behavior. It allows you to define how spans are generated and processed, essentially serving as the central point for managing trace creation and propagation in your app.
from opentelemetry.sdk.trace.export import BatchSpanProcessor
`BatchSpanProcessor` is responsible for batching spans before they're exported. This is an important aspect of efficient trace data management as it aggregates multiple spans into fewer network requests, reducing the overhead on your app’s performance and the tracing backend.
from opentelemetry.sdk.resources import Resource, SERVICE\_NAME
The `Resource` class is used to describe your app’s service attributes, such as its name, version, and environment. This contextual information is attached to the traces and helps in identifying and categorizing trace data, making it easier to filter and analyze in your monitoring setup.
from opentelemetry.exporter.otlp.proto.http.trace\_exporter import OTLPSpanExporter
The `OTLPSpanExporter` is responsible for sending your app’s trace data to a backend that supports the OTLP such as Axiom. It formats the trace data according to the OTLP standards and transmits it over HTTP, ensuring compatibility and standardization in how telemetry data is sent across different systems and services.
---
# Send OpenTelemetry data from a Ruby on Rails app to Axiom
Source: https://axiom.co/docs/guides/opentelemetry-ruby
This guide provides detailed steps on how to configure OpenTelemetry in a Ruby app to send telemetry data to Axiom using the [OpenTelemetry Ruby SDK](https://opentelemetry.io/docs/languages/ruby/).
* Install a [Ruby version manager](https://www.ruby-lang.org/en/documentation/installation/) like `rbenv` and use it to install the latest Ruby version.
* Install [Rails](https://guides.rubyonrails.org/v5.0/getting_started.html) using the `gem install rails` command.
## Set up the Ruby on Rails app [#set-up-the-ruby-on-rails-app]
1. Create a new Rails app using the `rails new myapp` command.
2. Go to the app directory with the `cd myapp` command.
3. Open the `Gemfile` and add the following OpenTelemetry packages:
```ruby
gem 'opentelemetry-api'
gem 'opentelemetry-sdk'
gem 'opentelemetry-exporter-otlp'
gem 'opentelemetry-instrumentation-rails'
gem 'opentelemetry-instrumentation-http'
gem 'opentelemetry-instrumentation-active_record', require: false
gem 'opentelemetry-instrumentation-all'
```
Install the dependencies by running `bundle install`.
## Configure the OpenTelemetry exporter [#configure-the-opentelemetry-exporter]
In the `initializers` folder of your Rails app, create a new file called `opentelemetry.rb`, and then add the following OpenTelemetry exporter configuration:
```ruby
require 'opentelemetry/sdk'
require 'opentelemetry/exporter/otlp'
require 'opentelemetry/instrumentation/all'
OpenTelemetry::SDK.configure do |c|
c.service_name = 'ruby-traces' # Set your service name
c.use_all # Or specify individual instrumentation you need
c.add_span_processor(
OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(
OpenTelemetry::Exporter::OTLP::Exporter.new(
endpoint: 'https://AXIOM_DOMAIN/v1/traces',
headers: {
'Authorization' => 'Bearer API_TOKEN',
'X-AXIOM-DATASET' => 'DATASET_NAME'
}
)
)
)
end
```
## Run the instrumented app [#run-the-instrumented-app]
Run your Ruby on Rails app with OpenTelemetry instrumentation.
### In development mode [#in-development-mode]
Start the Rails server using the `rails server` command. The server will start on the default port (usually 3000), and you can access your app by visiting `http://localhost:3000` in your web browser.
As you interact with your app, OpenTelemetry automatically collects telemetry data and sends it to Axiom using the configured OTLP exporter.
### In production mode [#in-production-mode]
For production, ensure to precompile assets and run migrations if necessary. Start the server with `RAILS_ENV=production bin/rails server`. This setup ensures your Ruby app is instrumented to send traces to Axiom, using OpenTelemetry for observability.
## Observe the telemetry data in Axiom [#observe-the-telemetry-data-in-axiom]
As you interact with your app, traces are collected and exported to Axiom, allowing you to monitor, analyze, and gain insights into your app’s performance and behavior.
1. In your Axiom account and click the **Datasets** or **Stream** tab.
2. Select your dataset from the list.
3. From the list of fields, click the **trace\_id** to view your spans.
## Dynamic OpenTelemetry Traces dashboard [#dynamic-opentelemetry-traces-dashboard]
This data can then be further viewed and analyzed in Axiom’s dashboard, offering a deeper understanding of your app’s performance and behavior.
1. In your Axiom account, select **Dashboards**, and click the traces dashboard named after your dataset.
2. View the dashboard which displays your total traces, incoming spans, average span duration, errors, slowest operations, and top 10 span errors across services.
## Send data from an existing Ruby app [#send-data-from-an-existing-ruby-app]
### Manual instrumentation [#manual-instrumentation]
Manual instrumentation allows users to define and manage telemetry data collection points within their Ruby apps, providing granular control over what is traced.
1. Initialize Tracer. Use the OpenTelemetry API to obtain a tracer from the global tracer provider. This tracer will be used to start and manage spans.
```ruby
tracer = OpenTelemetry.tracer_provider.tracer('my-tracer')
```
2. Manually start a span at the beginning of the block of code you want to trace and ensure to end it when your operations complete. This is useful for gathering detailed data about specific operations.
```ruby
span = tracer.start_span('operation_name')
begin
# Perform operation
rescue => e
span.record_exception(e)
span.status = OpenTelemetry::Trace::Status.error("Operation failed")
ensure
span.finish
end
```
3. Enhance spans with custom attributes to provide additional context about the traced operations, helping in debugging and monitoring performance.
```ruby
span.set_attribute("user_id", user.id)
span.add_event("query_executed", attributes: { "query" => sql_query })
```
### Automatic instrumentation [#automatic-instrumentation]
Automatic instrumentation in Ruby uses OpenTelemetry’s libraries to automatically generate telemetry data for common operations, such as HTTP requests and database queries.
1. Set up the OpenTelemetry SDK with the necessary instrumentation libraries in your Ruby app. This typically involves modifying the Gemfile and an initializer to set up the SDK and auto-instrumentation.
```ruby
# In config/initializers/opentelemetry.rb
OpenTelemetry::SDK.configure do |c|
c.service_name = 'ruby-traces'
c.use_all # Automatically use all available instrumentation
end
```
2. Ensure your Gemfile includes gems for the automatic instrumentation of the frameworks and libraries your app uses.
```ruby
gem 'opentelemetry-instrumentation-rails'
gem 'opentelemetry-instrumentation-http'
gem 'opentelemetry-instrumentation-active_record'
```
After setting up, no additional manual changes are required for basic telemetry data collection. The instrumentation libraries handle the creation and management of telemetry data automatically.
## Reference [#reference]
### List of OpenTelemetry trace fields [#list-of-opentelemetry-trace-fields]
| Field Category | Field Name | Description |
| ------------------------------- | ------------------------------------ | ------------------------------------------------------------- |
| **General Trace Information** | | |
| | \_rowId | Unique identifier for each row in the trace data. |
| | \_sysTime | System timestamp when the trace data was recorded. |
| | \_time | Timestamp when the actual event being traced occurred. |
| | trace\_id | Unique identifier for the entire trace. |
| | span\_id | Unique identifier for the span within the trace. |
| | parent\_span\_id | Unique identifier for the parent span within the trace. |
| **HTTP Attributes** | | |
| | attributes.http.method | HTTP method used for the request. |
| | attributes.http.status\_code | HTTP status code returned in response. |
| | attributes.http.target | Specific target of the HTTP request. |
| | attributes.http.scheme | Protocol scheme (HTTP/HTTPS). |
| **User Agent** | | |
| | attributes.http.user\_agent | User agent string, providing client software and OS. |
| **Custom Attributes** | | |
| | attributes.custom\["http.host"] | Host information where the HTTP request was sent. |
| | attributes.custom.identifier | Path to a file or identifier in the trace context. |
| | attributes.custom.layout | Layout used in the rendering process of a view or template. |
| **Resource Process Attributes** | | |
| | resource.process.command | Command line string used to start the process. |
| | resource.process.pid | Process ID. |
| | resource.process.runtime.description | Description of the runtime environment. |
| | resource.process.runtime.name | Name of the runtime environment. |
| | resource.process.runtime.version | Version of the runtime environment. |
| **Operational Details** | | |
| | duration | Time taken for the operation. |
| | kind | Type of span (for example, server, client, internal). |
| | name | Name of the span, often a high-level title for the operation. |
| **Code Attributes** | | |
| | attributes.code.function | Function or method being executed. |
| | attributes.code.namespace | Namespace or module that includes the function. |
| **Scope Attributes** | | |
| | scope.name | Name of the scope for the operation. |
| | scope.version | Version of the scope. |
| **Service Attributes** | | |
| | service.name | Name of the service generating the trace. |
| | service.version | Version of the service generating the trace. |
| | service.instance.id | Unique identifier for the instance of the service. |
| **Telemetry SDK Attributes** | | |
| | telemetry.sdk.language | Language of the telemetry SDK, for example, ruby. |
| | telemetry.sdk.name | Name of the telemetry SDK, for example, opentelemetry. |
| | telemetry.sdk.version | Version of the telemetry SDK, for example, 1.4.1. |
### List of imported libraries [#list-of-imported-libraries]
`gem 'opentelemetry-api'`
The `opentelemetry-api` gem provides the core OpenTelemetry API for Ruby. It defines the basic concepts and interfaces for distributed tracing, such as spans, tracers, and context propagation. This gem is essential for instrumenting your Ruby app with OpenTelemetry.
`gem 'opentelemetry-sdk'`
The `opentelemetry-sdk` gem is the OpenTelemetry SDK for Ruby. It provides the implementation of the OpenTelemetry API, including the tracer provider, span processors, and exporters. This gem is responsible for managing the lifecycle of spans and sending them to the specified backend.
`gem 'opentelemetry-exporter-otlp'`
The `opentelemetry-exporter-otlp` gem is an exporter that sends trace data to a backend that supports the OpenTelemetry Protocol (OTLP), such as Axiom. It formats the trace data according to the OTLP standards and transmits it over HTTP or gRPC, ensuring compatibility and standardization in how telemetry data is sent across different systems and services.
`gem 'opentelemetry-instrumentation-rails'`
The `opentelemetry-instrumentation-rails` gem provides automatic instrumentation for Ruby on Rails apps. It integrates with various aspects of a Rails app, such as controllers, views, and database queries, to capture relevant trace data without requiring manual instrumentation. This gem simplifies the process of adding tracing to your Rails app.
`gem 'opentelemetry-instrumentation-http'`
The `opentelemetry-instrumentation-http` gem provides automatic instrumentation for HTTP requests made using the `Net::HTTP` library. It captures trace data for outgoing HTTP requests, including request headers, response status, and timing information. This gem helps in tracing the external dependencies of your app.
`gem 'opentelemetry-instrumentation-active_record', require: false`
The `opentelemetry-instrumentation-active_record` gem provides automatic instrumentation for ActiveRecord, the Object-Relational Mapping (ORM) library used in Ruby on Rails. It captures trace data for database queries, including the SQL statements executed and their duration. This gem helps in identifying performance bottlenecks related to database interactions.
`gem 'opentelemetry-instrumentation-all'`
The `opentelemetry-instrumentation-all` gem is a meta-gem that includes all the available instrumentation libraries for OpenTelemetry in Ruby. It provides a convenient way to install and configure multiple instrumentation libraries at once, covering various aspects of your app, such as HTTP requests, database queries, and external libraries. This gem simplifies the setup process and ensures comprehensive tracing coverage for your Ruby app.
---
# Axiom transport for Pino logger
Source: https://axiom.co/docs/guides/pino
## Install SDK [#install-sdk]
To install the SDK, run the following:
```shell
npm install @axiomhq/pino
```
## Create Pino logger [#create-pino-logger]
The example below creates a Pino logger with Axiom configured. Set the `edge` option to the edge domain that matches the region your dataset lives in — see [Configure region](#configure-region) for the full list.
```ts EU Central 1
import pino from 'pino';
const logger = pino(
{ level: 'info' },
pino.transport({
target: '@axiomhq/pino',
options: {
dataset: process.env.AXIOM_DATASET,
token: process.env.AXIOM_TOKEN,
edge: 'eu-central-1.aws.edge.axiom.co',
},
}),
);
```
```ts US East 1
import pino from 'pino';
const logger = pino(
{ level: 'info' },
pino.transport({
target: '@axiomhq/pino',
options: {
dataset: process.env.AXIOM_DATASET,
token: process.env.AXIOM_TOKEN,
edge: 'us-east-1.aws.edge.axiom.co',
},
}),
);
```
After setting up the Axiom transport for Pino, use the logger as usual:
```js
logger.info('Hello from Pino!');
```
## Configure region [#configure-region]
Set the `edge` option on the transport to the edge domain for your Axiom deployment.
| Edge deployment | Base domain for ingest and query |
| ------------------ | -------------------------------- |
| US East 1 (AWS) | `us-east-1.aws.edge.axiom.co` |
| EU Central 1 (AWS) | `eu-central-1.aws.edge.axiom.co` |
Always use the `edge` option to target a region. Don't put a regional hostname in `url` — `url` is reserved for non-ingest API operations and will not route ingest correctly.
## Transport options [#transport-options]
| Option | Required | Description |
| --------- | -------- | ------------------------------------------------------------------------------------------------------------------ |
| `dataset` | yes | The Axiom dataset to ingest logs into. |
| `token` | yes | An Axiom API or personal token with `ingest` permission for the dataset. |
| `edge` | no | Edge domain for ingest, without scheme. Example: `eu-central-1.aws.edge.axiom.co`. Use this to target a region. |
| `edgeUrl` | no | Full edge URL (with scheme). Takes precedence over `edge` if both are set. Useful for self-hosted or proxy setups. |
| `url` | no | Base URL for non-ingest API operations. Only needed if you call other Axiom APIs from the same client. |
## Examples [#examples]
For more examples, see the [examples in GitHub](https://github.com/axiomhq/axiom-js/tree/main/examples/pino).
---
# Send data from Python app to Axiom
Source: https://axiom.co/docs/guides/python
To send data from a Python app to Axiom, use the Axiom Python SDK.
The Axiom Python SDK is an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/axiom-py).
## Install SDK [#install-sdk]
```shell Linux / MacOS
python3 -m pip install axiom-py
```
```shell Windows
py -m pip install axiom-py
```
```shell pip
pip3 install axiom-py
```
If you use the [Axiom CLI](/reference/cli), run `eval $(axiom config export -f)` to configure your environment variables. Otherwise, [create an API token](/reference/tokens) and export it as `AXIOM_TOKEN`.
You can also configure the client using options passed to the client constructor:
```py
import axiom_py
client = axiom_py.Client("API_TOKEN")
```
## Use client [#use-client]
```py
import axiom_py
client = axiom_py.Client()
client.ingest_events(
dataset="DATASET_NAME",
events=[
{"foo": "bar"},
{"bar": "baz"},
])
client.query(r"['DATASET_NAME'] | where foo == 'bar' | limit 100")
```
For more examples, see the [examples in GitHub](https://github.com/axiomhq/axiom-py/tree/main/examples/client_example.py).
## Configure region [#configure-region]
By default, the client sends data to `api.axiom.co`. To target a specific edge region, pass the `edge` argument with the edge domain that matches the region your dataset lives in:
```py EU Central 1
import axiom_py
client = axiom_py.Client(
token="xaat-your-api-token",
edge="eu-central-1.aws.edge.axiom.co",
)
```
```py US East 1
import axiom_py
client = axiom_py.Client(
token="xaat-your-api-token",
edge="us-east-1.aws.edge.axiom.co",
)
```
The following edge domains are available:
| Edge deployment | Base domain for ingest and query |
| ------------------ | -------------------------------- |
| US East 1 (AWS) | `us-east-1.aws.edge.axiom.co` |
| EU Central 1 (AWS) | `eu-central-1.aws.edge.axiom.co` |
For more information about edge deployments, see [Edge deployments](/reference/edge-deployments).
To point at a custom edge endpoint such as a proxy or load balancer, use `edge_url="https://your-edge-host"` instead. `edge_url` takes precedence over `edge` if both are set.
Edge endpoints require an API token (`xaat-`), not a personal token (`xapt-`). Passing a personal token with edge configuration raises an error.
Edge configuration must be passed explicitly when you create the client. Unlike `token` and `org_id`, the `edge` and `edge_url` arguments are not read from environment variables.
## Example with `AxiomHandler` [#example-with-axiomhandler]
The example below uses `AxiomHandler` to send logs from the `logging` module to Axiom:
```python
import axiom_py
from axiom_py.logging import AxiomHandler
import logging
def setup_logger():
client = axiom_py.Client()
handler = AxiomHandler(client, "DATASET_NAME")
logging.getLogger().addHandler(handler)
```
For a full example, see [GitHub](https://github.com/axiomhq/axiom-py/tree/main/examples/logger_example.py).
## Example with `structlog` [#example-with-structlog]
The example below uses [structlog](https://github.com/hynek/structlog) to send logs to Axiom. structlog isn't a dependency of the Axiom Python SDK, so install it separately with `pip install structlog`.
`AxiomProcessor` passes the event dictionary on unchanged so that later processors can run. Place a renderer such as `structlog.dev.ConsoleRenderer()` after it as the last processor. Without a renderer, structlog's logger receives a dictionary and raises a `TypeError`.
```python
from axiom_py import Client
from axiom_py.structlog import AxiomProcessor
import structlog
def setup_logger():
client = Client()
structlog.configure(
processors=[
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt="iso", key="_time"),
AxiomProcessor(client, "DATASET_NAME"),
structlog.dev.ConsoleRenderer(),
]
)
```
For a full example, see [GitHub](https://github.com/axiomhq/axiom-py/tree/main/examples/structlog_example.py).
---
# Send data from Rust app to Axiom
Source: https://axiom.co/docs/guides/rust
To send data from a Rust app to Axiom, use the Axiom Rust SDK.
The Axiom Rust SDK is an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/axiom-rs).
## Install SDK [#install-sdk]
Add the following to your `Cargo.toml`:
```toml
[dependencies]
axiom-rs = "VERSION"
```
Replace `VERSION` with the latest version number specified on the [GitHub Releases](https://github.com/axiomhq/axiom-rs/releases) page. For example, `0.11.0`.
If you use the [Axiom CLI](/reference/cli), run `eval $(axiom config export -f)` to configure your environment variables. Otherwise, [create an API token](/reference/tokens) and export it as `AXIOM_TOKEN`.
## Use client [#use-client]
```rust
use axiom_rs::Client;
use serde_json::json;
#[tokio::main]
async fn main() -> Result<(), Box> {
// Build your client by providing a personal token and an org id:
let client = Client::builder()
.with_token("API_TOKEN")
.build()?;
// Alternatively, auto-configure the client from the environment variable AXIOM_TOKEN:
let client = Client::new()?;
client.datasets().create("DATASET_NAME", "").await?;
client
.ingest(
"DATASET_NAME",
vec![json!({
"foo": "bar",
})],
)
.await?;
let res = client
.query(r#"['DATASET_NAME'] | where foo == "bar" | limit 100"#, None)
.await?;
println!("{:?}", res);
client.datasets().delete("DATASET_NAME").await?;
Ok(())
}
```
For more examples, see the [examples in GitHub](https://github.com/axiomhq/axiom-rs/tree/main/examples).
## Configure region [#configure-region]
By default, the client sends data to `api.axiom.co`. To target a specific edge region, add the `with_edge` method to the builder with the edge domain that matches the region your dataset lives in:
```rust EU Central 1
let client = Client::builder()
.with_token("xaat-your-api-token")
.with_edge("eu-central-1.aws.edge.axiom.co")
.build()?;
```
```rust US East 1
let client = Client::builder()
.with_token("xaat-your-api-token")
.with_edge("us-east-1.aws.edge.axiom.co")
.build()?;
```
The following edge domains are available:
| Edge deployment | Base domain for ingest and query |
| ------------------ | -------------------------------- |
| US East 1 (AWS) | `us-east-1.aws.edge.axiom.co` |
| EU Central 1 (AWS) | `eu-central-1.aws.edge.axiom.co` |
For more information about edge deployments, see [Edge deployments](/reference/edge-deployments).
You can also configure the region without changing code by exporting environment variables. When you build the client with `Client::new()`, these are read automatically:
```sh
export AXIOM_EDGE="eu-central-1.aws.edge.axiom.co"
# or, for a full URL (takes precedence over AXIOM_EDGE):
export AXIOM_EDGE_URL="https://eu-central-1.aws.edge.axiom.co"
```
To point at a custom edge endpoint such as a proxy or load balancer, use `.with_edge_url("https://your-edge-host")`. `with_edge_url` takes precedence over `with_edge` if both are set.
Edge endpoints require an API token (`xaat-`), not a personal token (`xapt-`). Ingesting with a personal token against an edge endpoint returns a `PersonalTokenNotSupportedForEdge` error.
## Optional features [#optional-features]
You can use the [Cargo features](https://doc.rust-lang.org/stable/cargo/reference/features.html#the-features-section):
* `default-tls`: Provides TLS support to connect over HTTPS. Enabled by default.
* `native-tls`: Enables TLS functionality provided by `native-tls`.
* `rustls-tls`: Enables TLS functionality provided by `rustls`.
* `tokio`: Enables usage with the `tokio` runtime. Enabled by default.
* `async-std`: Enables usage with the `async-std` runtime.
---
# Send logs from Apache Log4j to Axiom
Source: https://axiom.co/docs/guides/send-logs-from-apache-log4j
Log4j is a Java logging framework developed by the Apache Software Foundation and widely used in the Java community. This page covers how to get started with Log4j, configure it to forward log messages to Fluentd, and send logs to Axiom.
* [Install JDK 11](https://www.oracle.com/java/technologies/java-se-glance.html) or later
* [Install Maven](https://maven.apache.org/download.cgi)
* [Install Fluentd](https://www.fluentd.org/download)
* [Install Docker](https://docs.docker.com/get-docker/)
## Configure Log4j [#configure-log4j]
Log4j is a flexible and powerful logging framework for Java applications. To use Log4j in your project, add the necessary dependencies to your `pom.xml` file. The dependencies required for Log4j include `log4j-core`, `log4j-api`, and `log4j-slf4j2-impl` for logging capability, and `jackson-databind` for JSON support.
1. Create a new Maven project:
```bash
mvn archetype:generate -DgroupId=com.example -DartifactId=log4j-axiom-test -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
cd log4j-axiom-test
```
2. Open the `pom.xml` file and replace its contents with the following:
```xml
4.0.0
com.example
log4j-axiom-test
jar
1.0-SNAPSHOT
log4j-axiom-test
http://maven.apache.org
11
11
2.19.0
junit
junit
4.12
test
org.apache.logging.log4j
log4j-core
${log4j.version}
org.apache.logging.log4j
log4j-api
${log4j.version}
org.apache.logging.log4j
log4j-slf4j2-impl
${log4j.version}
com.fasterxml.jackson.core
jackson-databind
2.13.0
org.apache.maven.plugins
maven-shade-plugin
3.2.4
package
shade
com.example.App
false
```
This `pom.xml` file includes the necessary Log4j dependencies and configures the Maven Shade plugin to create an executable JAR file.
3. Create a new file named `log4j2.xml` in your root directory and add the following content:
```xml
```
This configuration sets up two appenders:
* A Socket appender that sends logs to Fluentd, running on `localhost:24224`. Is uses JSON format for the log messages, which makes it easier to parse and analyze the logs later in Axiom.
* A Console appender that prints logs to the standard output,
## Set log level [#set-log-level]
Log4j supports various log levels, allowing you to control the verbosity of your logs. The main log levels, in order of increasing severity, are the following:
* `TRACE`: Fine-grained information for debugging.
* `DEBUG`: General debugging information.
* `INFO`: Informational messages.
* `WARN`: Indications of potential problems.
* `ERROR`: Error events that might still allow the app to continue running.
* `FATAL`: Severe error events that might lead the app to cancel.
In the configuration above, the root logger level is set to INFO which means it logs messages at INFO level and above (WARN, ERROR, and FATAL).
To set the log level, create a simple Java class to demonstrate these log levels. Create a new file named `App.java` in the `src/main/java/com/example` directory with the following content:
```java
package com.example;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.Level;
import java.util.Random;
public class App {
// Define loggers for different purposes
private static final Logger logger = LogManager.getLogger(App.class);
private static final Logger securityLogger = LogManager.getLogger("SecurityLogger");
private static final Logger performanceLogger = LogManager.getLogger("PerformanceLogger");
public static void main(String[] args) {
// Configure logging levels programmatically
configureLogging();
Random random = new Random();
// Infinite loop to continuously generate log events
while (true) {
try {
// Simulate various logging scenarios
simulateUserActivity(random);
simulateDatabaseOperations(random);
simulateSecurityEvents(random);
simulatePerformanceMetrics(random);
// Simulate a critical error with 10% probability
if (random.nextInt(10) == 0) {
throw new RuntimeException("Simulated critical error");
}
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
logger.warn("Sleep interrupted", e);
} catch (Exception e) {
logger.error("Critical error occurred", e);
} finally {
// Clear thread context after each iteration
ThreadContext.clearAll();
}
}
}
private static void configureLogging() {
// Set root logger level to DEBUG
Configurator.setRootLevel(Level.DEBUG);
// Set custom logger levels
Configurator.setLevel("SecurityLogger", Level.INFO);
Configurator.setLevel("PerformanceLogger", Level.TRACE);
}
// Simulate user activities and log them
private static void simulateUserActivity(Random random) {
String[] users = {"Alice", "Bob", "Charlie", "David"};
String[] actions = {"login", "logout", "view_profile", "update_settings"};
String user = users[random.nextInt(users.length)];
String action = actions[random.nextInt(actions.length)];
// Add user and action to thread context
ThreadContext.put("user", user);
ThreadContext.put("action", action);
// Log different user actions with appropriate levels
switch (action) {
case "login":
logger.info("User logged in successfully");
break;
case "logout":
logger.info("User logged out");
break;
case "view_profile":
logger.debug("User viewed their profile");
break;
case "update_settings":
logger.info("User updated their settings");
break;
}
}
// Simulate database operations and log them
private static void simulateDatabaseOperations(Random random) {
String[] operations = {"select", "insert", "update", "delete"};
String operation = operations[random.nextInt(operations.length)];
long duration = random.nextInt(1000);
// Add operation and duration to thread context
ThreadContext.put("operation", operation);
ThreadContext.put("duration", String.valueOf(duration));
// Log slow database operations as warnings
if (duration > 500) {
logger.warn("Slow database operation detected");
} else {
logger.debug("Database operation completed");
}
// Simulate database connection loss with 5% probability
if (random.nextInt(20) == 0) {
logger.error("Database connection lost", new SQLException("Connection timed out"));
}
}
// Simulate security events and log them
private static void simulateSecurityEvents(Random random) {
String[] events = {"failed_login", "password_change", "role_change", "suspicious_activity"};
String event = events[random.nextInt(events.length)];
ThreadContext.put("security_event", event);
// Log different security events with appropriate levels
switch (event) {
case "failed_login":
securityLogger.warn("Failed login attempt");
break;
case "password_change":
securityLogger.info("User changed their password");
break;
case "role_change":
securityLogger.info("User role was modified");
break;
case "suspicious_activity":
securityLogger.error("Suspicious activity detected", new SecurityException("Potential breach attempt"));
break;
}
}
// Simulate performance metrics and log them
private static void simulatePerformanceMetrics(Random random) {
String[] metrics = {"cpu_usage", "memory_usage", "disk_io", "network_latency"};
String metric = metrics[random.nextInt(metrics.length)];
double value = random.nextDouble() * 100;
// Add metric and value to thread context
ThreadContext.put("metric", metric);
ThreadContext.put("value", String.format("%.2f", value));
// Log high resource usage as warnings
if (value > 80) {
performanceLogger.warn("High resource usage detected");
} else {
performanceLogger.trace("Performance metric recorded");
}
}
// Custom exception classes for simulating errors
private static class SQLException extends Exception {
public SQLException(String message) {
super(message);
}
}
private static class SecurityException extends Exception {
public SecurityException(String message) {
super(message);
}
}
}
```
This class demonstrates the use of different log levels and also shows how to add context to your logs using `ThreadContext`.
## Forward log messages to Fluentd [#forward-log-messages-to-fluentd]
Fluentd is a popular open-source data collector used to forward logs from Log4j to Axiom. The Log4j configuration is already set up to send logs to Fluentd using the Socket appender. Fluentd acts as a unified logging layer, allowing you to collect, process, and forward logs from various sources to different destinations.
### Configure the Fluentd.conf file [#configure-the-fluentdconf-file]
To configure Fluentd, create a configuration file. Create a new file named `fluentd.conf` in your project root directory with the following content:
```xml
@type forward
bind 0.0.0.0
port 24224
@type multi_format
format json
time_key timeMillis
time_type string
time_format %Q
@type record_transformer
tag java.log4j
@type http
endpoint https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME
headers {"Authorization":"Bearer API_TOKEN"}
json_array true
@type memory
flush_interval 5s
chunk_limit_size 5m
total_limit_size 10m
@type json
```
This configuration does the following:
1. Set up a forward input plugin to receive logs from Log4j.
2. Add a `java.log4j` tag to all logs.
3. Forward the logs to Axiom using the HTTP output plugin.
### Create the Dockerfile [#create-the-dockerfile]
To simplify the deployment of the Java app and Fluentd, use Docker. Create a new file named `Dockerfile` in your project root directory with the following content:
```yaml
# Build stage
FROM maven:3.8.1-openjdk-11-slim AS build
WORKDIR /usr/src/app
COPY pom.xml .
COPY src ./src
COPY log4j2.xml .
RUN mvn clean package
# Runtime stage
FROM openjdk:11-jre-slim
WORKDIR /usr/src/app
RUN apt-get update && \
apt-get install -y --no-install-recommends \
ruby \
ruby-dev \
build-essential && \
gem install fluentd --no-document && \
fluent-gem install fluent-plugin-multi-format-parser && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
COPY --from=build /usr/src/app/target/log4j-axiom-test-1.0-SNAPSHOT.jar .
COPY fluentd.conf /etc/fluent/fluent.conf
COPY log4j2.xml .
# Create startup script
RUN echo '#!/bin/sh\n\
fluentd -c /etc/fluent/fluent.conf &\n\
sleep 5\n\
java -Dlog4j.configurationFile=log4j2.xml -jar log4j-axiom-test-1.0-SNAPSHOT.jar\n'\
> /usr/src/app/start.sh && chmod +x /usr/src/app/start.sh
EXPOSE 24224
CMD ["/usr/src/app/start.sh"]
```
This Dockerfile does the following:
1. Build the Java app.
2. Set up a runtime environment with Java and Fluentd.
3. Copy the necessary files and configurations.
4. Create a startup script to run both Fluentd and the Java app.
### Build and run the Dockerfile [#build-and-run-the-dockerfile]
1. To build the Docker image, run the following command in your project root directory:
```bash
docker build -t log4j-axiom-test .
```
2. Run the container with the following:
```bash
docker run -p 24224:24224 log4j-axiom-test
```
This command starts the container, running both Fluentd and your Java app.
## View logs in Axiom [#view-logs-in-axiom]
Now that your app is running and sending logs to Axiom, you can view them in the Axiom dashboard. Log in to your Axiom account and go to the dataset you specified in the Fluentd configuration.
Logs appear in real-time, with various log levels and context information added.
## Logging in Log4j best practices [#logging-in-log4j-best-practices]
* Use appropriate log levels: Reserve ERROR and FATAL for serious issues, use WARN for potential problems, and INFO for general app flow.
* Include context: Add relevant information to your logs using ThreadContext or by including important variables in your log messages.
* Use structured logging: Log in JSON format to make it easier to parse, and later, analyze the logs using [APL](https://axiom.co/docs/apl/introduction).
* Log actionable information: Include enough detail in your logs to understand and potentially reproduce issues.
* Use parameterized logging: Instead of string concatenation, use Log4j’s support for parameterized messages to improve performance.
* Configure appenders appropriately: Use asynchronous appenders for better performance in high-throughput scenarios.
* Regularly review and maintain your logs: Periodically check your logging configuration and the logs themselves to ensure they’re providing value.
---
# Send logs from a .NET app
Source: https://axiom.co/docs/guides/send-logs-from-dotnet
* [Install the .NET SDK](https://dotnet.microsoft.com/download).
## Option 1: Using HTTP Client [#option-1-using-http-client]
### Create a new .NET project [#create-a-new-net-project]
Create a new .NET project. In your terminal, go to the directory where you want to create your project. Run the following command to create a new console app named `AxiomLogs`.
```bash
dotnet new console -n AxiomLogs
```
### Install packages [#install-packages]
Install the packages for your project. Use the `Microsoft.AspNet.WebApi.Client` package to make HTTP requests to the Axiom API. Run the following command to install the package:
```bash
dotnet add package Microsoft.AspNet.WebApi.Client
```
### Configure the Axiom logger [#configure-the-axiom-logger]
Create a class to handle logging to Axiom. Create a new file named `AxiomLogger.cs` in your project directory with the following content:
```csharp
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public static class AxiomLogger
{
public static async Task LogToAxiom(string message, string logLevel)
{
// Create an instance of HttpClient to make HTTP requests
var client = new HttpClient();
// Specify the Axiom dataset name and construct the API endpoint URL
var datasetName = "DATASET_NAME";
var axiomEdgeDomain = "AXIOM_DOMAIN";
var axiomUri = $"https://{axiomEdgeDomain}/v1/ingest/{datasetName}";
// Replace with your Axiom API token
var apiToken = "API_TOKEN"; // Ensure your API token is correct
// Create an array of log entries, including the timestamp, message, and log level
var logEntries = new[]
{
new
{
timestamp = DateTime.UtcNow.ToString("o"),
message = message,
level = logLevel
}
};
// Serialize the log entries to JSON format using System.Text.Json.JsonSerializer
var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(logEntries), Encoding.UTF8, "application/json");
// Set the authorization header with the Axiom API token
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiToken);
// Make a POST request to the Axiom API endpoint with the serialized log entries
var response = await client.PostAsync(axiomUri, content);
// Check the response status code
if (!response.IsSuccessStatusCode)
{
// If the response isn’t successful, print the error details
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Failed to send log: {response.StatusCode}\n{responseBody}");
}
else
{
// If the response is successful, print "Log sent successfully."
Console.WriteLine("Log sent successfully.");
}
}
}
```
### Configure the main program [#configure-the-main-program]
Now that the Axiom logger is in place, update the main program so it can be used. Open the `Program.cs` file and replace its contents with the following code:
```csharp
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Log the application startup event with an "INFO" log level
await AxiomLogger.LogToAxiom("Application started", "INFO");
// Call the SimulateOperations method to simulate various application operations
await SimulateOperations();
// Log the .NET runtime version information with an "INFO" log level
await AxiomLogger.LogToAxiom($"CLR version: {Environment.Version}", "INFO");
// Log the application shutdown event with an "INFO" log level
await AxiomLogger.LogToAxiom("Application shutting down", "INFO");
}
static async Task SimulateOperations()
{
// Log the start of operations with a "DEBUG" log level
await AxiomLogger.LogToAxiom("Starting operations", "DEBUG");
// Log the database connection event with a "DEBUG" log level
await AxiomLogger.LogToAxiom("Connecting to database", "DEBUG");
await Task.Delay(500); // Simulated delay
// Log the successful database connection with an "INFO" log level
await AxiomLogger.LogToAxiom("Connected to database successfully", "INFO");
// Log the user data retrieval event with a "DEBUG" log level
await AxiomLogger.LogToAxiom("Retrieving user data", "DEBUG");
await Task.Delay(1000);
// Log the number of retrieved user records with an "INFO" log level
await AxiomLogger.LogToAxiom("Retrieved 100 user records", "INFO");
// Log the user preference update event with a "DEBUG" log level
await AxiomLogger.LogToAxiom("Updating user preferences", "DEBUG");
await Task.Delay(800);
// Log the successful user preference update with an "INFO" log level
await AxiomLogger.LogToAxiom("Updated user preferences successfully", "INFO");
try
{
// Log the payment processing event with a "DEBUG" log level
await AxiomLogger.LogToAxiom("Processing payments", "DEBUG");
await Task.Delay(1500);
// Intentionally throw an exception to demonstrate error logging
throw new Exception("Payment gateway unavailable");
}
catch (Exception ex)
{
// Log the payment processing failure with an "ERROR" log level
await AxiomLogger.LogToAxiom($"Payment processing failed: {ex.Message}", "ERROR");
}
// Log the email notification sending event with a "DEBUG" log level
await AxiomLogger.LogToAxiom("Sending email notifications", "DEBUG");
await Task.Delay(1200);
// Log the number of sent email notifications with an "INFO" log level
await AxiomLogger.LogToAxiom("Sent 50 email notifications", "INFO");
// Log the high memory usage detection with a "WARN" log level
await AxiomLogger.LogToAxiom("Detected high memory usage", "WARN");
await Task.Delay(500);
// Log the memory usage normalization with an "INFO" log level
await AxiomLogger.LogToAxiom("Memory usage normalized", "INFO");
// Log the completion of operations with a "DEBUG" log level
await AxiomLogger.LogToAxiom("Operations completed", "DEBUG");
}
}
```
This code simulates various app operations and logs messages at different levels (DEBUG, INFO, WARN, ERROR) to Axiom.
### Project file configuration [#project-file-configuration]
Ensure your `axiomlogs.csproj` file is configured with the package reference. The file should look like this:
```xml
Exe
net6.0
enable
enable
```
### Build and run the app [#build-and-run-the-app]
To build and run the app, go to the project directory in your terminal and run the following command:
```bash
dotnet build
dotnet run
```
This command builds the project and runs the app. You see the log messages being sent to Axiom, and the console displays `Log sent successfully.` for each log entry.
## Option 2: Using Serilog [#option-2-using-serilog]
### Install Serilog Packages [#install-serilog-packages]
Add Serilog and the necessary extensions to your project. You need the `Serilog`, `Serilog.Sinks.Http`, `Serilog.Formatting.Elasticsearch` and `Serilog.Formatting.Json` packages.
```bash
dotnet add package Serilog
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.Http
dotnet add package Serilog.Formatting.Elasticsearch
dotnet add package Microsoft.Extensions.Configuration
```
### Configure Serilog [#configure-serilog]
In your `Program.cs` or a startup configuration file, set up Serilog to use the HTTP sink. Configure the sink to point to the Axiom ingestion API endpoint.
```csharp
using Serilog;
using Serilog.Formatting.Elasticsearch;
using Serilog.Sinks.Http;
using System.Net.Http;
using System.Net.Http.Headers;
using System.IO;
using Microsoft.Extensions.Configuration;
public class AxiomConfig
{
public const string DatasetName = "DATASET_NAME";
public const string ApiToken = "API_TOKEN";
public const string ApiUrl = "https://AXIOM_DOMAIN/v1";
}
public class AxiomHttpClient : IHttpClient
{
private readonly HttpClient _httpClient;
public AxiomHttpClient()
{
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", AxiomConfig.ApiToken);
}
public void Configure(IConfiguration configuration)
{
}
public async Task PostAsync(string requestUri, Stream contentStream, CancellationToken cancellationToken = default)
{
var content = new StreamContent(contentStream);
content.Headers.Add("Content-Type", "application/json");
return await _httpClient.PostAsync(requestUri, content, cancellationToken).ConfigureAwait(false);
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
public class Program
{
public static async Task Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.Http(
requestUri: $"{AxiomConfig.ApiUrl}/ingest/{AxiomConfig.DatasetName}",
queueLimitBytes: null,
textFormatter: new ElasticsearchJsonFormatter(renderMessageTemplate: false, inlineFields: true),
httpClient: new AxiomHttpClient()
)
.CreateLogger();
try
{
Log.Information("Application started on .NET 8");
await SimulateOperations();
Log.Information($"Runtime version: {Environment.Version}");
Log.Information("Application shutting down");
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
await Log.CloseAndFlushAsync();
}
}
static async Task SimulateOperations()
{
Log.Debug("Starting operations");
Log.Debug("Connecting to database");
await Task.Delay(500);
Log.Information("Connected to database successfully");
Log.Debug("Retrieving user data");
await Task.Delay(1000);
Log.Information("Retrieved 100 user records");
Log.Debug("Updating user preferences");
await Task.Delay(800);
Log.Information("Updated user preferences successfully");
try
{
Log.Debug("Processing payments");
await Task.Delay(1500);
throw new Exception("Payment gateway unavailable");
}
catch (Exception ex)
{
Log.Error(ex, "Payment processing failed: {ErrorMessage}", ex.Message);
}
Log.Debug("Sending email notifications");
await Task.Delay(1200);
Log.Information("Sent 50 email notifications");
Log.Warning("Detected high memory usage: {UsagePercentage}%", 85);
await Task.Delay(500);
Log.Information("Memory usage normalized");
Log.Debug("Operations completed");
}
}
```
### Project file configuration [#project-file-configuration-1]
Ensure your `axiomlogs.csproj` file is configured with the package references. The file should look like this:
```xml
Exe
net8.0
enable
enable
SerilogApp
SerilogApp
```
### Build and run the app [#build-and-run-the-app-1]
To build and run the app, go to the project directory in your terminal and run the following commands:
```bash
dotnet build
dotnet run
```
This command builds the project and runs the app. You see the log messages being sent to Axiom.
## Option 3: Using NLog [#option-3-using-nlog]
### Install NLog Packages [#install-nlog-packages]
You need NLog and potentially an extension for HTTP targets.
```bash
dotnet add package NLog
dotnet add package NLog.Web.AspNetCore
dotnet add package NLog.Targets.Http
```
### Configure NLog [#configure-nlog]
Set up NLog by creating an `NLog.config` file or configuring it programmatically. Here is an example configuration for `NLog` using an HTTP target:
```xml
```
### Configure the main program [#configure-the-main-program-1]
Update the main program to use `NLog`. In your `Program.cs` file:
```csharp
using NLog;
using NLog.Web;
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
class Program
{
static async Task Main(string[] args)
{
logger.Info("Application started");
await SimulateOperations();
logger.Info($"CLR version: {Environment.Version}");
logger.Info("Application shutting down");
}
static async Task SimulateOperations()
{
logger.Debug("Starting operations");
logger.Debug("Connecting to database");
await Task.Delay(500); // Simulated delay
logger.Info("Connected to database successfully");
logger.Debug("Retrieving user data");
await Task.Delay(1000);
logger.Info("Retrieved 100 user records");
logger.Debug("Updating user preferences");
await Task.Delay(800);
logger.Info("Updated user preferences successfully");
try
{
logger.Debug("Processing payments");
await Task.Delay(1500);
throw new Exception("Payment gateway unavailable");
}
catch (Exception ex)
{
logger.Error($"Payment processing failed: {ex.Message}");
}
logger.Debug("Sending email notifications");
await Task.Delay(1200);
logger.Info("Sent 50 email notifications");
logger.Warn("Detected high memory usage");
await Task.Delay(500);
logger.Info("Memory usage normalized");
logger.Debug("Operations completed");
}
}
```
### Project file configuration [#project-file-configuration-2]
Ensure your `axiomlogs.csproj` file is configured with the package references. The file should look like this:
```xml
Exe
net6.0
enable
enable
```
### Build and run the app [#build-and-run-the-app-2]
To build and run the app, go to the project directory in your terminal and run the following commands:
```bash
dotnet build
dotnet run
```
This command builds the project and runs the app. You should see the log messages being sent to Axiom.
## Best practices for logging [#best-practices-for-logging]
To make your logging more effective, consider the following best practices:
* Include relevant information such as user IDs, request details, and system state in your log messages to provide context when investigating issues.
* Use different log levels (DEBUG, INFO, WARN, ERROR) to categorize the severity and importance of log messages. This allows you to filter and analyze logs more effectively
* Use structured logging formats like JSON to make it easier to parse and analyze log data
## Conclusion [#conclusion]
This guide covers the steps to send logs from a C# .NET app to Axiom. By following these instructions and adhering to logging best practices, you can effectively monitor your app, diagnose issues, and gain valuable insights into its behavior.
---
# Send logs from Elixir to Axiom
Source: https://axiom.co/docs/guides/send-logs-from-elixir
This guide explains how to integrate Axiom as a logging solution in an Elixir app. Elixir’s `Logger` is built on the Erlang/OTP `:logger` framework, which lets you attach custom handlers to the logging pipeline. In this guide, you create a handler that receives every log event, buffers events in a GenServer, and forwards them in batches to the ingest endpoint of your Axiom [edge deployment](/reference/edge-deployments) using the [Req](https://hexdocs.pm/req) HTTP client.
* [Elixir](https://elixir-lang.org/install.html) 1.15 or later with Erlang/OTP 26 or later
* Familiarity with Mix and OTP applications
## Installation [#installation]
### Create an Elixir project [#create-an-elixir-project]
Create a new Mix project with a supervision tree. The `--sup` flag generates an `Application` module where you start the process that buffers log events.
```bash
mix new axiom_elixir_demo --sup
cd axiom_elixir_demo
```
### Add the HTTP client [#add-the-http-client]
Axiom doesn’t provide an Elixir SDK. Instead, this guide uses [Req](https://hexdocs.pm/req), a popular Elixir HTTP client, to call the Axiom ingest API directly. Req encodes request bodies as JSON with Jason, so you don’t need to add a JSON library yourself.
Open `mix.exs` and add `req` to the dependencies:
```elixir
defmodule AxiomElixirDemo.MixProject do
use Mix.Project
def project do
[
app: :axiom_elixir_demo,
version: "0.1.0",
elixir: "~> 1.15",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
def application do
[
extra_applications: [:logger],
mod: {AxiomElixirDemo.Application, []}
]
end
defp deps do
[
{:req, "~> 0.5"}
]
end
end
```
Fetch the dependencies:
```bash
mix deps.get
```
## Configure the Axiom connection [#configure-the-axiom-connection]
Mix evaluates `config/runtime.exs` when your app starts, including in releases, which makes it the right place to read secrets from environment variables. Create the file with the following content:
```elixir
import Config
config :axiom_elixir_demo, AxiomLogger,
token: System.fetch_env!("AXIOM_TOKEN"),
dataset: System.fetch_env!("AXIOM_DATASET"),
domain: System.fetch_env!("AXIOM_DOMAIN"),
batch_size: 100,
flush_interval: 2_000
```
Set the environment variables before you run the app:
```bash
export AXIOM_TOKEN=API_TOKEN
export AXIOM_DATASET=DATASET_NAME
export AXIOM_DOMAIN=AXIOM_DOMAIN
```
### Target your edge deployment [#target-your-edge-deployment]
Axiom ingests, stores, and queries your event data within the edge deployment your dataset lives in. `AXIOM_DOMAIN` is the base domain of that edge deployment, and the handler sends events to `https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME`. Axiom currently offers edge deployments in the US and in the EU:
For example, if your dataset lives in the `EU Central 1 (AWS)` edge deployment, set `AXIOM_DOMAIN` to `eu-central-1.aws.edge.axiom.co`. The handler then sends events to `https://eu-central-1.aws.edge.axiom.co/v1/ingest/DATASET_NAME`, and your event data is ingested, stored, and queried within the EU. For more information, including how to determine the edge deployment of your organization and how to create datasets in other edge deployments, see [Edge deployments](/reference/edge-deployments).
The `batch_size` and `flush_interval` options control how often the handler sends events to Axiom. With the values above, the handler sends a request when it has collected 100 events or when two seconds have passed since the last request, whichever comes first. Axiom accepts up to 10,000 events in a single request. For more information, see [Limits](/reference/limits).
## Getting started with log levels in Elixir [#getting-started-with-log-levels-in-elixir]
Elixir’s `Logger` supports the eight syslog severity levels. Starting with the most severe:
* **emergency**: Your app is unusable and needs immediate attention.
* **alert**: Similar to emergency, but less severe.
* **critical**: Critical errors within the main parts of your app.
* **error**: Error conditions in your app.
* **warning**: Something unusual happened that may need to be addressed later.
* **notice**: Important information, but not a warning or error.
* **info**: General updates about what your app is doing.
* **debug**: Detailed messages used while debugging.
Each level has a matching macro in the `Logger` module. Pass structured data as metadata in the second argument. The handler you build in this guide forwards that metadata to Axiom as fields.
```elixir
require Logger
Logger.debug("Checking details.")
Logger.info("User logged in.", user_id: "exampleUserId")
Logger.notice("User tried a feature.")
Logger.warning("Feature might not work as expected.")
Logger.error("Feature failed to load.", error_code: 500)
Logger.critical("Major issue with the app.")
Logger.alert("Immediate action needed.")
Logger.emergency("The app is down.")
```
Output in the console:
```text
00:30:05.795 [debug] Checking details.
00:30:05.800 [info] User logged in.
00:30:05.801 [notice] User tried a feature.
00:30:05.801 [warning] Feature might not work as expected.
00:30:05.801 [error] Feature failed to load.
00:30:05.801 [critical] Major issue with the app.
00:30:05.801 [alert] Immediate action needed.
00:30:05.801 [emergency] The app is down.
```
Elixir’s default log level is `:debug`, so every level reaches the handlers. To reduce noise in production, raise the level in your configuration with `config :logger, level: :info`.
## Creating the custom logger handler [#creating-the-custom-logger-handler]
The integration consists of two modules:
* `AxiomLogger.Handler` is an Erlang `:logger` handler. Its `log/2` callback runs in the process that emitted the log event, so it only converts the event into a map and hands it to the buffer.
* `AxiomLogger.Buffer` is a GenServer that collects events and sends them to Axiom in batches. Doing the HTTP work in a separate process means that logging never blocks your app.
### Handler [#handler]
Create `lib/axiom_logger/handler.ex` with the following content:
```elixir
defmodule AxiomLogger.Handler do
@moduledoc """
An Erlang `:logger` handler that converts log events into JSON-friendly maps
and hands them to `AxiomLogger.Buffer`, which batches them and sends them to Axiom.
"""
# Default metadata keys that are noise in Axiom.
@skip_metadata [:gl, :time, :report_cb, :erl_level, :initial_call, :process_label, :domain, :ancestors, :callers]
# Called by :logger when the handler is added.
def adding_handler(config), do: {:ok, config}
# Called by :logger when the handler is removed. Flush so nothing is lost on shutdown.
def removing_handler(_config), do: AxiomLogger.Buffer.flush()
# Never forward the buffer's own log events. This prevents infinite loops.
def log(%{meta: %{axiom_internal: true}}, _config), do: :ok
# Called by :logger in the process that emitted the log event, so keep it cheap:
# build the event and hand it to the buffer.
def log(%{level: level, msg: msg, meta: meta}, _config) do
AxiomLogger.Buffer.push(build_event(level, msg, meta))
end
defp build_event(level, msg, meta) do
timestamp =
meta
|> Map.get(:time, System.system_time(:microsecond))
|> DateTime.from_unix!(:microsecond)
|> DateTime.to_iso8601()
%{"_time" => timestamp, "level" => Atom.to_string(level), "metadata" => build_metadata(meta)}
|> put_message(msg)
end
# Plain string messages, for example Logger.info("User logged in.")
defp put_message(event, {:string, chardata}) do
Map.put(event, "message", IO.chardata_to_string(chardata))
end
# Structured reports, for example Logger.info(%{event: "order_placed", order_id: 42})
defp put_message(event, {:report, report}) when is_map(report) do
Map.put(event, "report", sanitize(report))
end
defp put_message(event, {:report, report}) when is_list(report) do
if Keyword.keyword?(report) do
Map.put(event, "report", report |> Map.new() |> sanitize())
else
Map.put(event, "message", inspect(report))
end
end
# Erlang-style format strings, for example :logger.info(~c"~p items", [3])
defp put_message(event, {format, args}) do
Map.put(event, "message", format |> :io_lib.format(args) |> IO.chardata_to_string())
rescue
_ -> Map.put(event, "message", inspect({format, args}))
end
defp build_metadata(meta) do
{mfa, meta} = Map.pop(meta, :mfa)
{file, meta} = Map.pop(meta, :file)
meta
|> Map.drop(@skip_metadata)
|> sanitize()
|> maybe_put("file", file && to_string(file))
|> put_mfa(mfa)
end
defp put_mfa(metadata, {module, function, arity}) do
Map.merge(metadata, %{"module" => inspect(module), "function" => "#{function}/#{arity}"})
end
defp put_mfa(metadata, _), do: metadata
defp maybe_put(map, _key, nil), do: map
defp maybe_put(map, key, value), do: Map.put(map, key, value)
# Convert any Elixir term into something the JSON encoder accepts.
defp sanitize(value) when is_binary(value) do
if String.valid?(value), do: value, else: inspect(value)
end
defp sanitize(value) when is_number(value) or is_boolean(value) or is_nil(value), do: value
defp sanitize(value) when is_atom(value), do: Atom.to_string(value)
defp sanitize(%DateTime{} = value), do: DateTime.to_iso8601(value)
defp sanitize(%NaiveDateTime{} = value), do: NaiveDateTime.to_iso8601(value)
defp sanitize(value) when is_struct(value), do: inspect(value)
defp sanitize(value) when is_map(value) do
Map.new(value, fn {key, val} -> {sanitize_key(key), sanitize(val)} end)
end
defp sanitize(value) when is_list(value) do
if value != [] and Keyword.keyword?(value) do
value |> Map.new() |> sanitize()
else
Enum.map(value, &sanitize/1)
end
end
# PIDs, references, tuples, functions, and ports
defp sanitize(value), do: inspect(value)
defp sanitize_key(key) when is_atom(key), do: Atom.to_string(key)
defp sanitize_key(key) when is_binary(key), do: key
defp sanitize_key(key), do: inspect(key)
end
```
How the handler works:
* **Timestamps**: The `:time` metadata holds the time of the log call in microseconds. The handler converts it to an ISO 8601 string in a field named `_time`, which Axiom uses as the timestamp of the event. Without this field, Axiom uses the time it received the event instead.
* **Messages and reports**: Plain string messages are sent in the `message` field. Structured reports, such as `Logger.info(%{event: "order_placed"})`, are sent as a `report` object so that you can query each key as a separate field.
* **Metadata**: Default metadata such as the module, function, line, file, and PID is sent in a `metadata` object together with any metadata you pass to the `Logger` calls. Values that JSON can’t represent, such as PIDs, references, and tuples, are converted to strings with `inspect/1`.
* **Loop prevention**: The buffer marks itself with the `axiom_internal` metadata key. The first `log/2` clause ignores events that carry this key, so errors logged by the buffer are never sent back to Axiom.
* **Shutdown**: When the handler is removed, `removing_handler/1` flushes the buffer so that the last events aren’t lost.
### Buffer [#buffer]
Create `lib/axiom_logger/buffer.ex` with the following content:
```elixir
defmodule AxiomLogger.Buffer do
@moduledoc """
Collects log events and sends them to the Axiom ingest API in batches.
Events are flushed when the batch reaches `:batch_size` events or when
`:flush_interval` milliseconds have passed, whichever comes first.
"""
use GenServer
require Logger
@default_batch_size 100
@default_flush_interval 2_000
def start_link(opts) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
@doc "Adds an event to the buffer. Never blocks the caller."
def push(event), do: GenServer.cast(__MODULE__, {:push, event})
@doc "Sends all buffered events immediately and waits for the request to finish."
def flush, do: GenServer.call(__MODULE__, :flush, 30_000)
@impl true
def init(opts) do
# Run terminate/2 on shutdown so the last batch is sent.
Process.flag(:trap_exit, true)
# Mark this process so AxiomLogger.Handler ignores anything it logs.
Logger.metadata(axiom_internal: true)
domain = Keyword.fetch!(opts, :domain)
dataset = Keyword.fetch!(opts, :dataset)
state = %{
url: "https://#{domain}/v1/ingest/#{URI.encode(dataset)}",
token: Keyword.fetch!(opts, :token),
batch_size: Keyword.get(opts, :batch_size, @default_batch_size),
flush_interval: Keyword.get(opts, :flush_interval, @default_flush_interval),
events: [],
count: 0
}
{:ok, schedule_flush(state)}
end
@impl true
def handle_cast({:push, event}, state) do
state = %{state | events: [event | state.events], count: state.count + 1}
if state.count >= state.batch_size do
{:noreply, do_flush(state)}
else
{:noreply, state}
end
end
@impl true
def handle_call(:flush, _from, state), do: {:reply, :ok, do_flush(state)}
@impl true
def handle_info(:flush, state), do: {:noreply, state |> do_flush() |> schedule_flush()}
@impl true
def terminate(_reason, state) do
do_flush(state)
:ok
end
defp schedule_flush(state) do
Process.send_after(self(), :flush, state.flush_interval)
state
end
defp do_flush(%{events: []} = state), do: state
defp do_flush(state) do
events = Enum.reverse(state.events)
# retry: :transient retries HTTP 408/429/5xx responses and connection errors.
case Req.post(state.url, json: events, auth: {:bearer, state.token}, retry: :transient) do
{:ok, %Req.Response{status: 200, body: %{"failed" => 0}}} ->
:ok
{:ok, %Req.Response{status: 200, body: body}} ->
Logger.warning("Axiom rejected some events: #{inspect(body["failures"])}")
{:ok, %Req.Response{status: status, body: body}} ->
Logger.error("Axiom ingest failed with HTTP #{status}: #{inspect(body)}")
{:error, error} ->
Logger.error("Axiom ingest request failed: #{Exception.message(error)}")
end
%{state | events: [], count: 0}
end
end
```
How the buffer works:
* **Endpoint**: Events are sent to `https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME`, the ingest endpoint of your [edge deployment](/reference/edge-deployments). The dataset name is URL-encoded.
* **Authentication**: The `auth: {:bearer, token}` option sets the `Authorization: Bearer API_TOKEN` header.
* **Payload**: The `json:` option encodes the list of events as a JSON array and sets the `Content-Type` header to `application/json`, which is the format the ingest endpoint expects.
* **Retries**: By default, Req only retries GET and HEAD requests. Setting `retry: :transient` also retries POST requests that fail with a connection error or with HTTP status 408, 429, 500, 502, 503, or 504.
* **Response**: A successful request returns HTTP 200 with a body that includes `ingested` and `failed` counts. The buffer logs a warning if Axiom rejects some events and an error if the request fails.
* **Shutdown**: The process traps exits so that `terminate/2` runs when the app stops and sends the remaining events.
## Attaching the handler [#attaching-the-handler]
Open `lib/axiom_elixir_demo/application.ex` and replace its content with the following:
```elixir
defmodule AxiomElixirDemo.Application do
@moduledoc false
use Application
@impl true
def start(_type, _args) do
children = [
{AxiomLogger.Buffer, Application.fetch_env!(:axiom_elixir_demo, AxiomLogger)}
]
opts = [strategy: :one_for_one, name: AxiomElixirDemo.Supervisor]
{:ok, pid} = Supervisor.start_link(children, opts)
# Attach the handler after the buffer process is running.
:ok = :logger.add_handler(:axiom, AxiomLogger.Handler, %{level: :debug})
{:ok, pid}
end
@impl true
def prep_stop(state) do
# Removing the handler flushes buffered events before the supervision tree stops.
:logger.remove_handler(:axiom)
state
end
end
```
The `start/2` callback starts the buffer under the supervisor first and then attaches the handler with `:logger.add_handler/3`. The `level: :debug` option sets the minimum level for this handler. The `prep_stop/1` callback removes the handler before the supervision tree shuts down, which flushes the remaining events.
## Creating the test module [#creating-the-test-module]
Replace the content of `lib/axiom_elixir_demo.ex` with a module that logs a message at every level:
```elixir
defmodule AxiomElixirDemo do
@moduledoc "Emits a log event at every level so you can see them arrive in Axiom."
require Logger
def run do
Logger.debug("Checking details.", action: "detail_check", status: "initiated")
Logger.info("User logged in.", user_id: "exampleUserId", method: "standard_login")
Logger.notice("User tried a feature.", feature: "experimental_feature_x", status: "trial")
Logger.warning("Feature might not work as expected.", feature: "experimental_feature", stage: "beta")
Logger.error("Feature failed to load.", feature: "feature_y", error_code: 500)
Logger.critical("Major issue with the app.", system: "payment_processing", error: "service_unavailable")
Logger.alert("Immediate action needed.", issue: "security", severity: "high")
Logger.emergency("The app is down.", system: "entire_application", status: "offline")
# Structured report: the map becomes the `report` field in Axiom.
Logger.info(%{event: "order_placed", order_id: 1234, total: 59.99, currency: "USD"})
# Send whatever is still buffered before the script exits.
AxiomLogger.Buffer.flush()
end
end
```
The final call to `AxiomLogger.Buffer.flush/0` sends the buffered events immediately. This is useful in scripts that exit right after logging. In a long-running app, the buffer flushes automatically.
## Run the app [#run-the-app]
Run the test module with Mix:
```bash
mix run -e "AxiomElixirDemo.run()"
```
You can also start an interactive session with `iex -S mix` and call `AxiomElixirDemo.run()` from there. If the environment variables aren’t set, the app fails to start with a `System.EnvError` that names the missing variable.
## View the logs in Axiom [#view-the-logs-in-axiom]
Open your dataset in Axiom. Each event has a `level` and a `message` field, and Axiom flattens the nested objects into fields such as `metadata.module`, `metadata.function`, `metadata.line`, and `metadata.user_id`. Structured reports appear as `report.event`, `report.order_id`, and so on.
For example, the following query lists the most severe events together with the module and line that logged them:
```kusto
['DATASET_NAME']
| where level in ("error", "critical", "alert", "emergency")
| project _time, level, message, ['metadata.module'], ['metadata.line']
| order by _time desc
```
## Conclusion [#conclusion]
This guide has introduced you to integrating Axiom for logging in Elixir apps. You’ve learned how to attach a custom `:logger` handler, batch events in a GenServer, and forward them to Axiom with Req. With this knowledge, you’re set to track errors and analyze structured log data from your Elixir apps in Axiom.
---
# Send logs from Erlang to Axiom
Source: https://axiom.co/docs/guides/send-logs-from-erlang
This guide explains how to integrate Axiom as a logging solution in an Erlang/OTP app. Erlang’s `logger` module lets you attach custom handlers to the logging pipeline. In this guide, you create a handler that converts each log event into a JSON-friendly map, and a `gen_server` that buffers the events and sends them in batches to the ingest endpoint of your Axiom [edge deployment](/reference/edge-deployments). The integration only uses libraries that ship with Erlang/OTP: `httpc` from `inets` for HTTP, `ssl` for TLS, and the `json` module for encoding.
* [Erlang/OTP](https://www.erlang.org/downloads) 27 or later. The `json` module used in this guide ships with OTP 27. On older releases, use a JSON library such as `jsx` or `thoas` instead.
* [rebar3](https://rebar3.org/docs/getting-started/)
## Installation [#installation]
### Create an Erlang app [#create-an-erlang-app]
Create a new OTP app with rebar3. The `app` template generates an `application` callback module and a top-level supervisor.
```bash
rebar3 new app axiom_erlang_demo
cd axiom_erlang_demo
```
### Declare the OTP applications you use [#declare-the-otp-applications-you-use]
The integration uses `inets` and `ssl`, which are part of Erlang/OTP. Open `src/axiom_erlang_demo.app.src` and add them to the `applications` list so that the runtime starts them before your app:
```erlang
{application, axiom_erlang_demo, [
{description, "Send logs from Erlang to Axiom"},
{vsn, "0.1.0"},
{registered, [axiom_logger_sender]},
{mod, {axiom_erlang_demo_app, []}},
{applications, [
kernel,
stdlib,
inets,
ssl
]},
{env, []},
{modules, []},
{licenses, ["Apache-2.0"]},
{links, []}
]}.
```
No third-party dependencies are needed, so `rebar.config` keeps an empty `deps` list.
## Configure the Axiom connection [#configure-the-axiom-connection]
### Environment variables [#environment-variables]
The supervisor you create later in this guide reads the connection settings from environment variables. Set them before you run the app:
```bash
export AXIOM_TOKEN=API_TOKEN
export AXIOM_DATASET=DATASET_NAME
export AXIOM_DOMAIN=AXIOM_DOMAIN
```
### Target your edge deployment [#target-your-edge-deployment]
Axiom ingests, stores, and queries your event data within the edge deployment your dataset lives in. `AXIOM_DOMAIN` is the base domain of that edge deployment, and the handler sends events to `https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME`. Axiom currently offers edge deployments in the US and in the EU:
For example, if your dataset lives in the `EU Central 1 (AWS)` edge deployment, set `AXIOM_DOMAIN` to `eu-central-1.aws.edge.axiom.co`. The handler then sends events to `https://eu-central-1.aws.edge.axiom.co/v1/ingest/DATASET_NAME`, and your event data is ingested, stored, and queried within the EU. For more information, including how to determine the edge deployment of your organization and how to create datasets in other edge deployments, see [Edge deployments](/reference/edge-deployments).
### Log level [#log-level]
The primary log level of the Erlang runtime defaults to `notice`, which means that `info` and `debug` events are discarded before any handler sees them. Create `config/sys.config` to lower the primary level, and to drop the supervisor progress reports that become visible at that level:
```erlang
[
{kernel, [
%% The primary log level defaults to notice. Lower it so info and
%% debug events reach the handlers.
{logger_level, debug},
%% At debug level the console also prints supervisor progress reports.
%% This primary filter keeps them out of every handler.
{logger, [
{filters, log, [{progress, {fun logger_filters:progress/2, stop}}]}
]}
]}
].
```
Tell rebar3 to load this file when you start a shell. Open `rebar.config` and update the `shell` section:
```erlang
{erl_opts, [debug_info]}.
{deps, []}.
{shell, [
{config, "config/sys.config"},
{apps, [axiom_erlang_demo]}
]}.
```
## Getting started with log levels in Erlang [#getting-started-with-log-levels-in-erlang]
Erlang’s `logger` supports the eight syslog severity levels. Starting with the most severe:
* **emergency**: Your app is unusable and needs immediate attention.
* **alert**: Similar to emergency, but less severe.
* **critical**: Critical errors within the main parts of your app.
* **error**: Error conditions in your app.
* **warning**: Something unusual happened that may need to be addressed later.
* **notice**: Important information, but not a warning or error.
* **info**: General updates about what your app is doing.
* **debug**: Detailed messages used while debugging.
Each level has a matching `?LOG_*` macro in `logger.hrl`. Pass structured data as a metadata map in the second argument. The handler you build in this guide forwards that metadata to Axiom as fields.
```erlang
-include_lib("kernel/include/logger.hrl").
?LOG_DEBUG("Checking details."),
?LOG_INFO("User logged in.", #{user_id => <<"exampleUserId">>}),
?LOG_NOTICE("User tried a feature."),
?LOG_WARNING("Feature might not work as expected."),
?LOG_ERROR("Feature failed to load.", #{error_code => 500}),
?LOG_CRITICAL("Major issue with the app."),
?LOG_ALERT("Immediate action needed."),
?LOG_EMERGENCY("The app is down.").
```
The `logger` module also provides plain functions such as `logger:info/2` that accept the same arguments. The functions don’t know where they were called from, so the events they produce only carry the PID of the calling process. The macros add the module, function, line, and file to the metadata, which is why this guide uses them.
Output in the console from the default handler:
```text
=DEBUG REPORT==== 7-Sep-2026::00:42:15.454264 ===
Checking details.
=INFO REPORT==== 7-Sep-2026::00:42:15.465323 ===
User logged in.
=NOTICE REPORT==== 7-Sep-2026::00:42:15.465353 ===
User tried a feature.
=WARNING REPORT==== 7-Sep-2026::00:42:15.465378 ===
Feature might not work as expected.
=ERROR REPORT==== 7-Sep-2026::00:42:15.465404 ===
Feature failed to load.
=CRITICAL REPORT==== 7-Sep-2026::00:42:15.465423 ===
Major issue with the app.
=ALERT REPORT==== 7-Sep-2026::00:42:15.465437 ===
Immediate action needed.
=EMERGENCY REPORT==== 7-Sep-2026::00:42:15.465446 ===
The app is down.
```
## Creating the custom logger handler [#creating-the-custom-logger-handler]
The integration consists of two modules:
* `axiom_logger_h` is a `logger` handler. Its `log/2` callback runs in the process that emitted the log event, so it only converts the event into a map and hands it to the sender.
* `axiom_logger_sender` is a `gen_server` that collects events and sends them to Axiom in batches. Doing the HTTP work in a separate process means that logging never blocks your app.
### Handler [#handler]
Create `src/axiom_logger_h.erl` with the following content:
```erlang
%% A logger handler that converts log events into JSON-friendly maps and hands
%% them to axiom_logger_sender, which batches them and sends them to Axiom.
-module(axiom_logger_h).
-behaviour(logger_handler).
-export([adding_handler/1, removing_handler/1, log/2]).
%% Default metadata keys that are noise in Axiom.
-define(SKIP_METADATA, [gl, time, report_cb, domain, error_logger, logger_formatter]).
%% Called by logger when the handler is added.
adding_handler(Config) ->
{ok, Config}.
%% Called by logger when the handler is removed. Flush so nothing is lost on shutdown.
removing_handler(_Config) ->
axiom_logger_sender:flush(),
ok.
%% Never forward the sender's own log events. This prevents infinite loops.
log(#{meta := #{axiom_internal := true}}, _Config) ->
ok;
%% Called by logger in the process that emitted the log event, so keep it cheap:
%% build the event and hand it to the sender.
log(#{level := Level, msg := Msg, meta := Meta}, _Config) ->
axiom_logger_sender:push(build_event(Level, Msg, Meta)).
build_event(Level, Msg, Meta) ->
Time = maps:get(time, Meta, erlang:system_time(microsecond)),
Event = #{<<"_time">> => rfc3339(Time),
<<"level">> => atom_to_binary(Level, utf8),
<<"metadata">> => build_metadata(Meta)},
put_message(Event, Msg).
%% Plain strings, for example logger:info("User logged in.")
put_message(Event, {string, String}) ->
Event#{<<"message">> => to_binary(String)};
%% Structured reports, for example logger:info(#{event => order_placed, order_id => 42})
put_message(Event, {report, Report}) when is_map(Report) ->
Event#{<<"report">> => sanitize(Report)};
put_message(Event, {report, Report}) when is_list(Report) ->
case is_proplist(Report) of
true -> Event#{<<"report">> => sanitize(maps:from_list(Report))};
false -> Event#{<<"message">> => inspect(Report)}
end;
%% Format strings, for example logger:info("~p items", [3])
put_message(Event, {Format, Args}) ->
Message = try to_binary(io_lib:format(Format, Args))
catch _:_ -> inspect({Format, Args})
end,
Event#{<<"message">> => Message}.
build_metadata(Meta) ->
{Mfa, Meta1} = take(mfa, Meta),
{File, Meta2} = take(file, Meta1),
Metadata = sanitize(maps:without(?SKIP_METADATA, Meta2)),
put_mfa(put_file(Metadata, File), Mfa).
put_file(Metadata, undefined) -> Metadata;
put_file(Metadata, File) -> Metadata#{<<"file">> => to_binary(File)}.
put_mfa(Metadata, {Module, Function, Arity}) ->
Metadata#{<<"module">> => atom_to_binary(Module, utf8),
<<"function">> => to_binary(io_lib:format("~s/~B", [Function, Arity]))};
put_mfa(Metadata, _) ->
Metadata.
take(Key, Map) ->
{maps:get(Key, Map, undefined), maps:remove(Key, Map)}.
%% Convert any Erlang term into something json:encode/1 accepts.
sanitize(Value) when is_binary(Value); is_number(Value); is_boolean(Value); Value =:= null ->
Value;
sanitize(Value) when is_atom(Value) ->
atom_to_binary(Value, utf8);
sanitize(Value) when is_map(Value) ->
maps:fold(fun(Key, Val, Acc) -> Acc#{sanitize_key(Key) => sanitize(Val)} end, #{}, Value);
sanitize(Value) when is_pid(Value) ->
list_to_binary(pid_to_list(Value));
sanitize([]) ->
[];
sanitize(Value) when is_list(Value) ->
case io_lib:printable_unicode_list(Value) of
true -> unicode:characters_to_binary(Value);
false ->
case is_proplist(Value) of
true -> sanitize(maps:from_list(Value));
false -> [sanitize(Item) || Item <- Value]
end
end;
%% Tuples, references, functions, and ports
sanitize(Value) ->
inspect(Value).
sanitize_key(Key) when is_atom(Key) -> atom_to_binary(Key, utf8);
sanitize_key(Key) when is_binary(Key) -> Key;
sanitize_key(Key) -> inspect(Key).
is_proplist(List) ->
lists:all(fun({Key, _}) -> is_atom(Key) orelse is_binary(Key); (_) -> false end, List).
rfc3339(Microseconds) ->
list_to_binary(calendar:system_time_to_rfc3339(Microseconds, [{unit, microsecond}, {offset, "Z"}])).
to_binary(Chardata) ->
unicode:characters_to_binary(Chardata).
inspect(Term) ->
unicode:characters_to_binary(io_lib:format("~0tp", [Term])).
```
How the handler works:
* **Timestamps**: The `time` metadata holds the time of the log call in microseconds. The handler converts it to an RFC 3339 string in a field named `_time`, which Axiom uses as the timestamp of the event. Without this field, Axiom uses the time it received the event instead.
* **Messages and reports**: Plain string messages and format strings are sent in the `message` field. Structured reports, such as `logger:info(#{event => order_placed})`, are sent as a `report` object so that you can query each key as a separate field.
* **Metadata**: Default metadata such as the module, function, line, file, and PID is sent in a `metadata` object together with any metadata map you pass to the log calls. The module, function, line, and file are only present for events logged through the `?LOG_*` macros. Erlang strings are lists, so printable lists become JSON strings and other lists become JSON arrays. Values that JSON can’t represent, such as tuples, references, and functions, are formatted with `~p`.
* **Loop prevention**: The sender marks its own process with the `axiom_internal` metadata key. The first `log/2` clause ignores events that carry this key, so errors logged by the sender are never sent back to Axiom.
* **Shutdown**: When the handler is removed, `removing_handler/1` flushes the sender so that the last events aren’t lost.
### Sender [#sender]
Create `src/axiom_logger_sender.erl` with the following content:
```erlang
%% Collects log events and sends them to the Axiom ingest API in batches.
%%
%% Events are flushed when the batch reaches batch_size events or when
%% flush_interval milliseconds have passed, whichever comes first.
-module(axiom_logger_sender).
-behaviour(gen_server).
-export([start_link/1, push/1, flush/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]).
-define(MAX_ATTEMPTS, 3).
start_link(Config) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, Config, []).
%% Adds an event to the buffer. Never blocks the caller.
push(Event) ->
gen_server:cast(?MODULE, {push, Event}).
%% Sends all buffered events immediately and waits for the request to finish.
flush() ->
gen_server:call(?MODULE, flush, 30000).
init(#{token := Token, dataset := Dataset, domain := Domain} = Config) ->
%% Run terminate/2 on shutdown so the last batch is sent.
process_flag(trap_exit, true),
%% Mark this process so axiom_logger_h ignores anything it logs.
logger:update_process_metadata(#{axiom_internal => true}),
State = #{url => "https://" ++ Domain ++ "/v1/ingest/" ++ uri_string:quote(Dataset),
token => Token,
batch_size => maps:get(batch_size, Config, 100),
flush_interval => maps:get(flush_interval, Config, 2000),
events => [],
count => 0},
{ok, schedule_flush(State)}.
handle_cast({push, Event}, #{events := Events, count := Count, batch_size := BatchSize} = State) ->
State1 = State#{events := [Event | Events], count := Count + 1},
case Count + 1 >= BatchSize of
true -> {noreply, do_flush(State1)};
false -> {noreply, State1}
end.
handle_call(flush, _From, State) ->
{reply, ok, do_flush(State)}.
handle_info(flush, State) ->
{noreply, schedule_flush(do_flush(State))};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, State) ->
do_flush(State),
ok.
schedule_flush(#{flush_interval := Interval} = State) ->
erlang:send_after(Interval, self(), flush),
State.
do_flush(#{events := []} = State) ->
State;
do_flush(#{url := Url, token := Token, events := Events} = State) ->
Body = iolist_to_binary(json:encode(lists:reverse(Events))),
Request = {Url, [{"authorization", "Bearer " ++ Token}], "application/json", Body},
case post(Request, 1) of
ok -> ok;
{error, Reason} -> logger:error("Axiom ingest failed: ~p", [Reason])
end,
State#{events := [], count := 0}.
%% POST the batch, retrying HTTP 408/429/5xx responses and connection errors.
post(Request, Attempt) ->
HttpOptions = [{ssl, ssl_options()}, {connect_timeout, 5000}, {timeout, 15000}],
case httpc:request(post, Request, HttpOptions, [{body_format, binary}]) of
{ok, {{_, 200, _}, _Headers, _Body}} ->
ok;
{ok, {{_, Status, _}, _Headers, RespBody}} ->
maybe_retry({http, Status, RespBody}, retryable(Status), Request, Attempt);
{error, Reason} ->
maybe_retry(Reason, true, Request, Attempt)
end.
maybe_retry(_Reason, true, Request, Attempt) when Attempt < ?MAX_ATTEMPTS ->
timer:sleep(500 * Attempt),
post(Request, Attempt + 1);
maybe_retry(Reason, _Retryable, _Request, _Attempt) ->
{error, Reason}.
retryable(Status) ->
lists:member(Status, [408, 429, 500, 502, 503, 504]).
ssl_options() ->
[{verify, verify_peer},
{cacerts, public_key:cacerts_get()},
{depth, 3},
{customize_hostname_check, [{match_fun, public_key:pkix_verify_hostname_match_fun(https)}]}].
```
How the sender works:
* **Endpoint**: Events are sent to `https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME`, the ingest endpoint of your [edge deployment](/reference/edge-deployments). The dataset name is URL-encoded with `uri_string:quote/1`.
* **Request**: `httpc:request/4` sends a POST request with the `Authorization: Bearer API_TOKEN` header and the `Content-Type` set to `application/json`. The body is the list of events encoded as a JSON array with `json:encode/1`, which is the format the ingest endpoint expects.
* **TLS**: The `ssl` options verify the server certificate against the trust store of the operating system, which `public_key:cacerts_get/0` loads, and check that the certificate matches the host name.
* **Retries**: The `post/2` function retries connection errors and responses with HTTP status 408, 429, 500, 502, 503, or 504 up to three times with a short backoff.
* **Batching**: The sender sends a request when it has collected `batch_size` events or when `flush_interval` milliseconds have passed, whichever comes first. Axiom accepts up to 10,000 events in a single request. For more information, see [Limits](/reference/limits).
* **Shutdown**: The process traps exits so that `terminate/2` runs when the app stops and sends the remaining events.
## Starting the sender [#starting-the-sender]
Open `src/axiom_erlang_demo_sup.erl` and replace its content with a supervisor that reads the connection settings from the environment and starts the sender:
```erlang
-module(axiom_erlang_demo_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
SupFlags = #{strategy => one_for_one, intensity => 5, period => 10},
ChildSpecs = [
#{id => axiom_logger_sender,
start => {axiom_logger_sender, start_link, [axiom_config()]}}
],
{ok, {SupFlags, ChildSpecs}}.
axiom_config() ->
#{token => env("AXIOM_TOKEN"),
dataset => env("AXIOM_DATASET"),
domain => env("AXIOM_DOMAIN"),
batch_size => 100,
flush_interval => 2000}.
env(Name) ->
case os:getenv(Name) of
false -> error({missing_env_var, Name});
Value -> Value
end.
```
If one of the environment variables isn’t set, the app fails to start with a `missing_env_var` error that names the variable.
## Attaching the handler [#attaching-the-handler]
Open `src/axiom_erlang_demo_app.erl` and replace its content with the following:
```erlang
-module(axiom_erlang_demo_app).
-behaviour(application).
-export([start/2, prep_stop/1, stop/1]).
start(_StartType, _StartArgs) ->
{ok, Pid} = axiom_erlang_demo_sup:start_link(),
%% Attach the handler after the sender process is running.
ok = logger:add_handler(axiom, axiom_logger_h, #{
level => debug,
filters => [
%% Supervisor progress reports are emitted at info level for every
%% process that starts, including the HTTP connections this handler
%% opens. Drop them so they never feed back into the handler.
{progress, {fun logger_filters:progress/2, stop}},
%% Ignore events that originate from other nodes.
{remote_gl, {fun logger_filters:remote_gl/2, stop}}
]
}),
{ok, Pid}.
%% Removing the handler flushes buffered events before the supervision tree stops.
prep_stop(State) ->
logger:remove_handler(axiom),
State.
stop(_State) ->
ok.
```
The `start/2` callback starts the supervisor first and then attaches the handler with `logger:add_handler/3`. The `level` option sets the minimum level for this handler, and the filters keep supervisor progress reports and events from remote nodes out of Axiom. The `prep_stop/1` callback removes the handler before the supervision tree shuts down, which flushes the remaining events.
## Creating the test module [#creating-the-test-module]
Create `src/axiom_erlang_demo.erl` with a function that logs a message at every level. The module includes `logger.hrl` so that the `?LOG_*` macros are available:
```erlang
%% Emits a log event at every level so you can see them arrive in Axiom.
-module(axiom_erlang_demo).
%% The ?LOG_* macros add the module, function, line, and file to the metadata.
-include_lib("kernel/include/logger.hrl").
-export([run/0]).
run() ->
?LOG_DEBUG("Checking details.", #{action => detail_check, status => initiated}),
?LOG_INFO("User logged in.", #{user_id => <<"exampleUserId">>, method => standard_login}),
?LOG_NOTICE("User tried a feature.", #{feature => experimental_feature_x, status => trial}),
?LOG_WARNING("Feature might not work as expected.", #{feature => experimental_feature, stage => beta}),
?LOG_ERROR("Feature failed to load.", #{feature => feature_y, error_code => 500}),
?LOG_CRITICAL("Major issue with the app.", #{system => payment_processing, error => service_unavailable}),
?LOG_ALERT("Immediate action needed.", #{issue => security, severity => high}),
?LOG_EMERGENCY("The app is down.", #{system => entire_application, status => offline}),
%% Format strings work too.
?LOG_INFO("Processed ~p orders in ~p ms", [42, 117]),
%% Structured report: the map becomes the `report` field in Axiom.
?LOG_INFO(#{event => order_placed, order_id => 1234, total => 59.99, currency => <<"USD">>}),
%% Send whatever is still buffered before the shell exits.
axiom_logger_sender:flush().
```
The final call to `axiom_logger_sender:flush/0` sends the buffered events immediately. This is useful when you exit right after logging. In a long-running app, the sender flushes automatically.
## Run the app [#run-the-app]
Start a shell with rebar3. It compiles the app, loads `config/sys.config`, and starts the app together with `inets` and `ssl`:
```bash
rebar3 shell
```
Call the test function from the shell:
```erlang
1> axiom_erlang_demo:run().
```
To run the test without an interactive shell, pass the call with `--eval`. The `init:stop()` call shuts the app down cleanly, which flushes the remaining events:
```bash
rebar3 shell --eval "axiom_erlang_demo:run(), init:stop()."
```
## View the logs in Axiom [#view-the-logs-in-axiom]
Open your dataset in Axiom. Each event has a `level` and a `message` field, and Axiom flattens the nested objects into fields such as `metadata.module`, `metadata.function`, `metadata.line`, and `metadata.user_id`. Structured reports appear as `report.event`, `report.order_id`, and so on.
For example, the following query lists the most severe events together with the module and line that logged them:
```kusto
['DATASET_NAME']
| where level in ("error", "critical", "alert", "emergency")
| project _time, level, message, ['metadata.module'], ['metadata.line']
| order by _time desc
```
## Conclusion [#conclusion]
This guide has introduced you to integrating Axiom for logging in Erlang/OTP apps. You’ve learned how to attach a custom `logger` handler, batch events in a `gen_server`, and forward them to Axiom with `httpc` and the built-in `json` module. With this knowledge, you’re set to track errors and analyze structured log data from your Erlang apps in Axiom.
---
# Send logs from Laravel to Axiom
Source: https://axiom.co/docs/guides/send-logs-from-laravel
This guide explains integrating Axiom as a logging solution in a Laravel app. Using Axiom’s capabilities with a custom log channel, you can efficiently send your app’s logs to Axiom for storage, analysis, and monitoring. This integration uses Monolog, Laravel’s underlying logging library, to create a custom logging handler that forwards logs to Axiom.
* PHP development [environment](https://www.php.net/manual/en/install.php)
* [Composer](https://laravel.com/docs/11.x/installation) installed on your system
* Laravel app setup
## Installation [#installation]
### Create a Laravel project [#create-a-laravel-project]
Create a new Laravel project:
```bash
composer create-project --prefer-dist laravel/laravel laravel-axiom-logger
```
## Exploring the logging config file [#exploring-the-logging-config-file]
In your Laravel project, the `config` directory contains several configurations on how different parts of your app work, such as how it connects to the database, manages sessions, and handles caching. Among these files, **`logging.php`** identifies how you can define your app logs activities and errors. This file is designed to let you specify where your logs go: a file, a cloud service, or other destinations. The configuration file below includes the Axiom logging setup.
```bash
code config/logging.php
```
```php
env('LOG_CHANNEL', 'stack'),
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => false,
],
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'axiom' => [
'driver' => 'monolog',
'handler' => App\Logging\AxiomHandler::class,
'level' => env('LOG_LEVEL', 'debug'),
'with' => [
'apiToken' => env('AXIOM_TOKEN'),
'dataset' => env('AXIOM_DATASET'),
'axiomUrl' => env('AXIOM_HOST'),
],
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => 14,
'replace_placeholders' => true,
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => LOG_USER,
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];
```
At the start of the `logging.php` file in your Laravel project, you’ll find some Monolog handlers like `NullHandler`, `StreamHandler`, and a few more. This shows that Laravel uses Monolog to help with logging, which means it can do a lot of different things with logs.
### Default log channel [#default-log-channel]
The `default` configuration specifies the primary channel Laravel uses for logging. In this setup, this is set through the **`.env`** file with the **`LOG_CHANNEL`** variable, which you’ve set to **`axiom`**. This means that, by default, log messages will be sent to the Axiom channel, using the custom handler you’ve defined to send logs to the dataset.
```bash
LOG_CHANNEL=axiom
AXIOM_TOKEN=API_TOKEN
AXIOM_DATASET=DATASET_NAME
AXIOM_HOST=AXIOM_DOMAIN
LOG_LEVEL=debug
LOG_DEPRECATIONS_CHANNEL=null
```
### Deprecations log channel [#deprecations-log-channel]
The `deprecations` channel is configured to handle logs about deprecated features in PHP and libraries, helping you prepare for updates. By default, it’s set to ignore these warnings, but you can adjust this to direct deprecation logs to a specific channel if needed.
```php
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => false,
],
```
### Configuration log channel [#configuration-log-channel]
The heart of the `logging.php` file lies within the **`channels`** array where you define all available logging channels. The configuration highlights channels like **`single`**, **`axiom`**, and **`daily`**, each serving different logging purposes:
```php
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'axiom' => [
'driver' => 'monolog',
'handler' => App\Logging\AxiomHandler::class,
'level' => env('LOG_LEVEL', 'debug'),
'with' => [
'apiToken' => env('AXIOM_TOKEN'),
'dataset' => env('AXIOM_DATASET'),
'axiomUrl' => env('AXIOM_HOST'),
],
],
```
* **Single**: Designed for simplicity, the **`single`** channel writes logs to a single file. It’s a straightforward solution for tracking logs without needing complex log management strategies.
* Axiom: The custom **`axiom`** channel sends logs to your specified Axiom dataset, providing advanced log management capabilities. This integration enables powerful log analysis and monitoring, supporting better insights into your app’s performance and issues.
* **Daily**: This channel rotates logs daily, keeping your log files manageable and making it easier to navigate log entries over time.
Each channel can be customized further, such as adjusting the log level to control the verbosity of logs captured. The **`LOG_LEVEL`** environment variable sets this, defaulting to **`debug`** for capturing detailed log information.
## Getting started with log levels in Laravel [#getting-started-with-log-levels-in-laravel]
Laravel lets you choose from eight different levels of importance for your log messages, just like a list of warnings from very serious to just for info. Here’s what each level means, starting with the most severe:
* **EMERGENCY**: Your app is broken and needs immediate attention.
* **ALERT**: similar to `EMERGENCY`, but less severe.
* **CRITICAL**: Critical errors within the main parts of your app.
* **ERROR**: error conditions in your app.
* **WARNING**: something unusual happened that may need to be addressed later.
* **NOTICE**: Important info, but not a warning or error.
* **INFO**: General updates about what your app is doing.
* **DEBUG**: used to record some debugging messages.
Not every situation fits into one of these levels. For example, in an online store, you might use **INFO** to log when someone buys something and **ERROR** if a payment doesn’t go through because of a problem.
Here’s a simple way to log messages at each level in Laravel:
```php
use Illuminate\Support\Facades\Log;
Log::debug("Checking details.");
Log::info("User logged in.");
Log::notice("User tried a feature.");
Log::warning("Feature might not work as expected.");
Log::error("Feature failed to load.");
Log::critical("Major issue with the app.");
Log::alert("Immediate action needed.");
Log::emergency("The app is down.");
```
Output:
```php
[2023-09-01 00:00:00] local.DEBUG: Checking details.
[2023-09-01 00:00:00] local.INFO: User logged in.
[2023-09-01 00:00:00] local.NOTICE: User tried a feature.
[2023-09-01 00:00:00] local.WARNING: Feature might not work as expected.
[2023-09-01 00:00:00] local.ERROR: Feature failed to load.
[2023-09-01 00:00:00] local.CRITICAL: Major issue with the app.
[2023-09-01 00:00:00] local.ALERT: Immediate action needed.
[2023-09-01 00:00:00] local.EMERGENCY: The app is down.
```
## Creating the custom logger class [#creating-the-custom-logger-class]
This section explains how to create the custom logger class designed for sending your Laravel app’s logs to Axiom. This class named `AxiomHandler` , extends Monolog’s **`AbstractProcessingHandler`** giving you a structured way to handle log messages and forward them to Axiom.
* **Initializing cURL**: The **`initializeCurl`** method sets up a cURL handle to communicate with Axiom’s API. It prepares the request with the appropriate headers, including the authorization header that uses your Axiom API token and content type set to **`application/json` .**
* **Handling errors**: If there’s an error during the cURL request, it’s logged to PHP’s error log. This helps in diagnosing issues with log forwarding without disrupting your app’s normal operations.
* **Formatting logs**: Lastly, specify the log message format using the **`getDefaultFormatter`** method. By default, this uses Monolog’s **`JsonFormatter`** to ensure the log messages are JSON encoded, making them easy to parse and analyze in Axiom.
```php
apiToken = $apiToken;
$this->dataset = $dataset;
$this->axiomUrl = $axiomUrl;
}
private function initializeCurl(): \CurlHandle
{
$endpoint = "https://{$this->axiomUrl}/v1/ingest/{$this->dataset}";
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $this->apiToken,
'Content-Type: application/json',
]);
return $ch;
}
protected function write(LogRecord $record): void
{
$ch = $this->initializeCurl();
$data = [
'message' => $record->message,
'context' => $record->context,
'level' => $record->level->getName(),
'channel' => $record->channel,
'extra' => $record->extra,
];
$payload = json_encode([$data]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_exec($ch);
if (curl_errno($ch)) {
// Optionally log the curl error to PHP error log
error_log('Curl error: ' . curl_error($ch));
}
curl_close($ch);
}
protected function getDefaultFormatter(): FormatterInterface
{
return new \Monolog\Formatter\JsonFormatter();
}
}
```
## Creating the test controller [#creating-the-test-controller]
This section demonstrates the process of verifying that your custom Axiom logger is properly set up and functioning within your Laravel app. To do this, create a simple test controller with a method designed to send a log message using the Axiom channel. Following this, define a route that triggers this logging action, allowing you to easily test the logger by accessing a specific URL in your browser or using a tool like cURL.
Create a new controller called `TestController` within your `app/Http/Controllers` directory. In this controller, add a method named `logTest` . This method will use Laravel’s logging to send a test log message to your Axiom dataset. Here’s how you set it up:
```php
check() ? auth()->user()->id : 'guest';
return $record;
};
// Get the Monolog instance for the 'axiom' channel and push the custom processor
$logger = Log::channel('axiom')->getLogger();
if ($logger instanceof Logger) {
$logger->pushProcessor($customProcessor);
}
Log::channel('axiom')->debug("Checking details.", ['action' => 'detailCheck', 'status' => 'initiated']);
Log::channel('axiom')->info("User logged in.", ['user_id' => 'exampleUserId', 'method' => 'standardLogin']);
Log::channel('axiom')->info("User tried a feature.", ['feature' => 'experimentalFeatureX', 'status' => 'trial']);
Log::channel('axiom')->warning("Feature might not work as expected.", ['feature' => 'experimentalFeature', 'warning' => 'betaStage']);
Log::channel('axiom')->warning("Feature failed to load.", ['feature' => 'featureY', 'error_code' => 500]);
Log::channel('axiom')->error("Major issue with the app.", ['system' => 'paymentProcessing', 'error' => 'serviceUnavailable']);
Log::channel('axiom')->warning("Immediate action needed.", ['issue' => 'security', 'level' => 'high']);
Log::channel('axiom')->error("The app is down.", ['system' => 'entireApplication', 'status' => 'offline']);
return 'Log messages sent to Axiom';
}
}
```
This method targets the `axiom` channel, which you previously configured to forward logs to your Axiom account. The message **`Testing Axiom logger!`** should then appear in your Axiom dataset, confirming that the logger is working as expected.
## Registering the route [#registering-the-route]
Next, you need to make this test accessible via a web route. Open your `routes/web.php` file and add a new route that points to the **`logTest`** method in your **`TestController`**. This enables you to trigger the log message by visiting a specific URL in your web browser.
```php
## Conclusion [#conclusion]
This guide has introduced you to integrating Axiom for logging in Laravel apps. You’ve learned how to create a custom logger, configure log channels, and understand the significance of log levels. With this knowledge, you’re set to track errors and analyze log data effectively using Axiom.
---
# Send logs from a Ruby on Rails app using Faraday
Source: https://axiom.co/docs/guides/send-logs-from-ruby-on-rails
This guide provides step-by-step instructions on how to send logs from a Ruby on Rails app to Axiom using the Faraday library. By following this guide, you configure your Rails app to send logs to Axiom, allowing you to monitor and analyze your app logs effectively.
* Install a [Ruby version manager](https://www.ruby-lang.org/en/documentation/installation/) like `rbenv` and use it to install the latest Ruby version.
* Install [Ruby on Rails](https://guides.rubyonrails.org/v5.0/getting_started.html) using the `gem install rails` command.
## Set up the Ruby on Rails app [#set-up-the-ruby-on-rails-app]
1. Create a new Rails app using the `rails new myapp` command.
2. Navigate to the app directory: `cd myapp`
## Setting up the Gemfile [#setting-up-the-gemfile]
Open the `Gemfile` in your Rails app, and then add the following gems:
```ruby
gem 'faraday'
gem 'dotenv-rails', groups: [:development, :test]
```
Install the dependencies by running `bundle install`.
## Create and configure the Axiom logger [#create-and-configure-the-axiom-logger]
1. Create a new file named `axiom_logger.rb` in the `app/services` directory of your Rails app.
2. Add the following code to `axiom_logger.rb`:
```ruby
# app/services/axiom_logger.rb
require 'faraday'
require 'json'
class AxiomLogger
def self.send_log(log_data)
dataset_name = "DATASET_NAME"
axiom_ingest_api_url = "https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME"
ingest_token = "API_TOKEN"
conn = Faraday.new(url: axiom_ingest_api_url) do |faraday|
faraday.request :url_encoded
faraday.adapter Faraday.default_adapter
end
wrapped_log_data = [log_data]
response = conn.post do |req|
req.headers['Content-Type'] = 'application/json'
req.headers['Authorization'] = "Bearer #{ingest_token}"
req.body = wrapped_log_data.to_json
end
puts "AxiomLogger Response status: #{response.status}, body: #{response.body}"
if response.status != 200
Rails.logger.error "Failed to send log to Axiom: #{response.body}"
end
end
end
```
## Test with the Axiom logger [#test-with-the-axiom-logger]
1. Create a new file named `axiom_logger_test.rb` in the `config/initializers` directory.
2. Add the following code to `axiom_logger_test.rb`:
```ruby
# config/initializers/axiom_logger_test.rb
Rails.application.config.after_initialize do
puts "Sending test logs to Axiom using Ruby on Rails Faraday..."
# Info logs
AxiomLogger.send_log({ message: "Application started successfully", level: "info", service: "initializer" })
AxiomLogger.send_log({ message: "User authentication successful", level: "info", service: "auth" })
AxiomLogger.send_log({ message: "Data fetched from external API", level: "info", service: "external_api" })
AxiomLogger.send_log({ message: "Email notification sent", level: "info", service: "email" })
# Warn logs
AxiomLogger.send_log({ message: "API request took longer than expected", level: "warn", service: "external_api", duration: 1500 })
AxiomLogger.send_log({ message: "User authentication token expiring soon", level: "warn", service: "auth", user_id: 123 })
AxiomLogger.send_log({ message: "Low disk space warning", level: "warn", service: "system", disk_usage: "85%" })
AxiomLogger.send_log({ message: "Non-critical configuration issue detected", level: "warn", service: "config" })
# Error logs
AxiomLogger.send_log({ message: "Database connection error", level: "error", service: "database", error: "Timeout" })
AxiomLogger.send_log({ message: "Failed to process payment", level: "error", service: "payment", user_id: 456, error: "Invalid card" })
AxiomLogger.send_log({ message: "Unhandled exception occurred", level: "error", service: "application", exception: "NoMethodError" })
AxiomLogger.send_log({ message: "Third-party API returned an error", level: "error", service: "integration", status_code: 500 })
# Debug logs
AxiomLogger.send_log({ message: "Request parameters", level: "debug", service: "api", params: { page: 1, limit: 20 } })
AxiomLogger.send_log({ message: "Response headers", level: "debug", service: "api", headers: { "Content-Type" => "application/json" } })
AxiomLogger.send_log({ message: "User object details", level: "debug", service: "user", user: { id: 789, name: "Axiom Observability", email: "support@axiom.co" } })
AxiomLogger.send_log({ message: "Cache hit for key", level: "debug", service: "cache", key: "popular_products" })
end
```
Each log entry includes a message, level, service, and additional relevant data.
* Info logs:
* Application started successfully
* User authentication successful
* Data fetched from external API
* Email notification sent
* Warn logs:
* API request took longer than expected (including duration)
* User authentication token expiring soon (including user ID)
* Low disk space warning (including disk usage percentage)
* Non-critical configuration issue detected
* Error logs:
* Database connection error (including error message)
* Failed to process payment (including user ID and error message)
* Unhandled exception occurred (including exception type)
* Third-party API returned an error (including status code)
* Debug logs:
* Request parameters (including parameter values)
* Response headers (including header key-value pairs)
* User object details (including user attributes)
* Cache hit for key (including cache key)
Adjust the log messages, services, and additional data according to your app’s specific requirements and context.
## Create the `log.rake` tasks [#create-the-lograke-tasks]
1. Create a new directory named `tasks` in the `lib` directory of your Rails app.
2. Create a new file named `log.rake` in the `lib/tasks` directory.
3. Add the following code to `log.rake`:
```ruby
# lib/tasks/log.rake
namespace :log do
desc "Send a test log to Axiom"
task send_test_log: :environment do
log_data = { message: "Hello, Axiom from Rake!", level: "info", service: "rake_task" }
AxiomLogger.send_log(log_data)
puts "Test log sent to Axiom."
end
end
```
This code defines a Rake task that sends a test log to Axiom when invoked.
## View logs in Axiom [#view-logs-in-axiom]
1. Start your Rails server by running `rails server`.
2. Go to `http://localhost:3000` to trigger the test log from the initializer.
3. Run the Rake task to send another test log by executing `rails log:send_test_log` in your terminal.
4. In Axiom, go to the Stream tab, and then select the dataset where you send the logs.
5. You see the test logs appear allowing you to view and analyze your event data coming from your Ruby on Rails app.
## Conclusion [#conclusion]
You have successfully set up your Ruby on Rails app to send logs to Axiom using the Faraday library. With this configuration, you can centralize your app logs and use Axiom’s powerful features like [APL](/apl/introduction) for log querying, monitoring, and observing various log levels and types effectively.
---
# Axiom transport for Winston logger
Source: https://axiom.co/docs/guides/winston
## Install SDK [#install-sdk]
To install the SDK, run the following:
```shell
npm install @axiomhq/winston
```
## Import the Axiom transport for Winston [#import-the-axiom-transport-for-winston]
```js
import { WinstonTransport as AxiomTransport } from '@axiomhq/winston';
```
## Create a Winston logger instance [#create-a-winston-logger-instance]
```js
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [
// You can pass an option here. If you don’t, the transport is configured automatically
// using environment variables like `AXIOM_DATASET` and `AXIOM_TOKEN`
new AxiomTransport({
dataset: 'DATASET_NAME',
token: 'API_TOKEN',
}),
],
});
```
After setting up the Axiom transport for Winston, use the logger as usual:
```js
logger.log({
level: 'info',
message: 'Logger successfully setup',
});
```
### Error, exception, and rejection handling [#error-exception-and-rejection-handling]
To log errors, use the [`winston.format.errors`](https://github.com/winstonjs/logform#errors) formatter. For example:
```ts
import winston from 'winston';
import { WinstonTransport as AxiomTransport } from '@axiomhq/winston';
const { combine, errors, stack } = winston.format;
const axiomTransport = new AxiomTransport({ ... });
const logger = winston.createLogger({
// 8<----snip----
format: combine(errors({ stack: true }), json()),
// 8<----snip----
});
```
To automatically log exceptions and rejections, add the Axiom transport to the [`exceptionHandlers`](https://github.com/winstonjs/winston#exceptions) and [`rejectionHandlers`](https://github.com/winstonjs/winston#rejections). For example:
```ts
import winston from 'winston';
import { WinstonTransport as AxiomTransport } from '@axiomhq/winston';
const axiomTransport = new AxiomTransport({ ... });
const logger = winston.createLogger({
// 8<----snip----
transports: [axiomTransport],
exceptionHandlers: [axiomTransport],
rejectionHandlers: [axiomTransport],
// 8<----snip----
});
```
Running on Edge runtime isn’t supported.
## Configure region [#configure-region]
By default, the transport sends data to `api.axiom.co`. To target a specific edge region, set the `edge` option on `AxiomTransport` to the edge domain that matches the region your dataset lives in:
```ts EU Central 1
new AxiomTransport({
dataset: 'DATASET_NAME',
token: 'API_TOKEN',
edge: 'eu-central-1.aws.edge.axiom.co',
});
```
```ts US East 1
new AxiomTransport({
dataset: 'DATASET_NAME',
token: 'API_TOKEN',
edge: 'us-east-1.aws.edge.axiom.co',
});
```
The following edge domains are available:
| Edge deployment | Base domain for ingest and query |
| ------------------ | -------------------------------- |
| US East 1 (AWS) | `us-east-1.aws.edge.axiom.co` |
| EU Central 1 (AWS) | `eu-central-1.aws.edge.axiom.co` |
For more information about edge deployments, see [Edge deployments](/reference/edge-deployments).
Always use the `edge` option to target a region. Don't put a regional hostname in `url` — `url` is reserved for non-ingest API operations and won't route ingest correctly. (This is unrelated to the Edge runtime note above, which is about where your code runs.)
### Transport options [#transport-options]
| Option | Required | Description |
| --------- | -------- | ---------------------------------------------------------------------------------------------------------------- |
| `dataset` | yes | The Axiom dataset to ingest logs into. Falls back to the `AXIOM_DATASET` environment variable. |
| `token` | yes | An Axiom API token with `ingest` permission for the dataset. |
| `orgId` | no | Organization ID. Required when using a personal token. |
| `edge` | no | Edge domain for ingest, without scheme. Example: `eu-central-1.aws.edge.axiom.co`. Use this to target a region. |
| `edgeUrl` | no | Full edge URL with scheme. Takes precedence over `edge` if both are set. Useful for self-hosted or proxy setups. |
| `url` | no | Base URL for non-ingest API operations. |
| `onError` | no | Callback invoked when sending data fails. |
## Examples [#examples]
For more examples, see the [examples in GitHub](https://github.com/axiomhq/axiom-js/tree/main/examples/winston).
---
# Axiom adapter for Zap
Source: https://axiom.co/docs/guides/zap
Use the adapter of the Axiom Go SDK to send logs generated by the [uber-go/zap](https://github.com/uber-go/zap) library to Axiom.
The Axiom Go SDK is an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/axiom-go).
## Set up SDK [#set-up-sdk]
1. Install the Axiom Go SDK and configure your environment as explained in [Send data from Go app to Axiom](/guides/go).
2. In your Go app, import the `zap` package. It’s imported as an `adapter` so that it doesn’t conflict with the `uber-go/zap` package.
```go
import adapter "github.com/axiomhq/axiom-go/adapters/zap"
```
Alternatively, configure the adapter using [options](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/zap#Option) passed to the [New](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/zap#New) function:
```go
core, err := adapter.New(
adapter.SetDataset("DATASET_NAME"),
)
```
## Configure client [#configure-client]
To configure the underlying client manually, choose one of the following:
* Use [SetClient](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/zap#SetClient) to pass in the client you have previously created with [Send data from Go app to Axiom](/guides/go).
* Use [SetClientOptions](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/zap#SetClientOptions) to pass [client options](https://pkg.go.dev/github.com/axiomhq/axiom-go/axiom#Option) to the adapter.
```go
import (
"github.com/axiomhq/axiom-go/axiom"
adapter "github.com/axiomhq/axiom-go/adapters/zap"
)
// ...
core, err := adapter.New(
adapter.SetClientOptions(
axiom.SetPersonalTokenConfig("AXIOM_TOKEN", "AXIOM_ORG_ID"),
),
)
```
### Configure region [#configure-region]
By default, the adapter sends data to `api.axiom.co`. To target a specific edge region, pass `axiom.SetEdge` through `SetClientOptions` with the edge domain that matches the region your dataset lives in:
```go EU Central 1
core, err := adapter.New(
adapter.SetClientOptions(
axiom.SetAPITokenConfig("xaat-your-api-token"),
axiom.SetEdge("eu-central-1.aws.edge.axiom.co"),
),
)
```
```go US East 1
core, err := adapter.New(
adapter.SetClientOptions(
axiom.SetAPITokenConfig("xaat-your-api-token"),
axiom.SetEdge("us-east-1.aws.edge.axiom.co"),
),
)
```
The following edge domains are available:
| Edge deployment | Base domain for ingest and query |
| ------------------ | -------------------------------- |
| US East 1 (AWS) | `us-east-1.aws.edge.axiom.co` |
| EU Central 1 (AWS) | `eu-central-1.aws.edge.axiom.co` |
Edge endpoints require an API token (`xaat-`), not a personal token (`xapt-`). Use `axiom.SetAPITokenConfig` when targeting an edge region. You can also set `AXIOM_EDGE` or `AXIOM_EDGE_URL` in the environment instead of `axiom.SetEdge`. For a full edge URL such as a proxy, use `axiom.SetEdgeURL`, which takes precedence over `axiom.SetEdge`.
The adapter uses a buffer to batch events before sending them to Axiom. Flush this buffer explicitly by calling [Sync](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/zap#WriteSyncer.Sync). For more information, see the [zap documentation](https://pkg.go.dev/go.uber.org/zap/zapcore#WriteSyncer) and the [example in GitHub](https://github.com/axiomhq/axiom-go/blob/main/examples/zap/main.go).
## Reference [#reference]
For a full reference of the adapter’s functions, see the [Go Packages page](https://pkg.go.dev/github.com/axiomhq/axiom-go/adapters/zap).
---
# Acceptable use policy
Source: https://axiom.co/docs/legal/acceptable-use-policy
{/* vale off */}
This Axiom Acceptable Use Policy ("AUP") explains the polices that govern your access and use of the Service offered by Axiom to You. You must use the Service in a lawful manner that is consistent with Axiom’s published AUP. The examples provided by Axiom are a non-exhaustive list of prohibited conduct. Axiom reserves the right to modify this AUP at any time by posting an updated version of the AUP on Axiom’s website. Changes to the policy are deemed effective upon posting and You are responsible for monitoring the website for changes to the policy. Use of any Axiom Service by You is deemed an acceptance of the most current version of the AUP. If the terms of this AUP are violated, Axiom reserves the right to immediately suspend or terminate Your use of the Service.
**Responsibility for Content**\
You are solely responsible for the content and data you use with the Axiom Service. Axiom does not monitor such content for illegal activity. You shall comply with all applicable laws and regulations. Any transmission, storage or distribution, or any use that directly facilitates a violation of applicable law or regulation is strictly prohibited.
**Inappropriate and Illegal Content**\
You may not use, distribute or instruct others to use the Axiom Services for illegal or harmful conduct. The following is a non-exhaustive list of prohibited conduct:
* **Illegal Activities:** Use of content or data in connection with the Axiom Service that is illegal, harassing, defamatory, libelous, indecent, obscene, pornographic, promotes online gambling, or otherwise objectionable.
* **Harmful Content:** Use of content or data in connection with the Axiom Service that is harmful to Axiom’s Service, network or other users of the network including, but not limited to, viruses, Trojan horses, time bombs, or any other computer programming that may damage, interfere with program data or information.
* **Infringing Content:** Use of content or data in connection with the Axiom Service that infringes or misappropriates the intellectual property or property right of others including, but not limited to, material protected by copyright, trademark, patent, or trade secret.
* **Export Violations:** Use of the Axiom Service in violation of U.S. and International export laws, regulations and rules.
**Email, Spam and Usenet**\
Axiom explicitly prohibits you from using the Axiom Service to send unsolicited messages to users without their permission. The following is a non-exhaustive list of prohibited conduct.
* Using the Axiom Service to send unsolicited bulk email, commercial advertising, informational announcements or promotional material (“spam”).
* Using the Axiom Service to post email messages that are excessive or intended to harass others.
* Using the Axiom Service in a manner that assumes the identity of a user without the users explicit permission.
**Security Violations**\
You may not use the Axiom Service to violate the security or integrity of the Axiom Service or Axiom’s network. The following is non-exhaustive a list of prohibited conduct:
* Unauthorized access of networks, data, servers, or databases without obtaining permission.
* Any attempt to test the vulnerability of a network or system, probe or scan or to breach security or authentication measures without permission.
* Any attempt to interfere with, disrupt or disable Service to any user, or network, including, but not limited to, via means of attempts to overload the system, crashing, mail bombing, denial of service attacks, or flooding techniques.
* The forging of any TCP/IP packet header, or using a computer system or program that intentionally conceals the source of information.
* Any usage or attempted usage of the Service You aren’t authorized to use.
* Any attempt or action designed to circumvent or alter any use limitations, including but not limited to, storage restrictions or billing measurement on the Services.
**Reporting Violations**\
It is your responsibility to report all known or suspected violations of this AUP. Axiom reserves the right, but is not obligated to investigate any violation or misuse of the Services. Axiom reserves the right to immediately block access, suspend or terminate you access or use of the Axiom Service, Axiom deems in its sole discretion, has violated the terms of this AUP. Axiom will attempt to provide you notice of possible suspension of Services, but reserves the right to immediately suspend or terminate your access or use of the Axiom Service that would have an adverse effect on Axiom, the Axiom Service, the Axiom network, or any Axiom customer. Axiom shall not be liable for any damages arising out of the violation of this AUP and you shall indemnify Axiom for any and all damages that may arise from a violation of this AUP by You.
---
# Axiom for Startups terms
Source: https://axiom.co/docs/legal/axiom-for-startups
{/* vale Google.Contractions = NO */}
{/* vale Google.We = NO */}
{/* vale Google.WordList = NO */}
These terms govern your participation in Axiom for Startups (the “Program”). They supplement the [Axiom Terms of Service](/legal/terms-of-service) and form part of the applicable Service Description for Axiom Cloud. “Axiom” or “we” means Axiom, Inc. “You” means the company accepted into the Program.
These terms set out your Program benefits and participation requirements. Your use of Axiom remains subject to the Terms of Service, including your obligation to pay charges not covered by the Program.
## Eligibility [#eligibility]
To apply, your company must:
* Be a Seed or Series A company.
* Apply through a participating accelerator, investor or startup community.
* Be new to paid Axiom Cloud.
* Not have received an Axiom startup benefit before.
Companies using a free Axiom organization may apply before upgrading. Existing paid Axiom Cloud customers are not eligible.
Eligibility is assessed when we approve your application. Raising another funding round after approval does not, by itself, end your Program benefits.
## Application and approval [#application-and-approval]
Apply using the form on the Program page. You must be authorized to apply on your company’s behalf and provide accurate information. We may ask for information to verify your eligibility and contact the investor, accelerator, startup community or verification contact named in your application. We will share only the application information reasonably needed to confirm your eligibility. Acceptance is at Axiom’s discretion.
We’ll notify you by email if your application is approved and enable the Program for your approved Axiom organization. Your 12-month Program period begins when that organization upgrades to Axiom Cloud after approval. The platform-fee waiver and compute discount start together on that date. Approval alone does not start the 12-month period.
Benefits do not apply to usage or charges before that date.
## Program benefits [#program-benefits]
During your Program period, you receive:
* A waiver of the $25 monthly Axiom Cloud platform fee for 12 months.
* A 30% discount on standard Data Loading and Query Compute charges, for up to 12 months or until you have received $10,000 in savings from that discount, whichever comes first.
The $10,000 limit counts only savings from the 30% startup compute discount. Included usage and the platform-fee waiver do not count toward it. Reaching the compute savings limit does not end your platform-fee waiver; that continues until the end of your 12-month Program period.
All dollar amounts in these terms are in US dollars.
## Pricing and billing [#pricing-and-billing]
Axiom Cloud’s standard included usage and volume pricing still apply. We calculate eligible Data Loading and Query Compute charges after included usage and normal volume pricing, then apply the 30% startup discount.
Storage and add-ons are not discounted by the Program and follow [standard Axiom Cloud pricing](https://axiom.co/pricing). You remain responsible for charges after the Program benefits have been applied and for applicable taxes under the Terms of Service.
The startup compute discount cannot be combined with committed-use pricing or another promotional compute discount.
## Organization and company limits [#organization-and-company-limits]
Benefits apply only to the Axiom organization approved for the Program. Your company may receive Program benefits only once. Creating another organization does not create a new entitlement to Program benefits.
Unused benefits cannot be exchanged for cash.
## Case study and logo permission [#case-study-and-logo-permission]
As a condition of participating in the Program, you agree to work with Axiom on one case study about your company’s use of Axiom, if requested during your Program period. This includes making a relevant team member available for an interview and helping us verify the details. We’ll agree a reasonable timetable with you and provide the case study for your approval before publication. You will not unreasonably withhold or delay approval. We will not publish your confidential information without your written permission.
You grant Axiom a non-exclusive, royalty-free right to use your company’s name and logo to identify you as a Program participant or Axiom customer on our website, in customer lists and in marketing materials. We’ll follow any reasonable brand guidelines you provide. This permission continues after the Program ends for as long as you remain an Axiom customer. An approved case study, including the company name and logo used in it, may remain published and be used in marketing after that.
## End of benefits [#end-of-benefits]
When you reach $10,000 in startup compute savings, the compute discount ends and standard compute pricing resumes. Your platform fee remains waived for the rest of your 12-month Program period.
At the end of the 12-month period, all Program benefits expire and standard Axiom Cloud pricing resumes, including the platform fee. The Program benefits do not renew automatically. Your Axiom subscription continues under the Terms of Service and your billing settings.
Axiom may end your participation if we reasonably determine that you provided materially false eligibility information or obtained or used Program benefits through fraud or abuse. We’ll notify you if your participation ends early. Standard pricing applies from the end of your participation.
For any other material breach of these Program terms, we may end your participation if you do not resolve the breach within 30 days after written notice.
Ending your participation does not itself close your Axiom organization or terminate your service agreement. Suspension and termination of the service remain governed by the Terms of Service. Program benefits also end if your service agreement is terminated.
## Program changes [#program-changes]
Axiom may change eligibility criteria for future applications, update these Program terms, change Program benefits or discontinue the Program. We’ll act reasonably when making changes that affect companies already approved for the Program.
We will give approved companies at least 30 days’ written notice before a change that materially reduces their benefits or ends their participation because the Program is being discontinued. Changes apply only from their effective date and do not affect benefits already applied or charges already incurred. If a change is required by law, it may take effect sooner; we will give as much notice as reasonably possible.
This section governs changes to the Program only. Changes to your service agreement remain governed by the Terms of Service.
{/* vale Google.Contractions = YES */}
{/* vale Google.We = YES */}
{/* vale Google.WordList = YES */}
---
# Compute Credit and Committed Use Terms
Source: https://axiom.co/docs/legal/committed-use-terms
{/* vale Google.Contractions = NO */}
{/* vale Google.WordList = NO */}
These terms (the “Committed Use Terms”) apply when a Customer pre-purchases Compute Credits under a Committed Use Agreement, whether through Console, a Service Order, AWS Marketplace, or another ordering channel.
They do not apply to a Customer using Axiom solely on an on-demand basis without pre-purchasing Compute Credits.
Committed use provides a discounted rate in exchange for purchasing a fixed quantity of Compute Credits for a fixed term. Eligible Data Loading Compute and Query Compute Charges draw down the prepaid Compute Credit balance. Storage, platform fees, and add-ons remain separate cash charges.
A monthly tolerance threshold accommodates ordinary workload variability. The standard threshold is twice the committed allowance for the Billing Period. Any estimated Burst Surcharge displayed during a Billing Period is provisional and does not constitute a final determination of liability. Axiom determines the Burst Surcharge only after the full Billing Period closes. Crossing the pace reference on an individual day does not itself create a charge. The terms below also explain top-ups, exhaustion, renewal, rollover, and early renewal.
## 1. Definitions [#1-definitions]
The following terms are defined as set forth below unless otherwise defined in the Agreement:
**1.1 “Agreement”** means the [Axiom Terms of Service](/legal/terms-of-service) (the “ToS”) or similar agreement entered into by Axiom and Customer governing Customer’s use of the Service.
**1.2 “Order”** means a Service Order form, accepted Console order, AWS Marketplace order, private offer or CPPO, any resale transactions, or other ordering document that incorporates these terms and states the applicable commercial variables.
**1.3 “Eligible Compute Charges”** means the charges produced by Customer's use of the Data Loading Compute and Query Compute functions of the Service. The underlying usage is measured in the units stated in the Documentation and rated under the applicable graduated SKU schedules. Eligible Compute Charges exclude storage, platform fees, add-ons, taxes, and other cash-only charges.
**1.4 “Compute Credit”** means a prepaid accounting unit that may settle one U.S. dollar ($1.00) of Eligible Compute Charges. A Compute Credit is not the unit in which the underlying Data Loading or Query Compute usage is measured.
**1.5 “On-Demand Compute Credit Rate”** means $1.00 per Compute Credit.
**1.6 “Committed Use Agreement”** means an Order under which Customer purchases a stated total quantity of Compute Credits (the “Committed Compute Credits”) for a stated period (the “Commitment Term”) at a stated price per Compute Credit (the “Committed Rate”).
**1.7 “Commitment Term”** means the period beginning on the Commitment Start Date and ending on the fixed Commitment End Date, each as specified in the Order. Customer may select a commitment duration of twelve (12), twenty-four (24) or thirty-six (36) months. The Commitment End Date is the first monthly Billing Period boundary on or after the end of the selected duration. The Order will specify the resulting Commitment Start Date and Commitment End Date, and the Daily Committed Pace is calculated using the actual number of days between those dates.
For example, a commitment starts on October 21, 2026. Its selected 12-month duration reaches October 21, 2027. If monthly Billing Periods end on the 10th, the Commitment End Date is November 10, 2027. The Daily Committed Pace uses the resulting 385-day term.
**1.8 “Billing Period”** means the monthly billing period applicable to Customer under the Order. The Billing Period is distinct from the payment schedule and Compute Credit Grant Schedule.
**1.9 “Daily Committed Pace”** means the Committed Compute Credits divided by the total number of days in the Commitment Term.
**1.10 “Tolerance Multiplier”** means the multiplier used to calculate the Period Tolerance Threshold. The Tolerance Multiplier is 2.0 (200%), unless otherwise expressly specified in the applicable Service Order.
**1.11 “Active Days in Period”** means the number of days in a Billing Period during which the Committed Use Agreement is active. A partial first or final Billing Period includes only the days overlapping the Commitment Term.
**1.12 “Period Tolerance Threshold”** means the Daily Committed Pace multiplied by the Active Days in Period and then by the Tolerance Multiplier.
**1.13 “Above-Threshold Compute Credits”** means the greater of zero and the number of Compute Credits consumed in a Billing Period minus the Period Tolerance Threshold.
**1.14 “Burst Rate”** means the On-Demand Compute Credit Rate, unless otherwise expressly specified in the Order.
**1.15 “Compute Credits Applied in Period”** means the actual number of Compute Credits consumed from Customer's active prepaid balance to settle Eligible Compute Charges during a Billing Period. A Compute Credit Grant, Top-Up Compute Credit, expiry, or retirement is included according to its effective time. A Compute Credit that becomes available before an open Billing Period ends may be applied when that Billing Period is finalized, including to Eligible Compute Charges accumulated earlier in that Billing Period, but may not be used for or in connection with a prior closed Billing Period.
**1.16 “Prepaid Above-Threshold Compute Credits”** means the greater of zero and the Compute Credits Applied in Period minus the Period Tolerance Threshold.
**1.17 “Burst Surcharge”** means the Prepaid Above-Threshold Compute Credits multiplied by the difference between the Burst Rate and the Committed Rate.
**1.18 “Service Order”** means an order form issued by Axiom, fully executed by Customer and Axiom, that references the Agreement.
**1.19 “Console”** means the Axiom web application through which a Customer may purchase Compute Credits.
**1.20 “Data Loading Compute”** means the compute used to ingest Customer Data into the Service for indexing and storage. Usage of Data Loading Compute is measured in gibibytes of data loaded (“GiB”) and rated under the applicable graduated SKU schedule.
**1.21 “Query Compute”** means the compute capacity used to run queries and analyses against Customer Data stored in the Service. Usage of Query Compute is measured in gibibyte-hours (“GiB-hours”), representing one GiB of query-compute capacity used for one hour, and rated under the applicable graduated SKU schedule.
**1.22 “Compute Credit Grant”** means a grant of pre-purchased Compute Credits made under the Compute Credit Grant Schedule, excluding Top-Up Compute Credits and Rollover Compute Credits.
**1.23 “Top-Up Compute Credits”** means Compute Credits purchased within the Commitment Term following the initial purchase (as defined in Section 5).
**1.24 “Axiom Organization”** means an administrative tenancy boundary with respect to a Customer’s use of the Service.
## 2. Purchase, Compute Credit grants and payment [#2-purchase-compute-credit-grants-and-payment]
**2.1** Fees for Committed Compute Credits equal the Committed Compute Credits multiplied by the Committed Rate. The fees, payment dates and permitted payment method are stated in the Order. Unless the Order states an instalment schedule, the fees are due upon execution or acceptance of the Order.
**2.2** The Order will state when the corresponding Compute Credits are granted (the “Compute Credit Grant Schedule”). Committed Compute Credits are the total Compute Credits purchased for the full Commitment Term regardless of payment or grant cadence. Every grant under the Order expires on the fixed Commitment End Date.
**2.3** A multi-year Order may provide for annual payment and grant instalments without changing the rate earned by the full multi-year contractual commitment. All such grants remain subject to the same Commitment End Date.
**2.4** Fees for Committed Compute Credits are non-cancellable and non-refundable. Compute Credits cannot be redeemed for cash or transferred, except for the limited rollover and early renewal treatment expressly described in Sections 6 and 7 or as required by applicable law.
Notwithstanding anything to the contrary herein, the term “Compute Credit” is used throughout these terms solely as a unit of measure for tracking and allocating usage of the Services. Compute Credits do not constitute, represent, or evidence (a) a store of value; (b) a monetary instrument, currency, or cash equivalent; (c) any right, entitlement, or claim to monetary payment or reimbursement; or (d) any property interest of any kind.
Compute Credits have no independent monetary value, are not redeemable for cash or cash equivalents, and may not be transferred, sold, or assigned except as expressly permitted under these Terms. The use of the term “Compute Credit” is for administrative convenience only and shall not be construed to create any financial obligation of Axiom beyond the provision of the Services to which such Compute Credits apply.
## 3. Consumption and customer visibility [#3-consumption-and-customer-visibility]
**3.1** Each $1.00 of Eligible Compute Charges consumes one Compute Credit from Customer's available Compute Credit balance while a balance remains, regardless of the price Customer paid for that Compute Credit.
For example, $1,200 of Data Loading Compute charges and $800 of Query Compute charges consume 2,000 Compute Credits. A balance of 10,000 Compute Credits then becomes 8,000 Compute Credits. Storage, platform fees, and add-ons do not consume that balance.
**3.2** For the calculations in Sections 4 and 7, every Compute Credit in the active balance—including Compute Credits added by top-up or rollover—is treated at the active Committed Rate. Historical price tranches are not maintained within one active balance.
**3.3** During a Billing Period, Axiom may display usage to date, pace, balance, estimated or projected surcharge, projected exhaustion and related alerts. These values are provisional operational information, may increase, decrease, or return to zero as the Billing Period progresses, and are not an invoice or a final determination of liability.
**3.4** Commercial liability for a Burst Surcharge is determined only after the relevant Billing Period closes. No daily positive or negative billing adjustment is created.
## 4. Period threshold and Burst Surcharge [#4-period-threshold-and-burst-surcharge]
**4.1** At the close of each Billing Period, Axiom will determine the Period Tolerance Threshold, Above-Threshold Compute Credits, Compute Credits Applied in Period and Prepaid Above-Threshold Compute Credits for that Billing Period.
**4.2** Eligible Compute Charges at or below the Period Tolerance Threshold consume Compute Credits normally and create no Burst Surcharge.
**4.3** Prepaid Above-Threshold Compute Credits are calculated as the greater of zero and Compute Credits Applied in Period minus the Period Tolerance Threshold. This aggregate calculation excludes usage already invoiced on-demand without requiring individual usage events to be classified as prepaid or on-demand above the threshold.
**4.4** Prepaid Above-Threshold Compute Credits continue to consume the Compute Credit balance and also incur the Burst Surcharge. The two amounts together produce the Burst Rate for those Compute Credits; the Burst Surcharge is only the difference between the Committed Rate already paid and the Burst Rate.
**4.5** Axiom will invoice one final Burst Surcharge in cash for the closed Billing Period. It is not deducted from the Compute Credit balance.
**4.6** Usage already invoiced at the On-Demand Compute Credit Rate receives no Burst Surcharge.
**4.7** The result is final for that Billing Period. Lower usage within the same open Billing Period may reduce or eliminate a provisional surcharge, but usage in a later Billing Period does not reopen or offset a closed result.
For example, a Daily Committed Pace of 1,000 and 30 active days produces a standard threshold of 60,000 Compute Credits. If 70,000 prepaid Compute Credits are applied, 10,000 are above the threshold. At a $0.80 Committed Rate and $1.00 Burst Rate, the cash surcharge is $2,000.
## 5. Top-ups and exhaustion [#5-top-ups-and-exhaustion]
**5.1** During the Commitment Term, Customer may purchase additional Compute Credits at the active Committed Rate (“Top-Up Compute Credits”). Cumulative Console purchases of Top-Up Compute Credits during the Commitment Term may not exceed fifty percent (50%) of the original Committed Compute Credits.
**5.2** Top-Up Compute Credits enter the existing Compute Credit balance and expire on the existing Commitment End Date. They do not change the Committed Compute Credits, Daily Committed Pace, Tolerance Multiplier, Period Tolerance Threshold, Committed Rate or Commitment End Date.
**5.3** A top-up does not combine with the original purchase to qualify for a different aggregate volume tier and does not reprice the original purchase or the Top-Up Compute Credits.
**5.4** A Top-Up Compute Credit becomes available when Axiom receives the applicable payment. If it becomes available before an open Billing Period ends, it may be applied to Eligible Compute Charges accumulated earlier in that Billing Period. A top-up does not reopen or recalculate a closed Billing Period, reverse a final Burst Surcharge, or reprice usage already invoiced on-demand for a closed Billing Period.
**5.5** If the available Compute Credit balance reaches zero, subsequent Eligible Compute Charges accrue at the On-Demand Compute Credit Rate. If a Top-Up Compute Credit becomes available before the same Billing Period ends, it may settle those charges when the Billing Period is finalized. Any Eligible Compute Charges not settled by Compute Credits are invoiced monthly in arrears at the On-Demand Compute Credit Rate and receive no Burst Surcharge.
**5.6** Exhaustion does not shorten, terminate or renew the Commitment Term and does not change the Commitment End Date.
## 6. Scheduled expiry, renewal and rollover [#6-scheduled-expiry-renewal-and-rollover]
**6.1** Every unused Compute Credit associated with a Committed Use Agreement—including Top-Up Compute Credits and Rollover Compute Credits—expires at the Commitment End Date unless it qualifies for rollover under Section 6.2.
**6.2** If Customer enters into a replacement Committed Use Agreement effective immediately following the scheduled Commitment End Date with Committed Compute Credits equal to or greater than the expiring Committed Compute Credits, unused Compute Credits may roll into the new Commitment Term for up to twenty percent (20%) of the new Committed Compute Credits (“Rollover Compute Credits”). The following is an example of the applicable Rollover Compute Credits:
If the expiring Committed Use Agreement has 100,000 Committed Compute Credits, 30,000 Compute Credits remain unused, and Customer enters into a replacement Committed Use Agreement for 100,000 Committed Compute Credits, the rollover limit is 20,000 Compute Credits. Accordingly, 20,000 Compute Credits become Rollover Compute Credits and the remaining 10,000 unused Compute Credits expire.
**6.3** Rollover Compute Credits are added to the new Compute Credit balance and expire on the new Commitment End Date. The new Daily Committed Pace and Period Tolerance Threshold are calculated from the new Committed Compute Credits only; Rollover Compute Credits do not increase pace.
**6.4** If the new Committed Compute Credits are fewer than the expiring Committed Compute Credits, or Customer does not renew, all unused Compute Credits expire without refund.
**6.5** If Customer does not renew, subsequent Eligible Compute Charges remain available at the On-Demand Compute Credit Rate.
## 7. Mutually agreed early renewal [#7-mutually-agreed-early-renewal]
**7.1** The parties may enter into a replacement Committed Use Agreement before the scheduled Commitment End Date (an “Early Renewal”). An Early Renewal takes effect at the next Billing Period boundary stated in the replacement Order.
**7.2** The expiring agreement remains unchanged until the Early Renewal takes effect. The original Daily Committed Pace will continue to apply to the expiring agreement’s final Billing Period. Axiom will close its final Billing Period normally and then determine the unused Compute Credits in the active balance (“Remaining Compute Credits”).
**7.3** Solely to price the Early Renewal, the “Remaining Prepaid Value” equals the Remaining Compute Credits multiplied by the expiring Committed Rate. Remaining Prepaid Value is a non-cash price offset available only for the Early Renewal; it is not a refund, cash redemption right or transferable monetary balance.
**7.4** The replacement Order must have more Committed Compute Credits than the expiring Order. Its total value (“New Commitment Value”) equals the new Committed Compute Credits multiplied by the new Committed Rate and must exceed the Remaining Prepaid Value.
**7.5** The amount due for the Early Renewal equals the New Commitment Value minus the Remaining Prepaid Value, subject to the payment schedule in the replacement Order.
**7.6** On the Early Renewal effective date, Axiom will retire the entire old Compute Credit balance and establish the replacement grants in accordance with the new Compute Credit Grant Schedule. No old Compute Credit is both recognized in Remaining Prepaid Value and carried forward as a unit. Scheduled-renewal rollover under Section 6 does not also apply.
**7.7** The replacement Order begins one new full Commitment Term with a new Daily Committed Pace and fixed Commitment End Date. An Early Renewal creates no cash refund and does not reprice an open or closed Billing Period.
**7.8** If the parties do not agree an Early Renewal, the existing Committed Use Agreement, balance, pace, surcharge treatment and Commitment End Date continue unchanged.
## 8. On-demand use, other charges and spend controls [#8-on-demand-use-other-charges-and-spend-controls]
**8.1** In the absence of a Committed Use Agreement, and following exhaustion or expiry, Customer may continue to use the Service at the On-Demand Compute Credit Rate without a committed-use cutoff, subject to the Agreement and Customer's applicable spend controls.
**8.2** Storage, platform fees, add-ons and other non-compute charges are not payable in Compute Credits and are invoiced in cash at the rates and times stated in the Documentation or Order.
**8.3** Certain features in the Service may pause further cost-generating activity but do not amend the Committed Use Agreement, alter any threshold, or waive fees and liability already incurred.
## 9. Rates and changes [#9-rates-and-changes]
**9.1** The Committed Rate, Tolerance Multiplier and Burst Rate are fixed for the Commitment Term unless the parties execute an Early Renewal under Section 7.
**9.2** Published rates may change for future orders, but no published change applies to an executed Order during its Commitment Term.
**9.3** Rates specified in an Order apply only to that Order and its Commitment Term. They do not carry into a renewal or replacement Order unless expressly restated.
## 10. One active commitment [#10-one-active-commitment]
**10.1** Each Axiom Organization identified in an Order may have only one active Committed Use Agreement at a time.
## 11. Standard Compute Credit rates [#11-standard-compute-credit-rates]
**11.1** For purposes of the rate table below, annual committed volume equals the total Committed Compute Credits multiplied by twelve (12) and divided by the selected commitment duration in months. The selected duration of twelve (12), twenty-four (24) or thirty-six (36) months is used for this rate calculation; the actual dated Commitment Term determines the Daily Committed Pace under Section 1.9.
**11.2** The standard rate is determined by the row corresponding to annual committed volume and the column corresponding to the selected commitment duration. All rates in the table are stated in U.S. dollars per Compute Credit. No standard committed-use discount applies to annual committed volume below 25,000 Compute Credits.
**11.3** For example, an Order for 1,200,000 Committed Compute Credits over thirty-six (36) months has annual committed volume of 400,000 Compute Credits. The applicable row is 250,000 to 499,999 and the applicable column is 36 months, resulting in a Committed Rate of $0.73 per Compute Credit and total Compute Credit fees of $876,000.
| Annual committed Compute Credits | 12 months | 24 months | 36 months |
| -------------------------------- | --------- | --------- | --------- |
| 0 to 24,999 | $1.00 | $1.00 | $1.00 |
| 25,000 to 99,999 | $0.90 | $0.86 | $0.83 |
| 100,000 to 249,999 | $0.85 | $0.81 | $0.78 |
| 250,000 to 499,999 | $0.80 | $0.76 | $0.73 |
| 500,000 to 2,499,999 | $0.70 | $0.66 | $0.63 |
| 2,500,000 or more | $0.60 | $0.56 | $0.53 |
{/* vale Google.Contractions = YES */}
{/* vale Google.WordList = YES */}
---
# Cookie policy
Source: https://axiom.co/docs/legal/cookies
{/* vale off */}
## What are cookies? [#what-are-cookies]
Cookies are small data files that are placed on your computer when you visit a site. Cookies serve different purposes, like helping us understand how our site is being used, letting you navigate between pages efficiently, remembering your preferences, and generally improving your browsing experience. Cookies can also help ensure advertising you see online is more relevant to you and your interests.
## Who places cookies on my device? [#who-places-cookies-on-my-device]
Cookies set by the site you visit are called "first party cookies". Cookies set by parties other than us are called "third party cookies". Third party cookies enable third party features or functionality within the site, such as site analytics, advertising and social media features. The parties that set these third party cookies can recognize your computer or device both when it visits the site in question and also when it visits certain other sites and/or mobile apps. We do not control how these third parties' use your information, which is subject to their own privacy policies. See below for details on use of third party cookies and similar technologies with our sites and app.
## How long will cookies stay on my device? [#how-long-will-cookies-stay-on-my-device]
The length of time a cookie will stay on your device depends on whether it is a "persistent" or "session" cookie. Session cookies will only stay on your device until you stop browsing. Persistent cookies stay on your browsing device after you have finished browsing until they expire or are deleted.
## What other tracking technologies should I know about? [#what-other-tracking-technologies-should-i-know-about]
Cookies are not the only way to track visitors to a site or app. Companies use tiny graphics files with unique identifiers called beacons (and also "pixels" or "clear gifs") to recognize when someone visits its sites. These technologies often depend on cookies to function properly, and so disabling cookies may impair their functioning.
## What types of cookies and similar tracking technologies does Axiom use? [#what-types-of-cookies-and-similar-tracking-technologies-does-axiom-use]
We use cookies and other tracking technologies in the following categories described below.
### Essential cookies [#essential-cookies]
These cookies are essential to provide you with services available through our websites and to enable you to use some of their features. Without these cookies, the services that you have asked for cannot be provided, and we only use these cookies to provide you with those services.
**Who serves these cookies:** Axiom, Inc.
**How to refuse:** Because these cookies are strictly necessary to deliver the Websites to you, you cannot refuse them. You can block or delete them by changing your browser settings however, as described below under the heading "Your choices".
### Functionality cookies [#functionality-cookies]
These cookies allow our websites to remember choices you make when you use them. The purpose of these cookies is to provide you with a more personal experience and to avoid you having to re-select your preferences every time you visit our websites.
**Who serves these cookies:** Axiom, Inc.
**How to refuse:** To refuse these cookies, please follow the instructions below under the heading "Your choices".
### Analytics and performance cookies [#analytics-and-performance-cookies]
These cookies are used to collect information about traffic to our websites and how users use our websites. The information gathered may include the number of visitors to our websites, the websites that referred them to our websites, the pages they visited on our websites, what time of day they visited our websites, whether they have visited our websites before, and other similar information. We use this information to help operate our websites more efficiently, to gather broad demographic information, monitor the level of activity on our websites, and improve the websites.
**Who serves these cookies:**
**Segment** (Twilio, Inc.)
The subsite, [https://app.axiom.co](https://app.axiom.co) (a subsite of axiom.co) uses Segment to help analyze how users use the site. The tool does not use cookies however user data is shared with Segment. In addition to your name and email address, your IP may be transmitted to Segment (though never stored there). This information is then used to evaluate the use of the service as well as compute statistical reports on website activity to help us build a better product.
You can find more information about Segment's privacy policy here: [https://www.twilio.com/en-us/legal/privacy](https://www.twilio.com/en-us/legal/privacy). If you wish to not share usage information with Twilio/Segment, please let us know at [privacy@axiom.co](mailto:privacy@axiom.co)
**Mixpanel**
The subsite, [https://app.axiom.co](https://app.axiom.co) (a subsite of axiom.co) uses Mixpanel to help analyze how users use the site. The tool does not use cookies however user data is shared with Mixpanel. In addition to your name and email address, your IP may be transmitted to Mixpanel (though never stored there). This information is then used to evaluate the use of the service as well as compute statistical reports on website activity to help us build a better product.
You can find more information about Mixpanel's privacy policy here: [https://mixpanel.com/legal/privacy-policy](https://mixpanel.com/legal/privacy-policy). If you wish to not share usage information with Mixpanel, please let us know at [privacy@axiom.co](mailto:privacy@axiom.co)
**Hubspot** (Hubspot, Inc.)
The utilization of HubSpot's services enables the collection, storage, and analysis of user interaction data, enhancing our capacity to provide tailored content, optimize user experience, and conduct comprehensive website performance evaluations. It is imperative to note that all data captured through HubSpot's cookie tracking technology is processed and stored in strict adherence to applicable data protection laws and regulations, ensuring the utmost level of data integrity and security. Users retain the right to opt-out of cookie tracking at any given time, a provision that can be executed through the designated privacy settings available on our website. By continuing to navigate our website, users express their informed consent to our use of HubSpot for cookie tracking purposes, acknowledging the vital role it plays in our ongoing efforts to refine and personalize the user experience.
**Warmly** (Warmly, Inc.)
The Services use cookies and similar tracking technologies such as pixel tags, web beacons, and JavaScript to enable our servers to recognize your web browser, tell us how and when you visit and use our Services, analyze trends, learn about our user base and operate and improve our Services. These technologies help us measure and improve our services and personalize your experience. For more information about Warmly's privacy practices, visit [https://www.warmly.ai/p/privacy-policy](https://www.warmly.ai/p/privacy-policy).
**X, (Formally, Twitter)** (X, Inc. (Previously Twitter))
Pixels are small amounts of code placed on a web page, in a web-enabled app, or an email. We use pixels, some of which we provide to advertisers to place on their web properties, to learn whether you've interacted with specific web or email content — as many services do. This helps us measure and improve our services and personalize your experience, including the ads you see.
**Linkedin** (Linkedin, Inc.)
Pixels are small amounts of code placed on a web page, in a web-enabled app, or an email. We use pixels, some of which we provide to advertisers to place on their web properties, to learn whether you've interacted with specific web or email content — as many services do. This helps us measure and improve our services and personalize your experience, including the ads you see.
**Google Tag Manager, Google Analytics** (Google, LLC.)
Pixels are small amounts of code placed on a web page, in a web-enabled app, or an email. We use pixels, some of which we provide to advertisers to place on their web properties, to learn whether you've interacted with specific web or email content — as many services do. This helps us measure and improve our services and personalize your experience, including the ads you see.
**How to refuse:** To refuse these cookies, please follow the instructions below under the heading "Your choices" Alternatively, please click on the relevant opt-out link below.
You can control these cookies as described in the Your choices section below. The third parties who serve cookies listed in the table above may use other third parties to place cookies, but any such indirect placement of cookies is out of our control. You should review the privacy policies of the third parties listed in the table above to find out more information about their use of cookies.
## Your choices [#your-choices]
You can access cookie preferences by using the "Cookie settings" button above. However, most browsers let you remove or reject cookies. To do this, follow the instructions in your browser settings. Many browsers accept cookies by default until you change your settings. Please note that if you set your browser to disable cookies, parts of the site may not work properly. For more information about cookies, including how to see what cookies have been set on your computer or mobile device and how to manage and delete them, visit [www.allaboutcookies.org](http://www.allaboutcookies.org).
## Changes [#changes]
Information about the cookies we use may be updated from time to time, so please check back on a regular basis for any changes.
## Questions [#questions]
If you have any questions about this Cookie Policy, please contact us by email at [privacy@axiom.co](mailto:privacy@axiom.co).
---
# Data processing addendum
Source: https://axiom.co/docs/legal/data-processing
{/* vale off */}
This Data Processing Addendum (“**DPA**”) is incorporated into and forms part of the Axiom Terms of Service [https://axiom.co/docs/legal/terms-of-service](/legal/terms-of-service) or other applicable agreement governing the use of the Services (the “**Agreement**”).
**By accessing or using the Services, or otherwise indicating your acceptance of the Agreement, Customer hereby agrees to the terms of this DPA on behalf of itself and any affiliated entities it represent.**
This DPA applies to Axiom Inc.’s (“**Axiom**” or “**Company**”) Processing of Personal Data in connection with the Services and is effective as of the date Customer first access or use of the Services after the date of publication of this DPA (the “**Effective Date**”). This DPA does not require a signature to be valid or enforceable and is deemed to be mutually agreed upon and entered into by Customer and Axiom through Customer’s acceptance of the Agreement. This DPA applies only if and to the extent Applicable Data Protection Laws govern Axiom’s Processing of Customer Personal Data in performance of the Services as a ‘processor’, ‘service provider’ or similar role defined under Data Protection Laws. Accordingly, this DPA does not apply to Axiom’s Processing of any Personal Data for its own business or customer relationship, administration purposes, its own marketing or service analytics, its own information and systems security purposes supporting the operation of the Services, nor its own legal, regulatory or compliance purposes.
For a copy of the signed DPA for recordkeeping purposes, or if Customer requires a countersigned version due to internal policies, please contact Axiom at [privacy@axiom.co](mailto:privacy@axiom.co).
**1. Definitions**
In this DPA:
a) “**Business**”, “**Controller**”, “**Data Subject**”, “**Personal Data**”, “**Personal Data Breach**”, “**Processing**”, “**Processo**r”, “**Service Provider**” and “**Supervisory Authority**” have the meaning given to them in Data Protection Law;
b) “**Customer**” means the entity that is receiving the Services and has entered into the Agreement with Company.
c) “**Customer Personal Data**” means any Customer data that constitutes Personal Data, the Processing of which is subject to Data Protection Law, for which Customer or Customer’s customers are the Controller, and which is Processed by Company as part of providing the Services;
d) "**Data Protection Law**" means all applicable privacy and data protection laws relating to the processing of Customer Personal Data in connection with the Agreement, including but not limited to (i) the Regulation (EU) 2016/679 of the European Parliament and of the Council of 27th April 2016 on the protection of natural persons with regard to the processing of personal data and on the free movement of such data (“**GDPR**”), (ii) the GDPR as it forms part of the law of England and Wales, Scotland and Northern Ireland by virtue of section 3 of the European Union (Withdrawal) Act 2018, (iii) the e-Privacy Directive 2002/58/EC (as amended by Directive 2009/136/EC) and their national implementations in the European Economic Area (“**EEA**”) and the United Kingdom; and (iv) the California Consumer Privacy Act as amended by the California Privacy Rights Act (California Civil Code § 1798.100) (“CCPA”), each as applicable, and as may be amended or replaced from time to time;
e) “**Data Subject Rights**” means Data Subjects’ rights as set out in Data Protection Law;
f) “**International Data Transfer**” means any transfer of Customer Personal Data from the EEA, Switzerland or the United Kingdom to an international organization or to a country outside of the EEA, Switzerland and the United Kingdom;
g) “**Sell**” means to sell, rent, release, disclose, disseminate, make available, transfer, or otherwise communicate Customer Personal Data to a third party for monetary or other valuable consideration;
h) “**Services**” means the services provided by Company to Customer under the Agreement;
i) “**Share**” means to share, rent, release, disclose, disseminate, make available, transfer, or otherwise communicate Customer Personal Data to third parties for targeted advertising to an individual based on Personal Data obtained from the individual’s activity across non-affiliated or distinctly-branded websites, applications, or services;
j) “**Subprocessor**” means a Processor engaged by Company to Process Customer Personal Data;
k) “**Standard Contractual Clauses**" means the standard contractual clauses approved by the European Commission pursuant to implementing Decision (EU) 2021/914.
l) **“Third-Party Controller”** means a Controller for which Customer acts as a Processor; and
m) “**UK Addendum**” means the International Data Transfer Addendum to the Standard Contractual Clauses issued by the UK Information Commissioner’s Office, in force as of 21 March 2022, available at international-data-transfer-addendum.pdf (ico.org.uk).
**2. Scope and applicability**
2.1. This DPA applies to Processing of Customer Personal Data by the Company to provide the Services\*\*.\*\*
2.2. The subject matter, nature and purpose of the Processing, the types of Customer Personal Data and categories of Data Subjects are set out in Annex I.
2.3. Customer is a Controller and appoints Company as a Processor and, with respect to CCPA, a Service Provider, on behalf of Customer. Customer is responsible for compliance with the requirements of Data Protection Law applicable to Controllers.
**3. Instructions**
3.1. Company will Process Customer Personal Data to provide the Services and in accordance with Customer’s documented instructions and applicable Data Protection Law.
3.2. It is the parties’ intent that Company is a Service Provider, and Company certifies that it will not (i) Sell or Share Customer Personal Data; (ii) Process Customer Personal Data outside the direct business relationship between the parties or for any purpose other than to provide the Services in accordance with the Agreement, unless required or authorized by Data Protection Law; or (iii) combine the Personal Data that Company receives from or on behalf of Customer with Personal Data that Company collects or receives from another person.
3.3. The Controller’s instructions are documented in this DPA and the Agreement. Customer may reasonably issue additional instructions as necessary to comply with Data Protection Law. Company may charge a reasonable fee to comply with any additional instructions.
3.4. Unless prohibited by applicable law, Company will inform Customer if Company is subject to a legal obligation that requires Company to Process Customer Personal Data in contravention of Customer’s documented instructions.
3.5. Company will notify Customer after it makes a determination that it can no longer meet its obligations under Data Protection Law. Customer has the right, upon notice, to take reasonable and appropriate steps to stop and remediate Company’s unauthorized use of Customer Personal Data and to ensure that Company uses the Customer Personal Data that it collected pursuant to the Agreement in a manner consistent with Customer’s obligations under Data Protection Law.
**4. Personnel**
Company will ensure that all personnel authorized to Process Customer Personal Data are subject to an obligation of confidentiality.
**5. Security and Personal Data Breaches**
5.1. Taking into account the state of the art, the costs of implementation and the nature, scope, context and purposes of Processing as well as the risk of varying likelihood and severity for the rights and freedoms of natural persons, Company will implement and maintain appropriate technical and organizational measures designed to provide a level of security appropriate to the risk, including the measures listed in Annex II.
5.2. Customer acknowledges that the security measures in Annex II are appropriate in relation to the risks associated with Customer’s intended Processing, and will notify Company prior to any intended Processing for which Company’s security measures may not be appropriate.
5.3. Company will notify Customer without undue delay after becoming aware of a Personal Data Breach involving Customer Personal Data. If Company’s notification is delayed, it will be accompanied by reasons for the delay.
**6. Subprocessing**
6.1. Customer hereby authorizes Company to engage Subprocessors. A list of Company’s current Subprocessors is available at [https://axiom.co/sub-processors](https://axiom.co/sub-processors) (the “**Subprocessors Page**”), and may be updated by Company from time to time in accordance with this DPA.
6.2. Company will enter into a written agreement with Subprocessors which imposes the obligations consistent with applicable Data Protection Law. Subject to the limitations of liability included in the Agreement, Company agrees to be liable for the acts and omissions of its Subprocessors to the same extent Company would be liable under the terms of the DPA if it performed such acts or omissions itself.
6.3. When any new Subprocessor is engaged, Company will notify Customer of the engagement, which notice may be given by updating the Subprocessor Page and/or via a message through email or the Service. Axiom will give such notice at least ten (10) calendar days before the new Subprocessor Processes any Customer Personal Data, except that if Company reasonably believes engaging a new Subprocessor on an expedited basis is necessary to protect the confidentiality, integrity or availability of the Customer Personal Data or avoid material disruption to the Services, Axiom will give such notice as soon as reasonably practicable. If, within five (5) calendar days after such notice, Customer notifies Company in writing that Customer objects to the appointment of a new Subprocessor based on reasonable data protection concerns, the parties will discuss such concerns in good faith and whether they can be resolved. If the parties are not able to mutually agree to a resolution of such concerns, Customer, as its sole and exclusive remedy, may terminate the Agreement for convenience with no refunds and Customer will remain liable to pay any committed fees in an order form, order, statement of work or other similar ordering document.
**7. Assistance**
7.1. Taking into account the nature of the Processing, and the information available to Company, Company will assist Customer, including, as appropriate, by implementing technical and organizational measures, with the fulfillment of Customer’s own obligations under Data Protection Law to: comply with requests to exercise Data Subject Rights; conduct data protection impact assessments, and prior consultations with Supervisory Authorities; and notify a Personal Data Breach. Company reserves the right to charge a reasonable fee for assistance under this Section 7.
**8. Audit**
8.1. Upon reasonable request, Company must make available to Customer all information necessary to demonstrate compliance with the obligations of this DPA and allow for and contribute to audits, including inspections, as mandated by a Supervisory Authority or reasonably requested no more than once a year by Customer and performed by an independent auditor as agreed upon by Customer and Company. The foregoing shall only extend to those documents and facilities relevant and material to the Processing of Customer Personal Data, and shall be conducted during normal business hours and in a manner that causes minimal disruption.
8.2. Company will inform Customer if Company believes that Customer’s instruction under Section 8.1 infringes Data Protection Law. Company may suspend the audit or inspection, or withhold requested information until Company has modified or confirmed the lawfulness of the instructions in writing. Company and Customer each bear their own costs related to an audit.
8.3. Company may retain some or all of the Customer Personal Data to the extent required by Data Protection Law or other applicable law.
**9. International Data Transfers**
9.1. Customer hereby authorizes Company to carry out International Data Transfers with respect to Customer Personal Data in accordance with Data Protection Law. Company shall Process and store Customer Personal Data in the geographic location where Customer Personal Data is submitted to the Services by Customer, or otherwise made available to Company and such Customer Personal Data will not be transferred to, or replicated in another geographical location unless authorized by Customer, or necessary to provide the Services to Customer..
9.2. Customer Personal Data may be processed in the United States or the EU. Transfer Mechanisms (e.g., Standard Contractual Clauses) will apply as needed. Data hosting locations are managed with the same security measures and protocols as defined herein. To the extent that Axiom Processes Customer Personal Data originating from and protected by Data Protection Laws in one of the jurisdictions listed in Schedule 4 (Jurisdiction Specific Terms), then the terms specified therein with respect to the applicable jurisdiction(s) will apply in addition to the terms of this DPA.
9.3. To the extent that Customer’s use of the Services requires an onward transfer mechanism to lawfully transfer personal data from a jurisdiction (i.e., the European Economic Area (“**EEA**\*”),\* the United Kingdom (“**UK**”), Switzerland or any other jurisdiction listed in Schedule 3) to Axiom located outside of that jurisdiction (a “**Transfer Mechanism**”), the terms and conditions of Schedule 3 (Cross Border Transfer Mechanisms) will apply.
9.4. If Company’s compliance with Data Protection Law applicable to International Data Transfers is affected by circumstances outside of Company’s control, including circumstances affecting the validity of an applicable legal instrument, Company and Customer will work together in good faith to reasonably resolve such non-compliance.
9.5. The parties agree that the data export solutions identified in this Section 9 will not apply if and to the extent that Company adopts an alternative data export solution for the lawful transfer of Customer Personal Data (as recognized under applicable Data Protection Laws), in which event, Customer shall reasonably cooperate with Company to implement such solution and such alternative data export solution will apply instead (but solely to the extent such alternative data export solution extends to the territories to which Customer Personal Data is transferred under this DPA).
**10. Notifications**
10.1. Customer will send all notifications, requests and instructions under this DPA to [privacy@axiom.co](mailto:privacy@axiom.co). Company will send all notifications under this DPA to Customer’s registered email address.
**11. Liability**
11.1. Notwithstanding anything to the contrary in this DPA, the Agreement, or otherwise, the limitations of liability specified in the Agreement shall apply to any and all Company liability and obligation arising under or otherwise related to this DPA.
**12. Termination and return or deletion**
12.1. This DPA is terminated upon the termination or expiration of the Agreement. Unless required or permitted by applicable law, Company will delete all remaining copies of Customer Personal Data within sixty (60) days following termination or expiration of the Agreement.
**13. Modification of this DPA**
13.1. This DPA may only be modified by a written amendment mutually agreed upon and signed by both Company and Customer.
**14. Invalidity and severability**
14.1. If any provision of this DPA is found by any court or administrative body of competent jurisdiction to be invalid or unenforceable, then the invalidity or unenforceability of such provision does not affect any other provision of this DPA and all provisions not affected by such invalidity or unenforceability will remain in full force and effect.
**Annex I**
**DETAILS OF PROCESSING**
**A. LIST OF PARTIES**
**COMPANY / ‘DATA IMPORTER’ DETAILS**
| | |
| ---------------------------------------- | ------------------------------------------------------------------------------------------ |
| **Name:** | Axiom, Inc. a Delaware corporation. |
| **Address:** | 1390 Market Street, Suite 200 San Francisco CA 94102 USA |
| **Contact Details for Data Protection:** | Available upon request. |
| **Activities:** | Axiom will process Personal Data as necessary to provide the Services under the Agreement. |
| **Role:** | Processor |
**CUSTOMER / ‘DATA EXPORTER’ DETAILS**
| | |
| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| **Name:** | The entity or other person who is a counterparty to the Agreement. |
| **Address:** | As specified in the Service Order to the Agreement. |
| **Contact Details for Data Protection:** | The Customer signatory to the Service Order. |
| **Customer Activities:** | The use the Services as part of its ongoing business operations under and in accordance with the Agreement. |
| **Role:** | Controller |
**B. DESCRIPTION OF PROCESSING / TRANSFER**
| | |
| ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Categories of Data Subjects whose Personal Data is transferred** | The Data Subjects whose Personal Data are processed by Company when providing the Services to Customer, including: Personal Data with respect to Customer’s customers, end users, employees, agents and partners (who are natural persons). |
| **Categories of Personal Data transferred** | The categories of Personal Data that are processed by Company when providing the Services to Customer, including: contact information (name, age, gender, address, telephone number, email address, etc.), and device identifiers and internet or electronic network activity (IP addresses, GAID/IDFA, browsing history, timestamps, etc.). |
| **Sensitive data transferred (if applicable) and applied restrictions or safeguards** | No sensitive data is processed under the Agreement. |
| **Frequency of Transfer** | Continuous basis for the duration of the Agreement. |
| **Nature and purpose(s) of the data transfer and Processing** | Company will process Personal Data as necessary to provide the Services under the Agreement. |
| **Retention period (or, if not possible to determine, the criteria used to determine the period)** | Personal Data will be retained for as long as necessary taking into account the purpose of the processing, and in compliance with applicable laws, including laws on the statute of limitations. |
| **For transfers to (sub-)processors, also specify subject matter, nature, and duration of the processing** | Company will restrict the onward Subprocessor’s access to Customer Personal Data only to what is strictly necessary to provide the Services. |
| **Identify the competent supervisory authority/ies in accordance with Clause 13** | Where the EU GDPR applies, the competent authority will be determined in accordance with Clause 13 of the Standard Contractual Clauses. Where the UK GDPR applies, the UK Information Commissioner's Office. |
**Annex II**
**TECHNICAL AND ORGANIZATIONAL SECURITY MEASURES**
**DPA - Technical and Organizational Security Measures Annex**
The Company will implement the following specific security measures, as applicable:
| | |
| -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Security Management** | Axiom maintains a comprehensive written information security program (ISP) that is aligned with leading security frameworks, including ISO 27001 and SOC 2. This program includes policies, processes, and controls governing the processing of Personal Data, designed to: (a) Secure Personal Data against accidental or unlawful loss, access, or disclosure; (b) Identify and manage reasonably foreseeable risks to the security of the Axiom Production Environment; and (c) Minimize security risks through continuous risk assessment and regular testing. For the purpose of this Schedule, the “Axiom Production Environment" means Axiom's cloud infrastructure, servers, networking services, assets, and hosting software and systems managed by Axiom within its cloud service providers (including Amazon Web Services (AWS) and Cloudflare) used to process or store Personal Data. |
| **Maintaining of an Information Security Policy** | Axiom's ISP is established and maintained in accordance with its **SOC 2 and ISO 27001 certifications**. The policies are regularly reviewed, updated, and communicated to all relevant personnel. Security policies and procedures clearly define information security responsibilities for all aspects of our service, including: Maintaining and reviewing security policies and procedures. Secure software development (SDLC), operation, and maintenance. Security incident response and escalation procedures. User access administration based on the Principle of Least Privilege. Monitoring and control of all systems within the Axiom Production Environment. |
| **Secure Networks and Systems** | To protect Personal Data, Axiom utilizes a multi-layered security approach, leveraging cloud-native technologies such as **Virtual Private Clouds (VPCs), security groups, network access control lists (NACLs), and web application firewalls (WAFs)**. These controls are configured to deny all traffic by default and only permit traffic required for the provision of the service, effectively isolating the Axiom Production Environment from untrusted networks. All network security configurations are documented, subject to change control, and reviewed regularly. |
| **Personal Data Protection Measures (including storage limitation, data minimization and retention and encryption)** | **Encryption:** All Personal Data is encrypted both **at rest** using strong encryption standards (e.g., AES-256) and **in transit** across public networks using industry-standard cryptographic protocols (e.g., TLS 1.2 or higher). We have documented procedures to protect cryptographic keys against misuse. **Data Minimization & Retention:** In line with our compliance obligations, including **HIPAA**, Axiom limits Personal Data storage to the minimum necessary for the provision of our services and enforces defined data retention and disposal policies. |
| **Vulnerability Management Efforts** | Axiom protects its systems against malicious software using advanced **endpoint detection and response (EDR)** solutions and automated malware scanning. We maintain secure systems and applications by: Establishing processes to continuously identify and remediate security vulnerabilities. Implementing strict change management procedures, including the separation of development, testing, and production environments. Personal Data is not used in non-production environments. Following a secure software development lifecycle (SDLC) that incorporates security reviews, code analysis, and testing throughout the development process. |
| **Access Control Measures** | Access to Personal Data is strictly restricted on a **need-to-know basis** (Principle of Least Privilege) and limited to authorized personnel for legitimate business purposes. This is achieved by: Utilizing a centralized **Identity and Access Management (IAM)** system with a default "deny-all" setting. Assigning individually unique IDs to all users and requiring **Multi-Factor Authentication (MFA)** for access to the Axiom Production Environment. Enforcing strong password complexity rules and implementing processes for timely provisioning, modification, and de-provisioning of user access. Automatically locking user accounts after repeated failed login attempts and terminating idle sessions. |
| **Restriction of Physical Access to Personal Data Processing Systems** | As a cloud-native company, Axiom does not own or operate physical data centers. We leverage premier cloud service providers (**AWS and Cloudflare**), which are responsible for the physical security of the data centers housing the Axiom Production Environment. These providers are leading global companies that maintain robust physical security programs with controls such as: 24/7/365 on-site security personnel. Biometric and electronic access control. Perimeter security, including fencing and video surveillance. Regular audits and certifications (e.g., **SOC 2, ISO 27001**). Axiom ensures that backups are encrypted, logically secured, and stored in geo-redundant locations. Media containing Personal Data is disposed of using secure data destruction techniques. |
| **Regular Monitoring and Testing of Networks** | Access to Recipient Network and Personal Data is monitored using mechanisms that allow tracking, alerting, and analysis on a regular basis as well as upon need. All systems that process Personal Data are provided with correct and consistent time and audit trails. Audit trails for critical systems are kept for, at least, one year. The security of our systems is regularly tested as part of our **ISO 27001 and SOC 2** compliance programs, including: **Quarterly** internal and external network vulnerability scans. **Annual** internal and external penetration tests conducted by a qualified third party. Test findings are tracked and remediated in a timely manner according to their severity. |
| **Incident Response Plan** | Axiom maintains a formal Incident Response Plan to ensure a timely and effective response to any security breach. The plan is tested regularly and includes procedures for identification, containment, eradication, and recovery, as well as breach notification procedures. Axiom also maintains a **Business Continuity and Disaster Recovery (BCDR)** plan, which includes data backup and recovery procedures that are tested regularly to ensure service availability. |
| **Third Party Risk Management Program** | Axiom maintains a formal **Third-Party Risk Management (TPRM)** program. Before engaging any new vendor or service provider that will access Personal Data or the Axiom Production Environment, we conduct a thorough due diligence process to assess their security and compliance posture. |
**SCHEDULE 3**
**CROSS BORDER DATA TRANSFER MECHANISM**
**1. Definitions**
a. **“Standard Contractual Clauses”** means, depending on the circumstances unique to any particular Customer, any of the following:
(i) UK Standard Contractual Clauses; and (ii) 2021 Standard Contractual Clauses.
b. “**UK Standard Contractual Clauses**” means:
(i) Standard Contractual Clauses for data controller to data processor transfers approved by the European Commission in decision 2010/87/EU (“**UK Controller to Processor SCCs**”); and
(ii) Standard Contractual Clauses for data controller to data controller transfers approved by the European Commission in decision 2004/915/EC (“**UK Controller to Controller SCCs”**).
c. "**2021 Standard Contractual Clauses**" means the Standard Contractual Clauses approved by the European Commission in decision 2021/914.
**2. UK Standard Contractual Clauses**. For data transfers from the United Kingdom that are subject to the UK Standard Contractual Clauses, the UK Standard Contractual Clauses will be deemed entered into (and incorporated into this Addendum by reference) and completed as follows:
a. The UK Controller to Processor SCCs will apply where Axiom is processing Customer Data. The illustrative indemnification clause will not apply. Schedule 1 serves as Appendix 1 of the UK Controller to Processor SCCs. Schedule 2 serves as Appendix 2 of the UK Controller to Processor SCCs.
b. The UK Controller to Controller SCCs will apply where Axiom is processing Usage Data. In Clause II(h), Axiom will process personal data in accordance with the data processing principles set forth in Annex A of the UK Controller to Controller SCCs. The illustrative commercial clause will not apply. Schedule 1 serves as Annex B of the UK Controller to Controller SCCs. Personal Data transferred under these clauses may only be disclosed to the following categories of recipients: i) Axiom’s employees, agents, Affiliates, advisors and independent contractors with a reasonable business purpose for needing such personal data; ii) Axiom vendors that, in their performance of their obligations to Axiom, must process such personal data acting on behalf of and according to instructions from Axiom; and iii) any person (natural or legal) or organisation to whom Axiom may be required by applicable law or regulation to disclose personal data, including law enforcement authorities, central and local government.
**3. The 2021 Standard Contractual Clauses**. For data transfers from the European Economic Area, the UK, and Switzerland that are subject to the 2021 Standard Contractual Clauses, the 2021 Standard Contractual Clauses will apply in the following manner:
a. Module One (Controller to Controller) will apply where Customer is a controller of Usage Data and Axiom is a controller of Usage Data.
b. Module Two (Controller to Processor) will apply where Customer is a controller of Customer Data and Axiom is a processor of Customer Data;
c. For each Module, where applicable:
(i) in Clause 7, the option docking clause will not apply;
(ii) in Clause 9, Option 2 will apply, and the time period for prior notice of sub-processor changes will be as set forth in Section 6 (Subprocessing) of this Addendum;
(iii) in Clause 11, the optional language will not apply;
(iv) in Clause 17 (Option 1), the 2021 Standard Contractual Clauses will be governed by Irish law.
(v) in Clause 18(b), disputes will be resolved before the courts of Ireland; (vi) In Annex I, Part A: Data Exporter: Customer and authorized Affiliates of Customer.
Contact Details: Customer’s account owner email address, or to the email address(es) for which Customer elects to receive privacy communications.
Data Exporter Role: The Data Exporter’s role is outlined in Section 3 of this Addendum Schedule.
Signature & Date: By entering into the Agreement, Data Exporter is deemed to have signed these Standard Contractual Clauses incorporated herein, including their Annexes, as of the Effective Date of the Agreement.
Data Importer: Axiom Inc.
Contact Details: Axiom Privacy Team – [privacy@axiom.co](mailto:privacy@axiom.co)
Data Importer Role: The Data Importer’s role is outlined in Section 3 of this Addendum Schedule.
Signature & Date: By entering into the Agreement, Data Importer is deemed to have signed these Standard Contractual Clauses, incorporated herein, including their Annexes, as of the Effective Date of the Agreement.
(vii) In Annex I, Part B:
The categories of data subjects are described in Schedule 1, Section 4.
The sensitive data transferred is described in Schedule 1, Section 6.
The frequency of the transfer is a continuous basis for the duration of the Agreement. The nature of the processing is described in Schedule 1, Section 1.
The purpose of the processing is described in Schedule 1, Section 1.
The period of the processing is described in Schedule 1, Section 3.
For transfers to sub-processors, the subject matter, nature, and duration of the processing is outlined at [https://axiom.co/legal/sub-processors](https://axiom.co/legal/sub-processors).
(viii) In Annex I, Part C: The Irish Data Protection Commission will be the competent supervisory authority.
(ix) Schedule 2 serves as Annex II of the Standard Contractual Clauses.
4\. As to the specific modules, the parties agree that the following modules apply, as the circumstances of the transfer may apply:
Controller-Controller - Module One
Controller-Processor - Module Two
5\. To the extent there is any conflict between the Standard Contractual Clauses and any other terms in this Addendum, including Schedule 4 (Jurisdiction Specific Terms), the provisions of the Standard Contractual Clauses will prevail.
**SCHEDULE 4**
**JURISDICTION SPECIFIC TERMS**
1\. California
a. The definition of “**Applicable Data Protection Law**” includes the California Consumer Privacy Act (“**CCPA**”).
b. The terms “**business**”, “**commercial purpose**”, “**service provider**”, “**sell**” and “**personal information**” have the meanings given in the CCPA.
c. With respect to Customer Data, Axiom is a service provider under the CCPA.
d. Axiom will not (a) sell Customer Data; (b) retain, use or disclose any Customer Data for any purpose other than for the specific purpose of providing the Services, including retaining, using or disclosing the Customer Data for a commercial purpose other than providing the Services; or (c) retain, use or disclose the Customer Data outside of the direct business relationship between Axiom and Customer.
e. The parties acknowledge and agree that the Processing of Customer Data authorized by Customer’s instructions described in Section 5 of this Addendum is integral to and encompassed by Axiom’s provision of the Services and the direct business relationship between the parties.
f. Notwithstanding anything in the Agreement or any Order Form entered in connection therewith, the parties acknowledge and agree that Axiom’s access to Customer Data does not constitute part of the consideration exchanged by the parties in respect of the Agreement.
g. To the extent that any Usage Data (as defined in the Agreement) is considered Personal Data, if and when Axiom is subject to the CCPA, Axiom is the business under the CCPA with respect to such data and will Process such data in accordance with its Privacy Policy. As of October 1, 2021 Axiom is not subject to the CCPA as a business.
2\. EEA
a. The definition of “**Applicable Data Protection Laws**” includes the General Data Protection Regulation (EU 2016/679)(“**GDPR**”).
b. When Axiom engages a Subprocessor under Section 6 (Subprocessing), it will:
(i) require any appointed Subprocessor to protect Customer Data to the standard required by Applicable Data Protection Laws, such as including the same data protection obligations referred to in Article 28(3) of the GDPR, in particular providing sufficient guarantees to implement appropriate technical and organizational measures in such a manner that the processing will meet the requirements of the GDPR; and
(ii) require any appointed Subprocessor to agree in writing to only process data in a country that the European Union has declared to have an “adequate” level of protection; or to only process data on terms equivalent to the Standard Contractual Clauses.
c. GDPR Penalties. Notwithstanding anything to the contrary in this Addendum or in the Agreement (including, without limitation, either party’s indemnification obligations), neither party will be responsible for any GDPR fines issued or levied under Article 83 of the GDPR against the other party by a regulatory authority or governmental body in connection with such other party’s violation of the GDPR.
3\. Switzerland
a. The definition of “Applicable Data Protection Laws” includes the Swiss Federal Act on Data Protection.
b. When Axiom engages a Subprocessor under Section 6 (Subprocessing), it will:
(i) require any appointed Subprocessor to protect Customer Data to the standard required by Applicable Data Protection Laws, such as including the same data protection obligations referred to in Article 28(3) of the GDPR, in particular providing sufficient guarantees to implement appropriate technical and organizational measures in such a manner that the processing will meet the requirements of the GDPR; and
(ii) require any appointed Subprocessor to agree in writing to only process data in a country that the European Union has declared to have an “adequate” level of protection; or to only process data on terms equivalent to the Standard Contractual Clauses.
4\. United Kingdom
a. References in this Addendum to GDPR will to that extent be deemed to be references to the corresponding laws of the United Kingdom (including the UK GDPR and Data Protection Act 2018).
b. When Axiom engages a Subprocessor under Section 6 (Subprocessing), it will:
(i) require any appointed Subprocessor to protect Customer Data to the standard required by Applicable Data Protection Laws, such as including the same data protection obligations referred to in Article 28(3) of the GDPR, in particular providing sufficient guarantees to implement appropriate technical and organizational measures in such a manner that the processing will meet the requirements of the GDPR; and
(ii) require any appointed Subprocessor to agree in writing to only process data in a country that the European Union has declared to have an “adequate” level of protection; or to only process data on terms equivalent to the Standard Contractual Clauses.
---
# HIPAA anti-retaliation policy
Source: https://axiom.co/docs/legal/hipaa
{/* vale off */}
Title II of the Federal Health Insurance Portability and Accountability Act (42 USC 1320d to 1329d-8, and Section 264 of Public Law 104191), and its accompanying Privacy Regulations, 45 CFR Parts 160 and 164, require that "covered entities," as defined by the HIPAA Privacy Regulations, refrain from any retaliatory acts targeted toward those who file complaints or otherwise report HIPAA violations or infractions. The purpose of this policy is to clearly state the position of Axiom.co on intimidation and retaliation. This policy applies to all workforce, volunteers, and management of Axiom.co.
Under no circumstances shall Axiom.co intimidate, threaten, coerce, discriminate against, or take other retaliatory action against any individual for:
1. The exercise of rights guaranteed under HIPAA, including the filing of a HIPAA complaint against Axiom.co;
2. The filing of a HIPAA complaint with the Secretary of HHS;
3. Testifying, assisting, or participating in a HIPAA investigation, compliance, review, proceeding, or hearing;
4. Opposing any act or practice that is counter to the HIPAA regulations, provided the individual or person has a good faith belief that the practice opposed is unlawful, and the manner of the opposition is reasonable and does not involve a disclosure of PHI in violation of HIPAA.
No retaliatory action against an individual or group involved in filing HIPAA complaints or otherwise reporting infractions will be tolerated.
Under no circumstances shall Axiom.co require any member(s) of its workforce, volunteers, or management to waive their rights under HIPAA.
All allegations of HIPAA retaliation against individuals will be reviewed and investigated by Axiom.co in a timely manner.
---
# Partner agreement
Source: https://axiom.co/docs/legal/partner-agreement
{/* vale Google.Contractions = NO */}
{/* vale Google.WordList = NO */}
## Agreement and acceptance [#agreement-and-acceptance]
Please read these terms carefully before applying to or participating in the Axiom Partner Program offered by Axiom, Inc. ("**Axiom**" or "**Company**") through the [Axiom Partner Portal](https://partners.dub.co/axiom) (the "**Axiom Partner Program**" or "**App**").
By applying to, joining, or otherwise participating in the App, you ("**Partner**" or "**you**") agree to be bound by these terms and the Partner Program Guide (together, the "**Agreement**"), to the exclusion of all other terms. You represent and warrant that you have authority to enter into this Agreement. If you enter into this Agreement on behalf of an organization or entity, references to "Partner" and "you" refer to that organization or entity. If you do not agree, you may not participate in the App. If this Agreement is considered an offer, acceptance is expressly limited to its terms.
This click-through Agreement governs participation as a Public Partner. Preferred, Strategic, and Feature-Attached partnerships require separate written terms agreed with Axiom.
If this Agreement conflicts with the Program Requirements, this Agreement controls, except that the Program Requirements control the operational terms expressly delegated to them, including the Products and Services, attribution mechanics, eligible revenue, reward rate, Reward Period, and payout mechanics.
## 1. Definitions [#1-definitions]
* **“Customer”** means a Qualified Lead that becomes a paying Axiom customer.
* **“Effective Date”** means the date Partner agrees to this Agreement.
* **“Fees”** means those sums that Axiom receives from its Customer and books within the applicable Reward Period, calculated in accordance with the eligible revenue provisions of the Program Requirements.
* **“Products and Services”** means the products and services listed in the Program Requirements.
* **“Program Requirements”** means the Axiom Partner Program Guide and related terms and conditions available at the following URL: [https://axiom.co/docs/legal/partner-program-guide](https://axiom.co/docs/legal/partner-program-guide).
* **“Prospect”** means a party that is not a current Axiom customer, on Axiom’s sales forecast, or previously referred to Axiom by any other party.
* **“Public Partner”** means a Partner accepted into the public partner model described in the Program Requirements.
* **“Qualified Lead”** means a Prospect whose Axiom organization is attributed to Partner in accordance with the Program Requirements.
* **“Referral Fee”** means the fees payable to Partner pursuant to Sections 3 and 4.
* **“Reward Period”** means the period specified in the Program Requirements during which Fees received from a Customer are eligible for Referral Fees.
## 2. Appointment and Duties [#2-appointment-and-duties]
### 2.1 Appointment [#21-appointment]
Axiom appoints Partner as marketer and promoter of the Products and Services. Such appointment shall be non-exclusive unless otherwise expressly agreed to by the Parties in writing.
### 2.2 Duties [#22-duties]
Axiom may provide Partner with access to sales tools, training, and marketing collateral. Partner may use those resources to promote Axiom Products and Services and refer Prospects to Axiom in accordance with this Agreement and the Program Requirements. Partner is not required to make a minimum number of referrals or undertake any minimum level of promotional activity. Joint marketing efforts shall be as mutually agreed by the parties, provided that all press releases, announcements, and other publicity hereunder must be mutually agreed in writing in advance. Each party shall comply with good business practices and shall conduct itself in a way that reflects favorably on the other party and its products and services. Each party is responsible for its own expenses incurred in connection with its performance of this Agreement, unless herein expressly provided otherwise.
### 2.3 No Authority [#23-no-authority]
Partner shall not without Axiom’s prior written approval, make any representation or warranty regarding Axiom products or services, including without limitation representations regarding prices, terms of delivery, performance, terms of payment or conditions of sale, other than as explicitly set forth in this Agreement or described in applicable published documents provided by Axiom to Partner from time to time in connection with this Agreement. Partner is not authorized to make offers, accept orders, negotiate, or sign contracts, or assume or create any other obligation or responsibility binding on Axiom, or transact any business in Axiom’s name other than the marketing of Axiom products and services as expressly permitted hereunder. Axiom shall have sole responsibility and discretion for determining whether or not to enter into a contract with any other party. Only Axiom may develop, supply, maintain, execute contracts for, invoice for, and support the Products and Services. Axiom has the right, in its sole discretion, to modify or to discontinue the distribution or availability of any of the Products or Services at any time without notice. Partner agrees to indemnify, defend, and hold harmless Axiom for any loss or third party claim against Axiom resulting from Partner’s breach of this Section 2.3.
### 2.4 Trademark License [#24-trademark-license]
During the term of this Agreement, Axiom grants to Partner a non-exclusive, non-transferable license to use trademarks, trade names, services marks, services names, logos and designations in or associated with Axiom products and services (collectively, “**Marks**”) solely in connection with marketing and promotion in accordance with this Agreement. Any use of a Mark by Partner must correctly attribute ownership of such Mark to Axiom or its suppliers, and must comply with applicable law and Axiom’s then-current Mark usage guidelines. At Axiom’s request, Partner will provide any materials using a Mark to Axiom for approval, which shall not be unreasonably withheld. If Axiom provides Partner with a Product for demonstration purposes, Partner will not remove or obscure any Mark on or in such Product, and will not attach any additional mark, logo or trade designation to such Product. Partner acknowledges and agrees that Axiom owns the Marks and that any and all goodwill or other proprietary right created by or resulting from Partner’s use of a Mark shall inure solely to Axiom’s benefit. Partner shall not be deemed, by virtue of displaying a Mark, to have acquired any right or interest to such Mark greater than those limited rights granted by this Section.
### 2.5 No Other License [#25-no-other-license]
Except for the limited Trademark License granted by Section 2.4 above, Axiom does not grant Partner any right or license to any intellectual property. Sole ownership of all intellectual property rights in or related to the Axiom products and services, and to any associated documentation, shall remain with Axiom or its suppliers.
## 3. Referral Qualification Process [#3-referral-qualification-process]
### 3.1 Prospects [#31-prospects]
Partner may refer Prospects using the unique referral link provided through the App. A Prospect becomes a Qualified Lead when the Prospect creates an Axiom organization that is attributed to Partner in accordance with the Program Requirements. Axiom may reject or remove an attribution if the Prospect does not satisfy the eligibility and attribution requirements in the Program Requirements.
### 3.2 Qualified Leads and Referral Activities [#32-qualified-leads-and-referral-activities]
Partner may, by mutual agreement with Axiom, provide business context, organize meetings, or otherwise assist Axiom’s sales efforts for a Qualified Lead. Partner is not required to participate in pre-sales activities unless separately agreed in writing.
### 3.3 Customers [#33-customers]
If a Qualified Lead begins paying for the corresponding Products and Services, that Qualified Lead becomes a Customer. A Qualified Lead’s attribution does not expire solely because it does not become a Customer within a particular period, subject to the eligibility and attribution requirements in the Program Requirements. Partner is not entitled to a Referral Fee unless a Qualified Lead becomes a Customer, and Referral Fees accrue only on Fees received during the applicable Reward Period.
## 4. Referral Fees [#4-referral-fees]
If Axiom receives and books Fees from a Customer within the applicable Reward Period, then, subject to all other provisions of this Agreement, Axiom shall pay to Partner a Referral Fee in accordance with the Program Requirements. The Referral Fee shall be due and payable in accordance with the payout terms set out in the Program Requirements, including any holding period, payout cycle, and minimum payout threshold specified therein. If Partner receives a Referral Fee from Axiom under this Agreement, Partner may not receive a referral, finder’s, or similar fee from Axiom with respect to the same transaction under any other agreement or arrangement. Partner agrees to reimburse Axiom for any overpaid amounts.
## 5. Confidential Information [#5-confidential-information]
In the course of performing its obligations hereunder, one party may disclose or deliver to the other party certain trade secrets or confidential or proprietary information. Any information that the receiving party knows or has reason to know is confidential or proprietary, either because such information is marked or otherwise identified by the disclosing party orally or in writing as confidential or proprietary, or because such information has commercial value but is not generally known in the relevant trade or industry, shall be deemed the disclosing party’s Confidential Information. Neither party shall disclose the other party’s Confidential Information to third parties other than its personnel, agents, and representatives who need to know and are legally bound to protect the confidentiality of such information, except to the extent required by law. Each party agrees that it shall not disclose the other party’s Confidential Information except on a need-to-know basis to such personnel who have agreed in writing to protect the confidentiality of such information. Neither party shall use, modify, copy, or reproduce the other party’s Confidential Information except as necessary to fulfill its obligations hereunder. All documents and other tangible objects containing or representing Confidential Information that have been disclosed by either party to the other party, and all copies thereof in the possession of the other party, shall be and remain the property of the disclosing party and shall be promptly returned on request. The restrictions contained in this Section 5 shall not apply to information already lawfully known to or independently developed by the receiving party, disclosed in published materials, generally known to the public, or lawfully obtained from a third party. For clarity, this Agreement, the Program Requirements, and information made publicly available by the disclosing party are not Confidential Information. A receiving party’s obligations hereunder shall survive until such time as the disclosing party’s Confidential Information disclosed hereunder becomes publicly known and made generally available through no action or inaction of the receiving party.
## 6. Term And Termination [#6-term-and-termination]
This Agreement will take effect on the Effective Date and will continue until terminated. Either party may terminate this Agreement for convenience on thirty (30) days’ written notice. Axiom may suspend Partner’s participation or payments while it reasonably investigates suspected fraud, prohibited promotion, or other misconduct. Axiom may terminate this Agreement immediately if required by law or if Axiom reasonably determines that Partner has engaged in fraud, self-referral, spam, unlawful conduct, or another prohibited promotion practice described in the Program Requirements. For any other material breach, the non-breaching party may terminate this Agreement if the breach is not cured within ten (10) days after written notice.
Upon termination, Partner remains entitled only to Referral Fees earned before the effective date of termination. No new Referral Fees accrue after the effective date of termination unless Axiom agrees otherwise in writing. Axiom may withhold, cancel, or offset amounts otherwise payable to Partner against refunds, chargebacks, overpayments, losses, damages, costs, and third-party claims that Axiom reasonably determines resulted from Partner’s breach, fraud, or prohibited conduct, to the extent permitted by law. Partner agrees to reimburse Axiom for any overpaid amounts. Sections 5 through 9, together with payment obligations accrued before termination, shall survive expiration or termination of this Agreement.
## 7. Warranty Disclaimer [#7-warranty-disclaimer]
COMPANY MAKES NO WARRANTY HEREUNDER, EITHER EXPRESS OR IMPLIED, AND SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF MERCHANTABILITY, NONINFRINGEMENT OR FITNESS FOR A PARTICULAR PURPOSE WITH RESPECT TO COMPANY PRODUCTS AND SERVICES.
## 8. Limitation on Liability [#8-limitation-on-liability]
EXCEPT FOR BREACH OF SECTION 5, IN NO EVENT SHALL COMPANY BE LIABLE FOR ANY INCIDENTAL, CONSEQUENTIAL OR OTHER INDIRECT LOSS OR DAMAGE, INCLUDING LOST PROFITS, ARISING OUT OF THIS AGREEMENT OR ANY OBLIGATION HEREUNDER, REGARDLESS OF THE THEORY OF LIABILITY OR FORM OF ACTION, WHETHER IN CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE. COMPANY’S ENTIRE LIABILITY FOR ANY CLAIM, LOSS, DAMAGE OR EXPENSE FROM ANY CAUSE WHATSOEVER, REGARDLESS OF THE THEORY OF LIABILITY OR FORM OF ACTION, WHETHER IN CONTRACT OR TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, SHALL BE LIMITED, IN THE AGGREGATE FOR ALL SUCH CLAIMS, TO DIRECT, PROVEN DAMAGES IN AN AMOUNT NOT TO EXCEED THE AMOUNTS DUE TO PARTNER HEREUNDER.
## 9. General [#9-general]
### 9.1 No Agency [#91-no-agency]
The parties hereto are independent contractors. Nothing herein shall be construed to give one party the power to direct or control the day-to-day activities of the other, or to allow either party to create or assume any obligation on behalf of the other party.
### 9.2 Notices [#92-notices]
Any notice hereunder shall be, with respect to the Partner, directed to the email address provided by Partner in connection with Partner’s Axiom Partner Program account creation; and with respect to Axiom, directed to the following email address [partners@axiom.co](mailto:partners@axiom.co).
### 9.3 Assignment [#93-assignment]
Neither party may assign or transfer this Agreement, in whole or in part, either voluntarily or by operation of law, without the prior written consent of the other party. Any attempt to do so shall be a material default of this Agreement and shall be void.
### 9.4 Governing Law [#94-governing-law]
This Agreement shall be interpreted according to the laws of California without regard to its choice-of-law principles. The parties hereto consent to the personal and exclusive jurisdiction of the state and federal courts in California, and agree that venue shall lie exclusively in Santa Clara County, California.
### 9.5 Force Majeure [#95-force-majeure]
If an event beyond a party’s reasonable control prevents it from performing any of its obligations hereunder, other than a payment obligation, the time for that party’s performance will be extended for the period of the delay or inability to perform due to such event; provided that if such period lasts longer than thirty days, the other party may terminate this Agreement.
### 9.6 Entire Agreement [#96-entire-agreement]
This Agreement constitutes the entire agreement between the parties hereto with respect to the subject matter hereof and supersedes all other prior agreements, representations, and statements with respect to such subject matter. Axiom may modify or update this Agreement or the Program Requirements in its discretion by publishing the updated terms and notifying Partner at the email address associated with Partner’s account. Unless otherwise stated, updates take effect on the earlier of (i) thirty (30) days after publication and notice or (ii) Partner's continued participation after notice. Changes required by law and changes that benefit Partner may take effect immediately. Updated terms apply to Fees and Referral Fees earned on or after their effective date, including those relating to existing Qualified Leads and Customers, but do not affect Referral Fees earned before that date. Partner’s continued participation after an update takes effect constitutes acceptance of the updated terms.
No failure of either party to exercise or enforce any of its rights under this Agreement shall act as a waiver of such right, and no waiver of any breach shall act as a waiver of a subsequent breach. This Agreement may be executed in counterparts, each of which shall be deemed an original, and all of which shall constitute one and the same Agreement. If any provision of this Agreement is held by a court of competent jurisdiction to be unenforceable, that provision will be enforced to the maximum extent permissible under applicable law and the other provisions of this Agreement will remain in full force and effect.
{/* vale Google.WordList = YES */}
{/* vale Google.Contractions = YES */}
---
# Partner program guide
Source: https://axiom.co/docs/legal/partner-program-guide
This Partner Program Guide was last updated on August 20, 2026. It constitutes the "Program Requirements" referenced in, forms part of, and is subject to the terms of the Axiom Partner Agreement, available at [https://axiom.co/docs/legal/partner-agreement](/legal/partner-agreement). The version published at [https://axiom.co/docs/legal/partner-program-guide](/legal/partner-program-guide) governs, subject to Section 8.
## Welcome [#welcome]
Axiom is the modern machine data platform. Teams use it to keep every log, event, trace, and metric economically, without the need for sampling or shortened retention. Thousands of organizations run on it, from breakout companies to enterprises moving petabyte-scale workloads off legacy platforms.
Good recommendations come from all kinds of people. The Axiom Partner Program rewards the people and companies who introduce Axiom to teams that should be using it, with a share of the revenue those introductions create rather than a token bounty for a click.
## The program at a glance [#the-program-at-a-glance]
| Program detail | Public Partner terms |
| -------------- | -------------------------------------------------------------------------------------------------------- |
| Reward | 5% of eligible revenue |
| Reward Period | 12 months beginning when the referred organization first becomes a paying Axiom customer |
| Reward form | Cash, or Axiom compute credits on request |
| Joining | Apply at [partners.dub.co/axiom](https://partners.dub.co/axiom); applications reviewed by the Axiom team |
## Partner types [#partner-types]
**Public Partner**: open to anyone approved into the program, including practitioners and advocates, creators and community builders, advisors and technology companies. Public Partners refer through a unique referral link and earn 5% of eligible revenue during each referred customer's Reward Period. The standard Public Partner terms are published in this guide and the Axiom Partner Agreement.
**Preferred Partner**: invitation-based, for companies that regularly bring qualified customer opportunities to Axiom. Preferred Partners register deals directly with the Axiom partner team and receive enhanced rewards and structured co-selling support. Commercial terms are agreed individually and set out in an exhibit to the partner's agreement.
**Strategic Partner**: invitation-based, for companies with deep customer relationships in a market or territory who lead opportunities at significant scale, including reselling arrangements (see the Reseller Addendum to the Axiom Partner Agreement). Commercial terms are agreed individually and set out in an exhibit to the partner's agreement.
**Feature-Attached Partner**: reserved for partners who have built and maintain Axiom-supported product integrations whose customer adoption is verifiable through product usage. Terms are agreed individually with the Axiom partner team.
The click-through Axiom Partner Agreement governs Public Partners. Preferred, Strategic, and Feature-Attached partnerships require separate written terms agreed with Axiom; those written terms control if they differ from this guide.
{/* vale Google.WordList = NO */}
To discuss Preferred, Strategic, or Feature-Attached partnership, contact **[partners@axiom.co](mailto:partners@axiom.co)** or mention it in your program application.
{/* vale Google.WordList = YES */}
## How it works (Public Partners) [#how-it-works-public-partners]
1. **Apply and get your link.** Apply at [partners.dub.co/axiom](https://partners.dub.co/axiom). Applications are reviewed by the Axiom team; approval is at Axiom's discretion. Once approved, you receive a unique referral link and access to a partner dashboard showing your referrals, commissions, and payouts.
2. **Make the introduction.** Share Axiom where it genuinely fits. When someone follows your link and signs up, the signup is attributed to you.
3. **Earn as they spend.** When the referred organization becomes a paying Axiom customer, its 12-month Reward Period begins. You earn 5% of eligible revenue from payments made during that period.
***
{/* vale Google.Contractions = NO */}
## Program Requirements [#program-requirements]
The following sections set out the operative requirements referenced by the Axiom Partner Agreement. Capitalized terms not defined here have the meanings given in the Agreement.
### 1. Products and Services [#1-products-and-services]
The Products and Services covered by the program are Axiom Cloud subscriptions and usage, as offered publicly by Axiom.
### 2. Eligibility and approval [#2-eligibility-and-approval]
{/* vale Google.WordList = NO */}
Individuals and entities may apply. Axiom reviews each application at its discretion and may decline an application, including for competitive conflict or restricted locations. Participation requires acceptance of the Axiom Partner Agreement. Once a Public Partner is approved, suspension and termination are governed by the Agreement.
{/* vale Google.WordList = YES */}
### 3. Referral attribution [#3-referral-attribution]
**Public Partners.** Following a partner's referral link sets a 90-day attribution cookie. If the person creates an Axiom organization during that window, the resulting organization is attributed to the partner and becomes a Qualified Lead. The 90-day Attribution Window applies only between the referral-link click and creation of the Axiom organization. Once attributed, the Qualified Lead remains attributed if it becomes a paying customer later, unless Axiom removes the attribution under the Agreement or these Program Requirements; the Reward Period does not begin until the organization becomes a paying customer. The Prospect must be new to Axiom: existing customers, prospects already engaged with Axiom's sales team, and prospects previously referred by another party cannot be attributed retroactively.
**Registered deals (Preferred and Strategic Partners).** A partner registers a named prospect with the Axiom partner team at [partners@axiom.co](mailto:partners@axiom.co). Axiom confirms or declines the registration in writing; a prospect qualifies only if it is not a current Axiom customer, not on Axiom's sales forecast, and not previously referred by another party. A confirmed registration is valid for **90 days** from Axiom's written confirmation and states its expiry date. If the prospect has not become a paying customer when the registration expires, the registration lapses and the prospect reverts to unregistered status; Axiom will extend a registration on written request where the partner is actively progressing the opportunity. A lapsed registration may be re-submitted if the prospect remains unclaimed.
### 4. Eligible revenue [#4-eligible-revenue]
For Public Partners, eligible revenue comprises the following, calculated on amounts the customer actually paid to Axiom:
* Axiom Cloud Platform Fee
* Compute credit purchases
* Data Loading Compute (usage-based)
* Query Compute (usage-based)
{/* vale Google.OxfordComma = NO */}
Excluded: storage, add-ons (including RBAC, Audit Log, SAML SSO, and Directory Sync), implementation or professional services, taxes, refunds, chargebacks, and credited or uncollected amounts.
{/* vale Google.OxfordComma = YES */}
For Preferred, Strategic, and Feature-Attached Partners, eligible revenue is defined in the partner's agreement exhibit.
### 5. Rewards and the Reward Period [#5-rewards-and-the-reward-period]
* **Public Partner reward:** 5% of eligible revenue.
* **Reward Period:** 12 months beginning when the referred organization first becomes a paying Axiom customer. There is no cap on eligible revenue within the Reward Period; no rewards accrue on revenue received after it ends.
* The Reward Period is separate from the 90-day Attribution Window described in Section 3. A Qualified Lead may become a paying customer after the Attribution Window has ended because its attribution was fixed when the Axiom organization was created.
* The 90-day registration validity for Preferred and Strategic registered deals is separate from both the Public Partner Attribution Window and the Reward Period.
### 6. Payouts [#6-payouts]
* Commissions become payable after a **30-day holding period** from the corresponding paid invoice (safeguarding against refunds and chargebacks), and are paid in the **next monthly payout cycle**.
* **Minimum payout: $20.** Balances below the minimum roll forward until reached.
* Payouts are made via the payout method connected in the partner dashboard; method availability and any receiving fees depend on the partner's location, per Dub's payout documentation.
* **Compute credits election:** partners with an active Axiom Cloud account may request rewards as Axiom compute credits of equivalent value instead of cash; contact [partners@axiom.co](mailto:partners@axiom.co) to elect this.
* Partners are responsible for their own tax obligations; tax documentation is collected through the partner dashboard where applicable.
### 7. Promotion rules [#7-promotion-rules]
These rules keep the program fair for every partner and keep referrals worth what they say they are. The following aren't permitted and may result in suspension or termination under the Agreement. As provided in the Agreement, Axiom may withhold, cancel, or offset amounts otherwise payable against losses resulting from a partner's breach, fraud, or prohibited conduct:
* Bidding on Axiom brand terms in paid search
* Misrepresenting Axiom's pricing, capabilities, or terms
* Posting referral links on coupon or deal sites
* Spam or unsolicited bulk outreach
* Self-referrals or referrals of entities the partner controls
* Making representations, warranties, or commitments on Axiom's behalf
### 8. Changes [#8-changes]
Axiom may update this guide from time to time in its discretion by publishing the updated terms and notifying Public Partners through the email address associated with their accounts. Unless otherwise stated, updates take effect on the earlier of 30 days after publication and notice or a partner's continued participation after notice. Changes required by law and changes that benefit partners may take effect immediately. Updated terms apply to rewards earned on or after their effective date, including rewards relating to existing Qualified Leads and customers, but do not affect rewards earned before that date.
### 9. Contact [#9-contact]
**[partners@axiom.co](mailto:partners@axiom.co)**: applications, deal registration, credits election, and all program questions.
---
# Privacy policy
Source: https://axiom.co/docs/legal/privacy
{/* vale off */}
At Axiom, Inc. (“Axiom”, “Company” or “we”), we take privacy and the security of data seriously. This policy (“Privacy Policy” or “Policy”) is established to help advise you about how we treat your personal data. By using or accessing any Company websites (collectively, “Sites”), you acknowledge awareness of the practices and policies outlined below, and hereby consent that we will collect, use and share your personal data as described in this Privacy Policy.
Remember that use of our Services is at all times subject to our Terms of Service available at the following URL: [https://axiom.co/docs/legal/terms-of-service](/legal/terms-of-service). Any terms used in this Policy that are otherwise undefined have the definitions given to them in our Terms of Use.
We may modify this Privacy Policy from time to time. When material modifications are made, we will alert you to any such changes by placing a notice on a Site, by sending you an email and/or by some other means. Please note that if you’ve opted not to receive legal notice emails from us (or haven’t provided us with a valid email address), those legal notices will still apply. If you use or access a Site after any changes to the Privacy Policy have been published on our website, you consent and agree to all of the changes.
### **Privacy Policy Table of Contents** [#privacy-policy-table-of-contents]
* What this Privacy Policy Covers
* Personal Data
* How We Disclose Your Personal Data
* Tracking Tools and Opt-Out
* Data Security
* Data Retention
* Personal Data of Children
* California Resident Rights
* Virginia Resident Rights
* Other State Law Privacy Rights
* European Union and United Kingdom Data Subject Rights
* Transfers of Personal Data
* Contact Information
### **What this Privacy Policy Covers** [#what-this-privacy-policy-covers]
Our Privacy Policy covers how we treat Personal Data that we gather when you access or use any Site. “Personal Data” means information that identifies or relates to a particular individual and includes information referred to as “personally identifiable information” or “personal information” under applicable data privacy laws, rules or regulations. Our Privacy Policy does not cover the practices of companies we don’t own or control or people we don’t manage.
### **Personal Data** [#personal-data]
#### **Categories of Personal Data We Collect** [#categories-of-personal-data-we-collect]
This chart details the categories of Personal Data that we collect and have collected over the past 12 months:
| Category of Personal Data | Examples of Personal Data We Collect | Categories of Third Parties With Whom We Share this Personal Data |
| :------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------- |
| Profile or Contact Data | First and last name Email address | Service Providers |
| Device/IP Data | IP Address Domain Server Type of device, operating system, browser used to access service | Service Providers |
| Web Analytics | Referring webpage, source through which users accessed the Services Non-identifiable request IDs Statistics associated with the interaction between device or browser and Services Browsing or search history | Service Providers |
| Geolocation Data | IP address-based location information | Service Providers |
#### **Categories of Sources of Personal Data** [#categories-of-sources-of-personal-data]
Personal Data about you is collected from the following categories of sources:
* When you provide such information directly to us.
* When you create an account or use our interactive tools or Sites.
* When you voluntarily provide information in free-form text boxes through the Sites or through responses to surveys or questionnaires.
* When you send us an email or otherwise contact us.
* When you use Sites such information is collected automatically, by us and/or third parties.
* Through Cookies (defined in [Cookies and Similar Technologies](/legal/cookies) ).
* If you use a location-enabled browser, we and/or third parties may receive information about your location.
* If you download and install certain applications and software we make available, we and/or third parties may receive and collect information transmitted from your computing device for the purpose of providing you the relevant Sites, such as information regarding when you are logged on and available to receive updates or alert notices.
#### **Third Parties** [#third-parties]
* Vendors
* We may use analytics providers to analyze how you interact and engage with Sites, or third parties may help us provide you with customer support.
* We may use vendors to obtain information to generate leads and create user profiles.
#### **Our Business Purposes for Collecting or Disclosing Personal Data** [#our-business-purposes-for-collecting-or-disclosing-personal-data]
* Providing, Customizing and Improving Sites
* Creating and managing your account or other user profiles.
* Processing orders or other transactions; billing.
* Providing you with the products, services or information you request.
* Meeting or fulfilling the reason you provided the information to us.
* Providing support and assistance regarding Sites
* Improving the Sits, including testing, research, internal analytics and product development.
* Doing fraud protection, security and debugging.
* Corresponding with You
* Responding to correspondence that we receive from you, contacting you when necessary or requested, and sending you information regarding the Company or Sites.
* Sending emails and other communications according to your preferences or that display content that we think will interest you.
* Meeting Legal Requirements and Enforcing Legal Terms
* Fulfilling our legal obligations under applicable law, regulation, court order or other legal process, such as preventing, detecting and investigating security incidents and potentially illegal or prohibited activities.
We will not collect additional categories of Personal Data or use the Personal Data we collected for materially different, unrelated or incompatible purposes without providing you notice as is described above.
#### **How We Disclose Your Personal Data** [#how-we-disclose-your-personal-data]
We disclose your Personal Data to categories of service providers and other parties listed in this section. Some of these disclosures may constitute a “sale” of your Personal Data as defined under applicable laws. For more information, please refer to the state-specific sections below.
* Service Providers. These parties help us provide the Services or perform business functions on our behalf. They include:
* Hosting, technology and communication providers.
* Analytics providers
* Support and customer service vendors.
* Payment processors.
* Our payment processing partner Stripe, Inc. (“Stripe”) collects your voluntarily-provided payment card information necessary to process your payment.
* Please see Stripe’s terms of service and privacy policy for information on its use and storage of your Personal Data.
### **Fulfilling Legal Obligations** [#fulfilling-legal-obligations]
We may share any Personal Data that we collect with third parties in relation to the activities set forth under “Meeting Legal Requirements and Enforcing Legal Terms” in the “Our Business Purposes for Collecting Personal Data” section above.
### **Business Transfers** [#business-transfers]
Personal Data collected may be transferred to a third party if we undergo a merger, acquisition, bankruptcy or other transaction in which such third party assumes control of our business (in whole or in part). In such an event, we will make reasonable efforts to notify you before your information becomes subject to different privacy and security policies and practices as authorized or mandated by applicable law.
### **Data that is Not Personal Data** [#data-that-is-not-personal-data]
We may create aggregated, de-identified or anonymized data from the Personal Data we collect, including by removing information that makes the data personally identifiable to a particular user. We may use such aggregated, de-identified or anonymized data and share it with third parties for our lawful business purposes, including to analyze, build and improve the Services and promote our business, provided that we will not share such data in a manner that could identify you.
### **Tracking Tools and Opt-Out** [#tracking-tools-and-opt-out]
The Services use cookies and similar technologies such as pixel tags, web beacons, clear GIFs and JavaScript (collectively, “Cookies”) to enable our servers to recognize your web browser, tell us how and when you visit and use our Services, analyze trends, learn about our user base and operate and improve our Services. Cookies are small pieces of data– usually text files – placed on your computer, tablet, phone or similar device when you use that device to access our Services. We may also supplement the information we collect from you with information received from third parties, including third parties that have placed their own Cookies on your device(s).
### **We use the following types of Cookies:** [#we-use-the-following-types-of-cookies]
* Essential Cookies. Essential Cookies are required for providing you with features or services that you have requested. For example, certain Cookies enable you to log into secure areas of our Services. Disabling these Cookies may make certain features and services unavailable.
* Functional Cookies. Functional Cookies are used to record your choices and settings regarding our Services, maintain your preferences over time and recognize you when you return to our Services. These Cookies help us to personalize our content for you, greet you by name and remember your preferences (for example, your choice of language or region).
* Performance/Analytical Cookies. Performance/Analytical Cookies allow us to understand how visitors use our Services. They do this by collecting information about the number of visitors to the Services, what pages visitors view on our Services and how long visitors are viewing pages on the Services. Performance/Analytical Cookies also help us measure the performance of our advertising campaigns to help us improve our campaigns and Services’ content for those who engage with our advertising.
You can decide whether or not to accept Cookies through your internet browser’s settings. Most browsers have an option for turning off the Cookie feature, which will prevent your browser from accepting new Cookies, as well as (depending on the sophistication of your browser software) allow you to decide on acceptance of each new Cookie in a variety of ways. You can also delete all Cookies that are already on your device. If you do this, however, you may have to manually adjust some preferences every time you visit our website and some of the Services and functionalities may not work.
To find out more information about Cookies generally, including information about how to manage and delete Cookies, please visit [https://allaboutcookies.org/](https://allaboutcookies.org/) or [https://ico.org.uk/for-the-public/online/cookies/](https://ico.org.uk/for-the-public/online/cookies/) if you are located in the European Union.
**Information from third party sites**. Our Sites include interfaces that allow you to connect with third party sites, such as when you create an account on our Sites by logging in to your Google account. If you connect to a third party site through the Sites, you authorize us to access, use and store the information that you agreed the third party site could provide to us based on your settings on that third party site. We will access, use and store that information in accordance with this Privacy Policy. You can revoke our access to the information you provide in this way at any time by amending the appropriate settings from within your account settings on the applicable third party site.
**Information Collected Automatically.** We may automatically log information about you and your computer or mobile device when you access our Sites. For example, we may log your operating system name and version, manufacturer and model, device identifier, browser type, screen resolution, the website you visited before browsing to our Sites, pages you viewed, how long you spent on a page, access times, general location information such as city, state or geographic area, and information about your use of and actions on our Sites. We collect this information about you using cookies. Please refer to the [Cookies and Similar Technologies](/legal/cookies) section for more details.
### **Website Monitoring, Recording, and Analytics** [#website-monitoring-recording-and-analytics]
When you interact with Sites, we and our service providers may collect information regarding your interactions in real time, including pages visited, search queries, navigation paths, mouse movements, scrolling activity, clicks, and information entered into forms or similar features. We may use analytics, session replay, or similar technologies to understand how you and users interact with our Sites, improve functionality, and identify technical or security issues. These technologies may record interactions as they occur and are configured to exclude or mask sensitive information, such as passwords or payment details. Our analytics, monitoring, and support providers process this information solely on our behalf, act as our service providers and agents, and are contractually restricted from using such information for their own independent purposes.
**By accessing or using our sites, you consent to the monitoring, recording, and collection of your interactions as described above.**
### **Data Security** [#data-security]
We endeavor to protect your Personal Data from unauthorized access, use and disclosure using appropriate physical, technical, organizational and administrative security measures based on our Services,the type of Personal Data being collected and how we are processing that data. You should also help protect your data by selecting and protecting your password and/or other sign-on mechanism(s) with care; limiting access to your computer or device and browser; and signing off after you have finished accessing your account. Although we work to protect the security of your account and other data that we hold in our records, be aware that no method of transmitting data over the internet or storing data is completely secure.
More information about our security and related compliance measures can be found here:
### **Data Retention** [#data-retention]
We retain Personal Data about you for as long as reasonably necessary to provide you with our Services or otherwise in support of our business or commercial purposes for utilization of your Personal Data, as expressed. When establishing a retention period for particular categories of data, we consider who we collected the data from, our need for the Personal Data, why we collected the Personal Data, and the sensitivity of the Personal Data. In some cases we retain Personal Data for a longer period, if doing so is necessary to comply with our legal obligations, resolve disputes or collect fees owed, or as is otherwise permitted or required by applicable law, rule or regulation. We may further retain information in an anonymous or aggregated form where such information would not identify you personally.
For example:
* We retain your profile information and credentials for as long as you have an account with us.
* We retain your payment data for as long as we need to process your purchase or subscription.
* We retain your device/IP data for as long as we need it to ensure that our systems are working appropriately, effectively and efficiently.
### **Personal Data of Children** [#personal-data-of-children]
As noted in the Terms of Use, we do not knowingly collect or solicit Personal Data from children under 13 years of age; if you are a child under the age of 13, please do not attempt to register for or otherwise use the Services or send us any Personal Data. If we learn we have collected Personal Data from a child under 13 years of age, we will delete that information as quickly as possible. If you believe that a child under 13 years of age may have provided Personal Data to us, please contact us at [privacy@axiom.co](mailto:privacy@axiom.co).
### **California Resident Rights** [#california-resident-rights]
If you are a California resident, you have the rights set forth in this section. Please see the “Exercising Your Rights” section below for instructions regarding how to exercise these rights. Please note that we may process Personal Data of our customers’ end users or employees in connection with our provision of certain services to our customers. If we are processing your Personal Data as a service provider, you may contact the entity that collected your Personal Data in the first instance to address your rights with respect to such data as desired.
If there are any conflicts between this section and any other provision of this Privacy Policy and you are a California resident, the portion that is more protective of Personal Data shall control to the extent of such conflict. If you have any questions about this section or whether any of the following rights apply to you, please contact us at [privacy@axiom.co](mailto:privacy@axiom.co).
### **Access** [#access]
You have the right to request certain information about our collection and use of your Personal Data over the past 12 months. In response, we will provide you with the following information:
* The categories of Personal Data that we have collected about you.
* The categories of sources from which that Personal Data was collected.
* The business or commercial purpose for collecting or selling your Personal Data.
* The categories of third parties with whom we have shared your Personal Data.
* The specific pieces of Personal Data that we have collected about you.
If we have disclosed your Personal Data to any third parties for a business purpose over the past 12 months, we will identify the categories of Personal Data shared with each category of third party recipient. If we have sold your Personal Data over the past 12 months, we will identify the categories of Personal Data sold to each category of third party recipient.
### **Deletion** [#deletion]
You have the right to request that we delete the Personal Data that we have collected about you. Under the CCPA, this right is subject to certain exceptions: for e.g., we may need to retain your Personal Data to provide you with the Services or complete a transaction or other action you may have requested, or if deletion of your Personal Data involves disproportionate effort to achieve. If your deletion request is subject to one of these exceptions, we may deny your deletion request to such data.
### **Correction** [#correction]
You have the right to request that we correct any inaccurate Personal Data we have collected about you. Under the CCPA, this right is subject to certain exceptions: for example, if we reasonably decide, based on the totality of circumstances related to your Personal Data, that such data is correct. If your correction request is subject to one of these CCPA exceptions, we may deny your request to correct such data.
### **Processing of Sensitive Personal Information Opt-Out** [#processing-of-sensitive-personal-information-opt-out]
Consumers have certain rights over the processing of their sensitive information. However, we do not intentionally collect sensitive categories of personal information, but it is possible to share sensitive information with us through your use of the Services. It is your responsibility not to share any such sensitive information when you use the Services.
### **Personal Data Sales Opt-Out and Opt-In** [#personal-data-sales-opt-out-and-opt-in]
We will not sell your Personal Data, and have not done so over the last 12 months. To our knowledge, we do not sell the Personal Data of minors under 16 years of age. Under the CCPA, California residents have certain rights when a business “shares” Personal Data with third parties for purposes of cross-contextual behavioral advertising. We have shared the foregoing categories of Personal Data for the purposes of cross-contextual behavioral advertising.
Under California Civil Code Sections 1798.83-1798.84, California residents are entitled to contact us to prevent disclosure of Personal Data to third parties for such third parties’ direct marketing purposes; in order to submit such a request, please contact us at [privacy@axiom.co](mailto:privacy@axiom.co).
Your browser may offer you a “Do Not Track” option, which allows you to signal to operators of websites and web applications and services that you do not wish such operators to track certain of your online activities over time and across different websites. Our Services do not support Do Not Track requests at this time. To find out more about “Do Not Track,” you can visit [www.allaboutdnt.com](https://www.allaboutdnt.com/).
### **Virginia Resident Rights** [#virginia-resident-rights]
If you are a Virginia resident, you have the rights set forth under the Virginia Consumer Data Protection Act (“VCDPA”). Please see the “Exercising Your Rights” section below for instructions regarding how to exercise these rights. Please note that we may process Personal Data of our customers’ end users or employees in connection with our provision of certain services to our customers. If we are processing your Personal Data as a service provider, you should contact the entity that collected your Personal Data in the first instance to address your rights with respect to such data. Additionally, please note that these rights are subject to certain conditions and exceptions under applicable law, which may permit or require us to deny your request.
If there are any conflicts between this section and any other provision of this Privacy Policy and you are a Virginia resident, the portion that is more protective of Personal Data shall control to the extent of such conflict. If you have any questions about this section or whether any of the following rights apply to you, please contact us at [privacy@axiom.co](mailto:privacy@axiom.co).
### **Access** [#access-1]
You have the right to request confirmation of whether or not we are processing your Personal Data and to access your Personal Data.
### **Correction** [#correction-1]
You have the right to correct inaccuracies in your Personal Data, to the extent such correction is appropriate in consideration of the nature of such data and our purposes of processing your Personal Data.
### **Portability** [#portability]
You have the right to request a copy of your Personal Data in a machine-readable format, to the extent technically feasible.
### **Deletion** [#deletion-1]
You have the right to delete your Personal Data.
### **Opt-Out of Certain Processing Activities** [#opt-out-of-certain-processing-activities]
* You have the right to opt-out of the processing of your Personal Data for targeted advertising purposes. We do not process your Personal Data for targeted advertising purposes.
* You have the right to opt-out to the sale of your Personal Data. We do not currently sell your Personal Data as defined under the VCDPA.
* You have the right to opt-out from the processing of your Personal Data for the purposes of profiling in furtherance of decisions that produce legal or similarly significant effects to you, if applicable.
### **Appealing a Denial** [#appealing-a-denial]
If we refuse to take action on a request within a reasonable period of time after receiving your request in accordance with this section, you may appeal our decision. In such an appeal, you must (1) provide sufficient information to allow us to verify that you are the person about whom the original request pertains and to clearly identify the original request, and (2) provide a sufficient description of the basis of your appeal. Please note that your appeal will be subject to your rights and obligations afforded to you under the VCDPA. We will respond to your appeal within 60 days of receiving your request. If we deny your appeal, you have the right to contact the Virginia Attorney General using the methods described at [https://www.oag.state.va.us/consumer-protection/index.php/file-a-complaint](https://www.oag.state.va.us/consumer-protection/index.php/file-a-complaint).
You may appeal a decision by us using the following methods:
* Email us at: [privacy@axiom.co](mailto:privacy@axiom.co) (title must include “VCDPA Appeal”)
* Call us at: (628) 200-3079
### **Exercising Your Rights under CCPA** [#exercising-your-rights-under-ccpa]
To exercise the rights described in this Privacy Policy, you or, if you are a California resident, your Authorized Agent (as defined below) can send us a request that (1) provides sufficient information to allow us to adequately verify that you are the person about whom we have collected Personal Data, and (2) describes your request in sufficient detail to allow us to understand, evaluate and respond ( a “Valid Request”). We are not obligated to respond to requests that do not meet these criteria. We will only use Personal Data provided in a Valid Request to verify your identity and complete your request.
We are committed to respond to Valid Requests within the time frame required by applicable law. We will not charge you a fee for making a Valid Request unless your Valid Request(s) is excessive, repetitive or manifestly unfounded. If we determine that your Valid Request warrants a fee, we will notify you of the fee and explain that decision before completing your request.
You may submit a Valid Request using the following methods:
* Email us at: [privacy@axiom.co](mailto:privacy@axiom.co)\
Call us at: (628) 200-3079
If you are a California resident, you may also authorize an agent (an “Authorized Agent”) to exercise your rights on your behalf.
### **We Will Not Discriminate Against You for Exercising Your Rights** [#we-will-not-discriminate-against-you-for-exercising-your-rights]
We will not discriminate against you for exercising your rights under applicable data protection laws. We will not deny you our goods or services, charge you different prices or rates, or provide you a lower quality of goods and services if you exercise your rights under applicable law. However, we may offer different tiers of our Services, as allowed by applicable law, with varying prices, rates or levels of quality of the goods or services you receive related to the value of Personal Data that we receive from you.
## **Other State Law Privacy Rights** [#other-state-law-privacy-rights]
### **Nevada Resident Rights** [#nevada-resident-rights]
If you are a resident of Nevada, you have the right to opt-out of the sale of certain Personal Data to third parties. You can exercise this right by contacting us at [privacy@axiom.co](mailto:privacy@axiom.co) with the subject line “Nevada Do Not Sell Request” and providing us with your name and the email address associated with your account.
## **European Union and United Kingdom Data Subject Rights** [#european-union-and-united-kingdom-data-subject-rights]
### **EU and UK Residents** [#eu-and-uk-residents]
If you are a resident of the European Union (“EU”), United Kingdom (“UK”), Lichtenstein, Norway or Iceland, you may have additional rights under the EU or UK General Data Protection Regulation (the “GDPR”) with respect to your Personal Data, as outlined below.
We use the terms “Personal Data” and “processing” as they are defined in the GDPR in this section, but “Personal Data” generally means information that can be used to individually identify a person, and “processing” generally covers actions that can be performed in connection with data such as collection, use, storage and disclosure. Company will be the controller of your Personal Data processed in connection with the Services.
If there are any conflicts between this section and any other provision of this Privacy Policy, the policy or portion that is more protective of Personal Data shall control to the extent of such conflict. If you have any questions about this section or whether any of the following applies to you, please contact us at [privacy@axiom.co](mailto:privacy@axiom.co). Note that we may also process Personal Data of our customers’ end users or employees in connection with our provision of certain services to you, in which case we are the processor of Personal Data. If we are the processor of your Personal Data, please contact the controller party in the first instance to address your rights with respect to such data.
### **Personal Data We Collect** [#personal-data-we-collect]
The “Categories of Personal Data We Collect” section above details the Personal Data that we collect from you.
### **Personal Data Use and Processing Grounds** [#personal-data-use-and-processing-grounds]
The “Our Commercial or Business Purposes for Collecting Personal Data” section above explains how we use your Personal Data.
We will only process your Personal Data if we have a lawful basis for doing so. Lawful bases for processing include consent, contractual necessity and our “legitimate interests” or the legitimate interest of others, as further described below.
* Contractual Necessity: We process the following categories of Personal Data as a matter of “contractual necessity”, meaning that we need to process the data to perform under our Terms of Use with you, which enables us to provide you with the Services. When we process data due to contractual necessity, failure to provide such Personal Data will result in your inability to use some or all portions of the Services that require such data.
* Profile or Contact Data
* Payment Data
* Legitimate Interest: We process the following categories of Personal Data when we believe it furthers the legitimate interest of us or third parties:
* Device/IP Data
* Web Analytics
* We may also de-identify or anonymize Personal Data to further our legitimate interests.
* Examples of these legitimate interests include (as described in more detail above):
* Providing, customizing and improving the Services.
* Marketing the Services.
* Corresponding with you.
* Meeting legal requirements and enforcing legal terms.
* Completing corporate transactions.
* Consent: In some cases, we process Personal Data based on the consent you expressly grant to us at the time we collect such data.
* Other Processing Grounds: From time to time we may also need to process Personal Data to comply with a legal obligation, if it is necessary to protect the interests of you or other data subjects, or if it is necessary in the public interest.
### **Sharing Personal Data** [#sharing-personal-data]
The “How We Share Your Personal Data” section above details how we share your Personal Data with third parties.
### **EU Data Subject Rights** [#eu-data-subject-rights]
For more information about these EU or UK personal data terms and your rights related thereto, or to submit a request for information, please email us at [privacy@axiom.co](mailto:privacy@axiom.co). Please note that in some circumstances, we may not be able to fully comply with your request, such as if it is frivolous or impractical, if it jeopardizes the rights of others, or if it is not required by law, but, in those circumstances, we are committed to respond to notify you of such a decision regardless. In some cases, we may also need you to provide us with additional information, which may include Personal Data, if necessary to verify your identity and the nature of your request.
Access: You can request more information about the Personal Data we hold about you and request a copy of such Personal Data. You can also access certain of your Personal Data by logging on to your account.
Rectification: If you believe that any Personal Data we are holding about you is incorrect or incomplete, you can request that we correct or supplement such data. You can also correct some of this information directly by logging on to your account.
Erasure: You can request that we erase some or all of your Personal Data from our systems.
Withdrawal of Consent: If we are processing your Personal Data based on your consent, you have the right to withdraw your consent at any time. Please note, however, that if you exercise this right, you may have to then provide express consent on a case-by-case basis for the use or disclosure of certain of your Personal Data, if such use or disclosure is necessary to enable you to utilize some or all of our Services.
Portability: You can ask for a copy of your Personal Data in a machine-readable format. You can also request that we transmit the data to another controller where technically feasible.
Objection: You can contact us to let us know that you object to the further use or disclosure of your Personal Data for certain purposes, such as for direct marketing purposes.
Restriction of Processing: You can ask us to restrict further processing of your Personal Data.
Right to File Complaint: You have the right to lodge a complaint about Company's practices with respect to your Personal Data with the supervisory authority of your country or EU Member State. A list of Supervisory Authorities is available here: [https://edpb.europa.eu/about-edpb/board/members\_en](https://edpb.europa.eu/about-edpb/board/members_en)
### **Transfers of Personal Data** [#transfers-of-personal-data]
The Services are hosted and operated in the United States (“U.S.”) through Company and its service providers. By using the Services, you acknowledge that any Personal Data about you is being provided to Company in the U.S. and will be hosted on U.S. servers, and you authorize Company to transfer, store and process your information to and in the U.S., and possibly other countries. In some circumstances, your Personal Data may be transferred to the U.S. pursuant to a data processing agreement incorporating legally required data protection clauses.
### **Contact Information:** [#contact-information]
If you have additional questions about this Privacy Policy, the methods in which we collect and use your Personal Data or your choices and rights regarding such collection and use, please do not hesitate to contact us at:
* [https://axiom.co](https://axiom.co)
* [privacy@axiom.co](mailto:privacy@axiom.co)
* Axiom, Inc., 1390 Market Street, Suite 200, San Francisco, CA 94102
---
# SLA
Source: https://axiom.co/docs/legal/sla
{/* vale off */}
Axiom is committed to delivering a reliable, performant, and secure data platform. We want our customers to have full confidence in the Axiom Service, backed by transparent commitments. This Service Quality document covers:
1. **Service availability** and corresponding SLAs
2. **Priorities, support response times, and escalation**
3. **Incident management and communications**
Please note this Axiom Service Quality document is subject to the agreement between Customer and Axiom with respect to the Axiom Service (the “Agreement”). All terms not otherwise defined herein are defined as set forth in the Agreement.
## Service availability [#service-availability]
### Scope [#scope]
This Axiom Service Level Agreement (“SLA”) describes the service availability regarding the Axiom Service specified in the applicable Service Description or otherwise ordered by Customer. This SLA applies to the core functionality of the applicable Axiom Service: components such as data ingestion, query execution, alerting, and access to the Axiom Console and API; it does not apply to preview features unless otherwise noted herein.
### Availability commitments [#availability-commitments]
Axiom provides the following target uptime (the “Monthly Uptime Percentage” or “MUP”) with respect to Axiom Cloud:
| Axiom Service | Monthly Uptime Percentage |
| :------------ | :----------------------------- |
| Axiom Cloud | At least 99.9% (“three nines”) |
Axiom measures MUP on a calendar-month basis by taking the total minutes in a calendar month, subtracting any Scheduled Downtime and Exclusions, and then calculating how many of the remaining minutes the Axiom service was available.
### Scheduled and unscheduled downtime [#scheduled-and-unscheduled-downtime]
* **Scheduled Downtime:** means the maintenance windows that Axiom communicates to Customer at least seven (7) days in advance. Axiom strives to limit Scheduled Downtime to three (3) hours per month.
* **Unscheduled Downtime**: means any period of time the Axiom Service is unavailable, other than Scheduled Downtime or Exclusions. For example, system failures, unplanned service degradations, or regional outages.
* **Exclusions:** means any of the following:
* emergency maintenance;
* circumstances or events beyond the reasonable control of Axiom, including without limitation, any Force Majeure events;
* the performance or availability of local internet-service-providers engaged by Customer, and outages directly traceable to external providers (e.g., cloud platforms, DNS);
* issues resulting from Customer’s use of third-party hardware, software, or systems, network, firewalls, or infrastructure preventing normal Axiom usage;
* use by Customer of the Axiom Service not in strict compliance with the applicable Documentation;
* incidents caused by misuse, negligence, or unapproved modifications of Axiom Services;
* Unscheduled Downtime with respect to any Axiom Service made available on a no-fee or trial basis, or for which Customer has not paid to Axiom all of the applicable fees;
* Services clearly labelled “Preview”; and
* any issues resulting from changes to a Customer’s configuration of the Axiom Service.
**“Incident**” means a failure to meet the applicable MUP due to Unscheduled Downtime.
### Service credits [#service-credits]
If an Incident occurs with respect to Axiom Service , Customer may request credits with respect to such Axiom Service (“Credits”). To receive Credits, Customer must meet the following requirements:
* Notify the Axiom support team within thirty (30) days of the date the Incident occurred with the following phrase in the title: “SLA Incident” (the “Notice”);
* Notice must include: logs and supporting information reasonably necessary for Axiom to confirm the SLA Issue; and dates and times with respect to the SLA Issue.
Once verified by Axiom, Credits will be issued as a percentage of Customer’s monthly (or prorated) bill for the affected Axiom Service. Customer acknowledges and agrees that notwithstanding anything to the contrary: (a) the Credit is the sole and exclusive remedy with respect to any SLA Issue; (b) the Credit may only be used by Customer to reduce the applicable monthly fees with respect to future payment obligations regarding the Axiom Service impacted by the Incident; (c) Credits may not be converted into cash, cash equivalents, or entitle Customer to a refund; (d) any unused Credits shall expire and be of no use following the expiration or termination of the applicable Service Order or the Agreement; and (e) Credits may not be used to reduce the applicable monthly fees by more than fifty percent (50%).
The table below shows how Credits are calculated:
| Monthly Uptime Percentage | Service Credit Percentage |
| :------------------------------------- | :------------------------ |
| **Axiom Cloud:** \< 99.9% but >= 99.0% | 10% |
| **Axiom Cloud:** \< 99.0% but >= 95.0% | 25% |
| **Axiom Cloud:** \< 95.0% | 50% |
## Priorities, support response times, and escalation [#priorities-support-response-times-and-escalation]
### Bug resolution [#bug-resolution]
Axiom investigates all reported Issues. Axiom uses commercially reasonable efforts to fix or provide a workaround as set forth in this Service Quality document. If Axiom needs more time to address an Issue, Axiom will escalate internally and keep Customer informed regarding progress.
“Issue” means an incident that investigation reveals is caused by the Axiom Service’s failure to perform materially in accordance with the specifications set forth in the Documentation for such Axiom Service. An incident will not be classified as an Issue if (a) the relevant Axiom Service is not used for its intended purpose; (b) the incident is caused by Customer’s or a third party’s software or equipment; or (c) the version of the Axiom Service on which the Issue has purportedly occurred is not the most current version of such Axiom Service made available to Customer under the Agreement.
### Priority levels and escalation [#priority-levels-and-escalation]
Axiom offers **Standard** and **Premium** support. Standard support is included for all paying customers. Premium support is available as an add-on. Axiom classifies Issues by priority, ensuring faster responses and more frequent updates for critical issues.
| Priority | Description | Standard Response | Premium Response | Update Frequency |
| :---------------- | :---------------------------------------------------------------------------------------------- | :---------------- | :--------------- | :---------------------------------- |
| **Critical** (P1) | Issue results in complete system failure or critical business process disrupted. | 3 hours (24x7) | 1 hour (24x7) | Hourly |
| **High** (P2) | Issue results in partial system failures or disruptions to important business processes. | 1 business day | 4 hours (24x7) | Every 4 hours during business hours |
| **Medium** (P3) | Issue results in minor system failures or disruptions to non-critical business processes. | 2 business days | 1 business day | Weekly |
| **Low** (P4) | Issue results in minor issues or requests that do not significantly affect business operations. | 3 business days | 2 business days | On material updates |
For Critical, High, and Medium Issues that require additional attention, Axiom offers a tiered escalation process:
1. Technical Customer Support Engineer
2. Head of Product
3. VP of Engineering
4. CTO
Escalations to these levels are not automatic but are considered based on the nature and urgency and impact of the Issue. Axiom’s support team will manage this process, ensuring that the right people are involved at the right time.
#### Escalating a request [#escalating-a-request]
* If your request is already being handled by Customer Support, reply in the existing support thread and request an escalation.
* If you have a new request, write an email to [support@axiom.co](mailto:support@axiom.co) with "Escalation Request" in the subject line.
Our team monitors these channels closely and will respond promptly to escalation requests.
### Business hours [#business-hours]
Axiom Customer Support is offered during business hours as set forth below:
* **Business hours**: 8:00 AM – 6:00 PM Eastern Time (US) on weekdays, excluding U.S. public holidays.
* **EU support**: For EU-based requests, 8:00 AM – 6:00 PM ET on weekdays, excluding local public holidays.
## Incident management and communications [#incident-management-and-communications]
Axiom continuously monitors systems and has an on-call rotation that spans multiple time zones. For real-time visibility of incidents and maintenance, visit [status.axiom.co](https://status.axiom.co). In the event of **Critical** (P1) or **High** (P2) issues:
1. We will post updates to [status.axiom.co](https://status.axiom.co) (at least hourly during business hours).
2. Once resolved, we will share a post-mortem for Critical (P1) issues detailing what happened, how we mitigated the Issue, and how we plan to prevent future Issues.
An Issue will be considered resolved when one of the following has been completed:
1. a resolution to the Issue is made available to Customer;
2. a computer software code change in the form of a patch or a new revision that corrects the Issue is made available to Customer;
3. a short-term workaround is made available to Customer; or
4. an engineering commitment is made to correct the Issue in a future release of the Axiom Service.
Axiom is not obligated to correct any Issue or issue that meets any of the following conditions:
1. where the Axiom Service is not used for its intended purpose; or
2. where the Axiom Service has been altered, damaged, modified in a manner not approved in writing by Axiom; or
3. where the Axiom Service is a version that is no longer supported by Axiom; or
4. which is caused by Customer’s or a third party’s software, equipment, network or system;
5. which is caused by Customer’s negligence, abuse, misapplication, or use of the Axiom Service other than as specified in the Documentation; or
6. which would be resolved by the Customer using an error correction or update regarding the Axiom Service.
Customer acknowledges that new features may be added to the Axiom Service based on market demand and technological innovation. Accordingly, as Axiom develops enhanced versions of the Axiom Service, Axiom may cease to maintain and support older versions.
---
# Terms of service
Source: https://axiom.co/docs/legal/terms-of-service
{/* vale off */}
PLEASE READ THESE TERMS OF SERVICE CAREFULLY BEFORE USING THE SERVICE OFFERED BY AXIOM, INC. (“**AXIOM**”). BY MUTUALLY EXECUTING ONE OR MORE SERVICE ORDERS WITH AXIOM WHICH REFERENCE THESE TERMS (EACH, A “**SERVICE** **ORDER**”) OR BY ACCESSING OR USING THE SERVICES IN ANY MANNER, YOU (“**YOU**” OR “**CUSTOMER**”) AGREE TO BE BOUND BY THESE TERMS (TOGETHER WITH THE APPLICABLE SERVICE DESCRIPTION, THE “**AGREEMENT**”) TO THE EXCLUSION OF ALL OTHER TERMS. YOU REPRESENT AND WARRANT THAT YOU HAVE THE AUTHORITY TO ENTER INTO THIS AGREEMENT; IF YOU ARE ENTERING INTO THIS AGREEMENT ON BEHALF OF AN ORGANIZATION OR ENTITY, REFERENCES TO “CUSTOMER” AND “YOU” IN THIS AGREEMENT, REFER TO THAT ORGANIZATION OR ENTITY. IF YOU DO NOT AGREE TO ALL OF THE FOLLOWING, YOU MAY NOT USE OR ACCESS THE SERVICES IN ANY MANNER. IF THE TERMS OF THIS AGREEMENT ARE CONSIDERED AN OFFER, ACCEPTANCE IS EXPRESSLY LIMITED TO SUCH TERMS.
## 1 SCOPE OF SERVICE AND RESTRICTIONS [#1-scope-of-service-and-restrictions]
**1.1 Access to and Scope of Service**. Subject to Axiom’ receipt of the applicable Fees with respect to the service specified in the corresponding Service Description (the “**Service**”), Axiom will use commercially reasonable efforts to make the Service available to Customer as set forth in this Agreement. Subject to Customer’s compliance with the terms and conditions of the Agreement, Customer may access and use the Service as specified in the Service Description and the applicable Supplemental Terms. ”**Service Description**” means the applicable use limitations, fees, use period, Supplemental Terms and related limitations with respect to the applicable Service. The applicable Service Description is available on the Axiom website, presented in connection with billing or invoicing, or as specified in a Service Order.
**1.2 Supplemental Terms**. The Service is available in a number of versions, packages and implementation types (each an “**Offering**”). Each Offering may be subject to additional requirements, use limitation and associated specifics with respect to the operation and use of such Offering (the “**Supplemental Terms**”). The Supplemental Terms will be specified in the applicable Service Description.
**1.3 Trials.** If Customer is accessing or making use of the Service on a trial basis or no-fee basis as identified in the corresponding Service Description (the “**Trial**”), Customer may use the Service during the Trial provided that (a) access or such use does not to exceed the scope of the corresponding Service Description; (b) Customer acknowledges and agrees that the Trial is made available on an “as-is” basis without support, warranty, or indemnification; and (c) Axiom shall have no liability or obligation with respect to any Trial.
**1.4 Restrictions**. Customer will use the Service only in accordance with all applicable laws, including, but not limited to, rules and regulations related to data and personally identifiable information. Customer agrees not to, and will not allow any third party to: (i) remove or otherwise alter any proprietary notices or labels from the Service or any portion thereof; (ii) reverse engineer, decompile, disassemble, or otherwise attempt to discover the underlying structure, ideas, or algorithms of the Service or any software used to provide or make the Service available; (iii) rent, resell or otherwise allow any third party access to or use of the Service; (iv) use or access the Service in any manner inconsistent with the applicable Service Description; or (v) use or access of the Service in any manner inconsistent with the Axiom Acceptable Use Policy available at the following URL: [https://axiom.co/docs/legal/acceptable-use-policy](https://axiom.co/docs/legal/acceptable-use-policy) (the “**AUP**”).
**1.5 Ownership**. Axiom retains all right, title, and interest in and to the: the Service, Documentation, Axiom Confidential Information; any improvements to and derivative works of the same; Axiom Templates; and all other intellectual property created, used, provided, or made available by Axiom under or in connection with the Service (collectively, “**Axiom IP**”). Customer may from time to time provide suggestions, comments, or other feedback to Axiom with respect to the Service or Documentation (“**Feedback**”). Customer shall, and hereby does, grant to Axiom a nonexclusive, worldwide, perpetual, irrevocable, transferable, sublicensable, royalty-free, fully paid-up license to use the Feedback for any purpose.
**1.6 Customer Data**. Customer is solely responsible for Customer Data including, but not limited to: (a) compliance with all applicable laws and this Agreement; (b) any claims relating to Customer Data; and (c) any claims that Customer Data infringes, misappropriates, or otherwise violates the rights of any third party. Customer acknowledges and agrees that Customer Data may be irretrievably deleted after fifteen (15) days following a termination or expiration of this Agreement. Customer authorizes Axiom to use Customer Data as necessary to provide the Service to Customer. For purposes of this Agreement, “**Customer Data**” shall mean any data, information or other material provided, uploaded, or submitted by Customer to the Service in the course of using the Service. Customer shall retain all right, title and interest in and to the Customer Data, including all intellectual property rights therein.
**1.7 Telemetry Data** Axiom may collect or otherwise receive Telemetry Data and use the same in connection with improvements to the Service, and to monitor Customer’s compliance with the Service Description and the terms of this Agreement. “**Telemetry Data**” shall mean data and information generated by or collected by Axiom regarding Customer’s use of the Service, the health and performance of the Service, and related information, excluding any Customer Data. Telemetry Data will be held in aggregated and anonymized format and will not identify Customer, or reveal any Customer Confidential Information.
**1.8 Personal Data.** Customer acknowledges and agrees that the exchange of personal information subject to applicable personal data laws or regulations (“PII”) is not required to make use of the Service, and to the extent Customer transfers, submits, or otherwise makes PII available to Axiom or the Service, Customer agrees to Axiom’s Data Processing Agreement available at the following URL: [https://axiom.co/docs/legal/data-processing](https://axiom.co/docs/legal/data-processing) (the “DPA”).
**1.9 Support**. To the extent Axiom support is specified in the applicable Service Description, Axiom will use commercially reasonable efforts to provide support for the Service according to the Axiom Support Policy available at the following URL: [https://axiom.co/support](https://axiom.co/support) (“**Axiom Support**”).
**1.10 Service Suspension**. Axiom may suspend Customer’s access to or use of the Service as follows: (a) immediately if Axiom reasonably believes Customer’s use of the Service may pose a security risk to or may adversely impact the Service; (b) immediately if Customer become insolvent, has ceased to operate in the ordinary course, made an assignment for the benefit of creditors, or becomes the subject of any bankruptcy, reorganization, liquidation, dissolution or similar proceeding; (c) following thirty (30) days written notice if Customer is in breach of this Agreement or any Service Description (and has not cured such breach, if curable, within the thirty (30) days of such notice); or (d) Customer has failed to pay Axiom the Fees with respect to the Service. If any amount owing by Customer is thirty (30) or more days overdue (or 10 or more days overdue in the case of invoices to be paid by credit card), Axiom may, without limiting any rights and remedies, accelerate Customer’s unpaid fee obligations to become immediately due and payable, and suspend the provision of the Service to Customer until the overdue amounts are paid in full.
## 2 FEES, TAXES, AND AUTHORIZED RESELLERS [#2-fees-taxes-and-authorized-resellers]
**2.1 Fees and Invoicing Terms**. Customer shall pay to Axiom the fees as set forth in each applicable Service Description according to the billing frequency and method stated therein or otherwise presented to Customer (the “**Fees**”). Customer shall provide accurate and updated billing contact information. If Fees are not received by Axiom by the due date, then without limiting Axiom’ rights or remedies: (a) those charges may accrue late interest at the rate of 1.5% of the outstanding balance per month, or the maximum rate permitted by law, whichever is lower, and (b) Axiom may condition future renewals and Service Descriptions on different payment terms.
**2.2 Taxes**. Any and all payments made by Customer in accordance with this Agreement are exclusive of any taxes that might be assessed by any jurisdiction. Customer shall pay or reimburse Axiom for all value-added, sales, use, property, and similar taxes; all customs duties, import fees, stamp duties, license fees and similar charges; and all other mandatory payments to government agencies of whatever kind, except taxes imposed on the net or gross income of Axiom. All amounts payable to Axiom under this Agreement shall be without set-off and without deduction of any taxes, levies, imposts, charges, withholdings or duties of any nature which may be levied or imposed, including without limitation, value added tax, customs duty and withholding tax. To the extent Customer is required by the local taxing authority to withhold value added tax or a similar withholding tax, Customer agrees to true-up Fees payable to Axiom to account for such withholding.
**2.3 Authorized Resellers**. Customer may purchase subscriptions to the Service through a third party authorized in writing by Axiom to resell subscriptions to the Service (an “**Authorized Reseller**”). Service subscriptions resold to Customer by an Authorized Reseller (each a “**Resale Transaction**”) are subject to the terms and conditions of this Agreement, other than Sections 2.1, and 2.2. Customer will pay the Authorized Reseller the applicable fees according to the payment terms, fees, refund rights (if any), and associated commercial terms determined by and between Customer and the corresponding Authorized Reseller.
## 3 TERM AND TERMINATION [#3-term-and-termination]
**3.1 Term**. The term of this Agreement shall commence on the Effective Date and unless terminated earlier according to this Section 3, will end on the last day of the term specified in the Service Description (the “**Term**”). Unless otherwise specified in the Service Description or the applicable Service Order, each Service Description will renew automatically at the end of the applicable term (each such renewal, a “**Service Renewal**”), unless either party provides to the other advance written notice with respect to non-renewal at least thirty (30) days prior to the end of the then current term. Customer acknowledges and agrees that each Service Renewal shall be subject to the then-current, on-demand standard use rates, unless otherwise specified in the applicable Service Description.
**3.2 Termination**. This Agreement and the Service Descriptions hereunder may be terminated: (a) by either party if the other has materially breached this Agreement, within thirty (30) calendar days after written notice of such breach to the other party if the breach is remediable or immediately upon notice if the breach is not remediable; or (b) by Axiom upon written notice to Customer if Customer (i) has made or attempted to make any assignment for the benefit of its creditors or any compositions with creditors, (ii) has any action or proceedings under any bankruptcy or insolvency laws taken by or against it which have not been dismissed within sixty (60) days, (iii) has effected a compulsory or voluntary liquidation or dissolution, or (iv) has undergone the occurrence of any event analogous to any of the foregoing under the law of any jurisdiction.
**3.3 Effect of Termination**. Upon any expiration or termination of this Agreement, Customer shall (i) immediately cease use of the Service, and (ii) return all Axiom Confidential Information and other materials and information provided by Axiom. Any termination or expiration shall not relieve Customer of its obligation to pay all Fees accruing prior to termination. If the Agreement is terminated due to Section 3.2 (a), Customer shall pay to Axiom all Fees set forth in the corresponding Service Description(s).
**3.4 Survival.** The following provisions will survive termination of this Agreement: Sections 1.4, 1.5, 1.7, 2.1, 2.2, 3, 4, 5, 6.3, 7, and 8.
## 4 CONFIDENTIALITY [#4-confidentiality]
During the term of this Agreement, either party may provide the other party with confidential and/or proprietary materials and information (“**Confidential Information”**). All materials and information provided by the disclosing party and identified at the time of disclosure as “Confidential” or bearing a similar legend, and all other information that the receiving party reasonably should have known was the Confidential Information of the disclosing party, shall be considered Confidential Information. This Agreement is Confidential Information, and all pricing terms are Axiom Confidential Information. The receiving party shall maintain the confidentiality of the Confidential Information and will not disclose such information to any third party without the prior written consent of the disclosing party. The receiving party will only use the Confidential Information internally for the purposes contemplated hereunder. The obligations in this Section 4 shall not apply to any information that: (a) is made generally available to the public without breach of this Agreement, (b) is developed by the receiving party independently from and without reference to the Confidential Information, (c) is disclosed to the receiving party by a third party without restriction, or (d) was in the receiving party’s lawful possession prior to the disclosure and was not obtained by the receiving party either directly or indirectly from the disclosing party. The receiving party may disclose Confidential Information as required by law or court order; provided that, the receiving party provides the disclosing with prompt written notice thereof and uses the receiving party’s best efforts to limit disclosure. At any time, upon the disclosing party’s written request, the receiving party shall return to the disclosing party all disclosing party’s Confidential Information in its possession, including, without limitation, all copies and extracts thereof.
## 5 INDEMNIFICATION [#5-indemnification]
**5.1 Indemnification by Customer**. Customer will defend, indemnify, and hold Axiom, its affiliates, suppliers and licensors harmless and each of their respective officers, directors, employees and representatives from and against any claims, damages, losses, liabilities, costs, and expenses (including reasonable attorneys’ fees) arising out of or relating to any third party claim with respect to: (a) Customer Data; (b) breach of this Agreement or violation of applicable law by Customer; or (c) alleged infringement or misappropriation of third-party’s intellectual property rights resulting from Customer Data.
**5.2 Indemnification by Axiom**. Axiom will defend, indemnify, and hold Customer harmless from and against any third-party claims, damages, losses, liabilities, costs, and expenses (including reasonable attorneys’ fees) arising from claims by a thirty party that Customer’s use of the Service directly infringes or misappropriates a third party’s intellectual property rights (an “**Infringement Claim**”). Notwithstanding anything to the contrary, Axiom shall have no obligation to indemnify or reimburse Customer with respect to any Infringement Claim to the extent arising from: (a) the combination of any Customer Data with the Service; (b) the combination of any products or services, other than those provided by Axiom to Customer under this Agreement, with the Service; or (c) non-discretionary designs or specifications provided to Axiom by Customer that caused such Infringement Claim. Customer agrees to reimburse Axiom for any and all damages, losses, costs and expenses incurred as a result of any of the foregoing actions.
**5.3 Notice of Claim and Indemnity Procedure**. In the event of a claim for which a party seeks indemnity or reimbursement under this Section 5 (each an “**Indemnified Party**”) and as conditions of the indemnity, the Indemnified Party shall: (a) notify the indemnifying party in writing as soon as practicable, but in no event later than thirty (30) days after receipt of such claim, together with such further information as is necessary for the indemnifying party to evaluate such claim; and (b) the Indemnified Party allows the indemnifying party to assume full control of the defense of the claim, including retaining counsel of its own choosing. Upon the assumption by the indemnifying party of the defense of a claim with counsel of its choosing, the indemnifying party will not be liable for the fees and expenses of additional counsel retained by any Indemnified Party. The Indemnified Party shall cooperate with the indemnifying party in the defense of any such claim. Notwithstanding the foregoing provisions, the indemnifying party shall have no obligation to indemnify or reimburse for any losses, damages, costs, disbursements, expenses, settlement liability of a claim or other sums paid by any Indemnified Party voluntarily, and without the indemnifying party’s prior written consent, to settle a claim. Subject to the maximum liability set forth in Section 7, the provisions of this Section 5 constitute the entire understanding of the parties regarding each party’s respective liability under this Section 5, including but not limited to Infringement Claims (including related claims for breach of warranty) and each party’s sole obligation to indemnify and reimburse any Indemnified Party.
## 6 WARRANTY [#6-warranty]
**6.1 Warranty.** The Service, when used by Customer in accordance with the provisions of this Agreement and in compliance with the Service documentation published by Axiom (the “**Documentation**”), will conform in material respects, to the Documentation during the period of use specified in the applicable Service Description.
**6.2 Exclusive Remedies.** Customer shall report to Axiom, pursuant to the notice provision of this Agreement, any breach of the warranties set forth in this Section 6. In the event of a breach of warranty by Axiom under this Agreement, Customer’s sole and exclusive remedy, and Axiom’ entire liability, shall be prompt correction of any material non-conformance in order to minimize any material adverse effect on Customer’s business.
**6.3 Disclaimer of Warranty**. Axiom does not represent or warrant that the operation of the Service (or any portion thereof) will be uninterrupted or error free, or that the Service (or any portion thereof) will operate in combination with other hardware, software, systems, or data not provided by Axiom, except as expressly specified in the applicable Documentation. CUSTOMER ACKNOWLEDGES THAT, EXCEPT AS EXPRESSLY SET FORTH IN SECTION 6.1, AXIOM MAKES NO EXPRESS OR IMPLIED REPRESENTATIONS OR WARRANTIES OF ANY KIND WITH RESPECT TO THE SERVICE OR SERVICES, OR THEIR CONDITION. AXIOM IS FURNISHING THE WARRANTIES SET FORTH IN SECTION 6.1 IN LIEU OF, AND AXIOM HEREBY EXPRESSLY EXCLUDES, ANY AND ALL OTHER EXPRESS OR IMPLIED REPRESENTATIONS OR WARRANTIES, WHETHER UNDER COMMON LAW, STATUTE OR OTHERWISE, INCLUDING WITHOUT LIMITATION ANY AND ALL WARRANTIES AS TO MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, SATISFACTORY QUALITY, NON-INFRINGEMENT OF THIRD-PARTY RIGHTS.
## 7 LIMITATIONS OF LIABILITY [#7-limitations-of-liability]
IN NO EVENT SHALL AXIOM BE LIABLE FOR ANY, LOST PROFITS, BUSINESS INTERRUPTION, REPLACEMENT SERVICE OR OTHER SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, OR INDIRECT DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THEORY OF LIABILITY. AXIOM’S LIABILITY FOR ALL CLAIMS ARISING UNDER THIS AGREEMENT, WHETHER IN CONTRACT, TORT OR OTHERWISE, SHALL NOT EXCEED THE AMOUNT OF FEES PAID OR PAYABLE BY CUSTOMER UNDER THE APPLICABLE SERVICE DESCRIPTION DURING THE TWELVE (12) MONTH PERIOD PRECEDING THE CLAIM.
## 8 MISCELLANEOUS [#8-miscellaneous]
**8.1 Export Control**. Customer hereby certifies that Customer will comply with all current applicable export control laws applicable to Axiom Confidential Information, Customer’s use of the Service, and Customer Data. Customer agrees to defend, indemnify and hold Axiom harmless from any liability for Customer’s violation of any applicable export control laws.
**8.2 Compliance with Laws.** Customer shall comply with all applicable laws and regulations in its use of the Service and with respect to Customer Data, including without limitation the unlawful gathering or collecting, or assisting in the gathering or collecting of information in violation of any privacy laws or regulations. Customer shall, at its own expense, defend, indemnify and hold harmless Axiom from and against any and all claims, losses, liabilities, damages, judgments, government or federal sanctions, costs and expenses (including attorneys’ fees) incurred by Axiom arising from any claim or assertion by any third party of violation of privacy laws or regulations by Customer or any of its agents, officers, directors or employees.
**8.3 Assignment**. Neither party may transfer and assign its rights and obligations under this Agreement without the prior written consent of the other party. Notwithstanding the foregoing, Axiom may transfer and assign its rights under this Agreement without consent from the other party in connection with a change in control, acquisition or sale of all or substantially all of its assets.
**8.4 Force Majeure**. Neither party shall be responsible for failure or delay in performance by events out of their reasonable control, including but not limited to, acts of God, Internet outage, terrorism, war, fires, earthquakes and other disasters (each a “**Force Majeure**”). Notwithstanding the foregoing: (i) Customer shall be liable for payment obligations for Service rendered; and (ii) if a Force Majeure continues for more than thirty (30) days, either party may to terminate this agreement upon written notice to the other party.
**8.5 Notice**. All notices between the parties shall be in writing and shall be deemed to have been given if personally delivered or sent by registered or certified mail (return receipt), or by recognized courier service.
**8.6 No Agency**. Both parties agree that no agency, partnership, joint venture, or employment is created as a result of this Agreement. Customer does not have any authority of any kind to bind Axiom.
**8.7 Governing Law**. This Agreement and all matters relating to this Agreement shall be construed in accordance with and controlled by the laws of the State of California, without reference to its conflict of law principles. The parties agree to submit to the non-exclusive jurisdiction and venue of the courts located in Santa Clara, California and hereby waive any objections to the jurisdiction and venue of such courts.
**8.8 Entire Agreement**. This Agreement is the complete and exclusive statement of the mutual understanding of the parties and supersedes and cancels all previous written and oral agreements, communications, and other understandings relating to the subject matter of this Agreement, and all waivers and modifications must be in a writing signed by both parties, except as otherwise provided herein. Any term or provision of this Agreement held to be illegal or unenforceable shall be, to the fullest extent possible, interpreted so as to be construed as valid, but in any event the validity or enforceability of the remainder hereof shall not be affected. In the event of a conflict between this Agreement, the Service Description, or Supplemental Terms, the terms of this Agreement shall control.
---
# Terms of use
Source: https://axiom.co/docs/legal/terms-of-use
{/* vale off */}
These Terms of Use constitute a legally binding agreement made between you, whether personally or on behalf of an entity ("**you**") and Axiom, Inc., its affiliates or agents ("**Company**", "**we**", or "**our"**) concerning your access to and use of the axiom.co website as well as any other media form, media channel, mobile website or mobile application related, linked, or otherwise connected thereto (collectively, the "**Site**"). In the event that you are registering for a user account, evaluating our hosted / platform as a service-based service or buying paid-for services from Company, the Terms of Service [https://axiom.co/docs/legal/terms-of-service](/legal/terms-of-service) apply and shall govern your use of such services. We are registered in Delaware, United States and have our registered office at Axiom, Inc. 1390 Market Street, Suite 200, San Francisco, CA 94102. You agree that by accessing the Site, you have read, understood, and agreed to be bound by all of these Terms of Use. IF YOU DO NOT AGREE WITH ALL OF THESE TERMS OF USE, THEN YOU ARE EXPRESSLY PROHIBITED FROM USING THE SITE AND YOU MUST DISCONTINUE USE IMMEDIATELY.\
\
We reserve the right, in our sole discretion, to make changes or modifications to these Terms of Use from time to time. We will alert you about any changes by updating the “Last updated” date of these Terms of Use, and you waive any right to receive specific notice of each such change. Please ensure that you check the applicable Terms every time you use our Site so that you understand which Terms apply. You will be subject to, and will be deemed to have been made aware of and to have accepted, the changes in any revised Terms of Use by your continued use of the Site after the date such revised Terms of Use are posted.\
\
The information provided on the Site is not intended for distribution to or use by any person or entity in any jurisdiction or country where such distribution or use would be contrary to law or regulation or which would subject us to any registration requirement within such jurisdiction or country. Accordingly, those persons who choose to access the Site from other locations do so on their own initiative and are solely responsible for compliance with local laws, if and to the extent local laws are applicable.\
\
The Site is not tailored to comply with industry-specific regulations (Health Insurance Portability and Accountability Act (HIPAA), Federal Information Security Management Act (FISMA), etc.), so if your interactions would be subjected to such laws, you may not use this Site. You may not use the Site in a way that would violate the Gramm-Leach-Bliley Act (GLBA).\
\
The Site is intended for users who are at least 18 years old. Persons under the age of 18 are not permitted to use or register for the Site.
Unless otherwise expressly indicated herein, the Site is our proprietary property and all source code, databases, functionality, software, website designs, audio, video, text, photographs, and graphics on the Site (collectively, the “**Content**”) and the trademarks, service marks, and logos contained therein (the “**Marks**”) are owned or controlled by us or licensed to us, and are protected by copyright and trademark laws and various other intellectual property rights and unfair competition laws of the United States, international copyright laws, and international conventions. The Content and the Marks are provided on the Site “AS IS” for your information and personal use only. Except as expressly provided in these Terms of Use, no part of the Site and no Content or Marks may be copied, reproduced, aggregated, republished, uploaded, posted, publicly displayed, encoded, translated, transmitted, distributed, sold, licensed, or otherwise exploited for any commercial purpose whatsoever, without our express prior written permission.\
\
Provided that you are eligible to use the Site, you are granted a limited license to access and use the Site and to download or print a copy of any portion of the Content to which you have properly gained access solely for your personal, non-commercial use. We reserve all rights not expressly granted to you in and to the Site, the Content and the Marks.\
\
By using the Site, you represent and warrant that: (1) you have the legal capacity and you agree to comply with these Terms of Use; (2) you are not a minor in the jurisdiction in which you reside; (3) you will not use the Site for any illegal or unauthorized purpose; and (4) your use of the Site will not violate any applicable law or regulation.
If you provide any information that is untrue, inaccurate, not current, or incomplete, or otherwise violate these Terms of Use, we have the right to suspend or terminate your account and refuse any and all current or future use of the Site (or any portion thereof).\
\
You may not access or use the Site for any purpose other than that for which we make the Site available.\
\
**As a user of the Site, you agree not to:**
1. Systematically retrieve data or other content from the Site to create or compile, directly or indirectly, a collection, compilation, database, or directory without written permission from us.
2. Trick, defraud, or mislead us and other users, especially in any attempt to learn sensitive account information such as user passwords.
3. Circumvent, disable, or otherwise interfere with security-related features of the Site, including features that prevent or restrict the use or copying of any Content or enforce limitations on the use of the Site and/or the Content contained therein.
4. Disparage, tarnish, or otherwise harm, in our opinion, us and/or the Site.
5. Use any information obtained from the Site in order to harass, abuse, or harm another person.
6. Make improper use of our support services or submit false reports of abuse or misconduct.
7. Use the Site in a manner inconsistent with any applicable laws or regulations.
8. Engage in unauthorized framing of or linking to the Site.
9. Upload or transmit (or attempt to upload or to transmit) viruses, Trojan horses, or other material, including excessive use of capital letters and spamming (continuous posting of repetitive text), that interferes with any party’s uninterrupted use and enjoyment of the Site or modifies, impairs, disrupts, alters, or interferes with the use, features, functions, operation, or maintenance of the Site.
10. Engage in any automated use of the system, such as using scripts to send comments or messages, or using any data mining, robots, or similar data gathering and extraction tools.
11. Delete the copyright or other proprietary rights notice from any Content (including Third Party Content as defined below).
12. Attempt to impersonate another user or person or use the username of another user.
13. Upload or transmit (or attempt to upload or to transmit) any material that acts as a passive or active information collection or transmission mechanism, including without limitation, clear graphics interchange formats (“gifs”), 1×1 pixels, web bugs, cookies, or other similar devices (sometimes referred to as “spyware” or “passive collection mechanisms” or “pcms”).
14. Interfere with, disrupt, or create an undue burden on the Site or the networks or services connected to the Site.
15. Harass, annoy, intimidate, or threaten any of our employees or agents engaged in providing any portion of the Site to you.
16. Attempt to bypass any measures of the Site designed to prevent or restrict access to the Site, or any portion of the Site.
17. Copy or adapt the Site’s software, including but not limited to Flash, PHP, HTML, JavaScript, or other code.
18. Except as permitted by applicable law, decipher, decompile, disassemble, or reverse engineer any of the software comprising or in any way making up a part of the Site.
19. Except as may be the result of standard search engine or Internet browser usage, use, launch, develop, or distribute any automated system, including without limitation, any spider, robot, cheat utility, scraper, or offline reader that accesses the Site, or using or launching any unauthorized script or other software.
20. Use a buying agent or purchasing agent to make purchases on the Site.
21. Make any unauthorized use of the Site, including collecting usernames and/or email addresses of users by electronic or other means for the purpose of sending unsolicited email, or creating user accounts by automated means or under false pretenses.
22. Use the Site as part of any effort to compete with us or otherwise use the Site and/or the Content for any revenue-generating endeavor or commercial enterprise.
23. Use the Site to advertise or offer to sell goods and services, except as may be authorized by us.
Any use of the Site in violation of the foregoing violates these Terms of Use and may result in, among other things, termination or suspension of your rights to use the Site.\
\
You agree that we may access, store, process, and use any information and personal data that you provide following the terms of our Privacy Policy and your choices related thereto (including settings).\
\
By submitting suggestions or other feedback regarding the Site, you agree that we can use and share such feedback for any purpose without compensation to you.\
\
We do not assert any ownership over your Contributions, except to the extent that content included within such Contributions is considered a Submission as defined below. We are not liable for any statements or representations in your Contributions provided by you in any area on the Site. You are solely responsible for your Contributions to the Site and you expressly agree to exonerate us from any and all responsibility and to refrain from any legal action against us regarding your Contributions.\
\
You acknowledge and agree that any questions, comments, suggestions, ideas, feedback, or other information regarding the Site ("**Submissions**") provided by you to us are non-confidential. As between us, Company shall own exclusive rights, including all intellectual property rights, and shall be entitled to the unrestricted use, modification and dissemination of these Submissions for any lawful purpose, commercial or otherwise, without acknowledgment or compensation to you. Further, and to the extent that any of Your Submissions may be subject to copyright protection, You hereby grant to Company and to any recipients of software distributed by Company, a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute Your Contributions and any derivative works therefrom. You hereby waive all moral rights to any such Submissions, and you hereby warrant that any such Submissions are original with you or that you have the right to submit such Submissions. You agree there shall be no recourse against us for any alleged or actual infringement or misappropriation of any proprietary right in your Submissions.\
\
The Site may contain (or you may be sent via the Site) links to other websites ("**Third-Party Websites**") as well as articles, photographs, text, graphics, pictures, designs, music, sound, video, information, applications, software, and other content or items belonging to or originating from third parties ("**Third-Party Content**"). Such Third-Party Websites and Third-Party Content are not investigated, monitored, or checked for accuracy, appropriateness, or completeness by us, and we are not responsible for any Third-Party Websites accessed through the Site or any Third-Party Content posted on, available through, or installed from the Site, nor any content, accuracy, offensiveness, opinions, reliability, privacy practices, or other policies of or contained in the Third-Party Websites or the Third-Party Content. Inclusion of, linking to, or permitting the use or installation of any Third-Party Websites or any Third-Party Content does not imply approval or endorsement by us. If you decide to leave the Site and access the Third-Party Websites or to use or install any Third-Party Content, you do so at your own risk, and these Terms of Use no longer govern your use of such Third Party Websites. You should review the applicable terms and policies, including privacy and data gathering practices, of any website to which you navigate from the Site or relating to any applications you use or install from the Site. Any purchases you make through Third-Party Websites will be through other websites and from other companies, and we take no responsibility whatsoever in relation to such purchases which are exclusively between you and the applicable third party. You agree and acknowledge that we do not endorse the products or services offered on Third-Party Websites and you shall hold us harmless from any harm caused by your purchase of such products or services. Additionally, you shall hold us harmless from any losses sustained by you or harm caused to you relating to or resulting in any way from any Third-Party Content or any contact with Third-Party Websites\
\
We reserve the right, but not the obligation, to: (1) monitor the Site for violations of these Terms of Use; (2) take appropriate legal action against anyone who, in our sole discretion, violates the law or these Terms of Use, including without limitation, reporting such user to law enforcement authorities; (3) in our sole discretion and without limitation, refuse, restrict access to, limit the availability of, or disable (to the extent technologically feasible) any of your Contributions or any portion thereof; (4) in our sole discretion and without limitation, notice, or liability, to remove from the Site or otherwise disable all files and content that are excessive in size or are in any way burdensome to our systems; and (5) otherwise manage the Site in a manner designed to protect our rights and property and to facilitate the proper functioning of the Site.\
\
By using the Site, you agree to be bound by our Privacy Policy posted on the Site, which is incorporated into these Terms of Use. Please be advised the Site is hosted in the United States. If you access the Site from any other region of the world with laws or other requirements governing personal data collection, use, or disclosure that differ from applicable laws in the United States, then through your continued use of the Site, you are transferring your data to the United States, and you agree to have your data transferred to and processed in United States.\
\
These Terms of Use shall remain in full force and effect while you use the Site. WITHOUT LIMITING ANY OTHER PROVISION OF THESE TERMS OF USE, WE RESERVE THE RIGHT TO, IN OUR SOLE DISCRETION AND WITHOUT NOTICE OR LIABILITY, DENY ACCESS TO AND USE OF THE SITE (INCLUDING BLOCKING CERTAIN IP ADDRESSES), TO ANY PERSON FOR ANY REASON OR FOR NO REASON, INCLUDING WITHOUT LIMITATION FOR BREACH OF ANY REPRESENTATION, WARRANTY, OR COVENANT CONTAINED IN THESE TERMS OF USE OR OF ANY APPLICABLE LAW OR REGULATION. WE MAY TERMINATE YOUR USE OR PARTICIPATION IN THE SITE OR DELETE ANY CONTENT OR INFORMATION THAT YOU POSTED AT ANY TIME, WITHOUT WARNING, IN OUR SOLE DISCRETION.\
\
If we terminate or suspend your account for any reason, you are prohibited from registering and creating a new account under your name, a fake or borrowed name, or the name of any third party, even if you may be acting on behalf of the third party. In addition to terminating or suspending your account, we reserve the right to take appropriate legal action, including without limitation pursuing civil, criminal, and injunctive redress.\
\
We reserve the right to change, modify, or remove the contents of the Site at any time or for any reason at our sole discretion without notice. However, we have no obligation to update any information on our Site. We also reserve the right to modify or discontinue all or part of the Site without notice at any time. We will not be liable to you or any third party for any modification, price change, suspension, or discontinuance of the Site.\
\
We cannot guarantee the Site will be available at all times. We may experience hardware, software, or other problems or need to perform maintenance related to the Site, resulting in interruptions, delays, or errors. We reserve the right to change, revise, update, suspend, discontinue, or otherwise modify the Site at any time or for any reason without notice to you. You agree that we have no liability whatsoever for any loss, damage, or inconvenience caused by your inability to access or use the Site during any downtime or discontinuance of the Site. Nothing in these Terms of Use will be construed to obligate us to maintain and support the Site or to supply any corrections, updates, or releases in connection therewith.\
\
These Terms of Use and your use of the Site are governed by and construed in accordance with the laws of the State of California, without regard to its conflict of law principles.\
\
**Disclaimer and Limitation of Our Liability**
There may be information on the Site that contains typographical errors, inaccuracies, or omissions, including descriptions, pricing, availability, and various other information. We reserve the right to correct any errors, inaccuracies, or omissions and to change or update the information on the Site at any time, without prior notice.\
\
THE SITE IS PROVIDED ON AN AS-IS AND AS-AVAILABLE BASIS. YOU AGREE THAT YOUR USE OF THE SITE AND OUR SERVICES WILL BE AT YOUR SOLE RISK. TO THE FULLEST EXTENT PERMITTED BY LAW, WE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, IN CONNECTION WITH THE SITE AND YOUR USE THEREOF, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. WE MAKE NO WARRANTIES OR REPRESENTATIONS ABOUT THE ACCURACY OR COMPLETENESS OF THE SITE’S CONTENT OR THE CONTENT OF ANY WEBSITES LINKED TO THE SITE AND WE WILL ASSUME NO LIABILITY OR RESPONSIBILITY FOR ANY (1) ERRORS, MISTAKES, OR INACCURACIES OF CONTENT AND MATERIALS, (2) PERSONAL INJURY OR PROPERTY DAMAGE, OF ANY NATURE WHATSOEVER, RESULTING FROM YOUR ACCESS TO AND USE OF THE SITE, (3) ANY UNAUTHORIZED ACCESS TO OR USE OF OUR SECURE SERVERS AND/OR ANY AND ALL PERSONAL INFORMATION AND/OR FINANCIAL INFORMATION STORED THEREIN, (4) ANY INTERRUPTION OR CESSATION OF TRANSMISSION TO OR FROM THE SITE, (5) ANY BUGS, VIRUSES, TROJAN HORSES, OR THE LIKE WHICH MAY BE TRANSMITTED TO OR THROUGH THE SITE BY ANY THIRD PARTY, AND/OR (6) ANY ERRORS OR OMISSIONS IN ANY CONTENT AND MATERIALS OR FOR ANY LOSS OR DAMAGE OF ANY KIND INCURRED AS A RESULT OF THE USE OF ANY CONTENT POSTED, TRANSMITTED, OR OTHERWISE MADE AVAILABLE VIA THE SITE. WE DO NOT WARRANT, ENDORSE, GUARANTEE, OR ASSUME RESPONSIBILITY FOR ANY PRODUCT OR SERVICE ADVERTISED OR OFFERED BY A THIRD PARTY THROUGH THE SITE, ANY HYPERLINKED WEBSITE, OR ANY WEBSITE OR MOBILE APPLICATION FEATURED IN ANY BANNER OR OTHER ADVERTISING, AND WE WILL NOT BE A PARTY TO OR IN ANY WAY BE RESPONSIBLE FOR MONITORING ANY TRANSACTION BETWEEN YOU AND ANY THIRD-PARTY PROVIDERS OF PRODUCTS OR SERVICES.\
\
IN NO EVENT WILL WE OR OUR DIRECTORS, EMPLOYEES, OR AGENTS BE LIABLE TO YOU OR ANY THIRD PARTY FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, EXEMPLARY, INCIDENTAL, SPECIAL, OR PUNITIVE DAMAGES, INCLUDING LOST PROFIT, LOST REVENUE, LOSS OF DATA, OR OTHER DAMAGES ARISING FROM YOUR USE OF THE SITE, EVEN IF WE HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. NOTWITHSTANDING ANYTHING TO THE CONTRARY CONTAINED HEREIN, OUR LIABILITY TO YOU FOR ANY CAUSE WHATSOEVER AND REGARDLESS OF THE FORM OF THE ACTION, WILL AT ALL TIMES BE LIMITED TO ONE THOUSAND US DOLLARS ($1,000.00). CERTAIN US STATE LAWS AND INTERNATIONAL LAWS DO NOT ALLOW LIMITATIONS ON IMPLIED WARRANTIES OR THE EXCLUSION OR LIMITATION OF CERTAIN DAMAGES. IF THESE LAWS APPLY TO YOU, SOME OR ALL OF THE ABOVE DISCLAIMERS OR LIMITATIONS MAY NOT APPLY TO YOU, AND YOU MAY HAVE ADDITIONAL RIGHTS.\
\
You agree to defend, indemnify, and hold us harmless from and against any loss, damage, liability, claim, or demand, including reasonable attorneys’ fees and expenses, made by any third party due to or arising out of: (1) use of the Site; (2) breach of these Terms of Use; (3) any breach of your representations and warranties set forth in these Terms of Use; (4) your violation of the rights of a third party; or (5) any overt harmful act toward any other user of the Site with whom you connected via the Site. Notwithstanding the foregoing, we reserve the right, at your expense, to assume the exclusive defense and control of any matter for which you are required to indemnify us, and you agree to cooperate, at your expense, with our defense of such claims. We will use reasonable efforts to notify you of any such claim, action, or proceeding which is subject to this indemnification upon becoming aware of it.\
\
We will maintain certain data that you transmit to the Site for the purpose of managing the performance of the Site, as well as data relating to your use of the Site. Although we perform regular routine backups of data, you are solely responsible for all data that you transmit or that relates to any activity you have undertaken using the Site. You agree that we shall have no liability to you for any loss or corruption of any such data, and you hereby waive any right of action against us arising from any such loss or corruption of such data.\
\
Visiting the Site, sending us emails, and completing online forms constitute electronic communications. You consent to receive electronic communications, and you agree that all agreements, notices, disclosures, and other communications we provide to you electronically, via email and on the Site, satisfy any legal requirement that such communication be in writing. YOU HEREBY AGREE TO THE USE OF ELECTRONIC SIGNATURES, CONTRACTS, ORDERS, AND OTHER RECORDS, AND TO ELECTRONIC DELIVERY OF NOTICES, POLICIES, AND RECORDS OF TRANSACTIONS INITIATED OR COMPLETED BY US OR VIA THE SITE. You hereby waive any rights or requirements under any statutes, regulations, rules, ordinances, or other laws in any jurisdiction which require an original signature or delivery or retention of non-electronic records, or to payments or the granting of credits by any means other than electronic means to the extent applicable.
If any complaint with us is not satisfactorily resolved, you can contact the Complaint Assistance Unit of the Division of Consumer Services of the California Department of Consumer Affairs in writing at 1625 North Market Blvd., Suite N 112, Sacramento, California 95834 or by telephone at (800) 952-5210 or (916) 445-1254.\
\
These Terms of Use and any policies or operating rules posted by us on the Site or in respect to the Site constitute the entire agreement and understanding between you and us. Our failure to exercise or enforce any right or provision of these Terms of Use shall not operate as a waiver of such right or provision. These Terms of Use operate to the fullest extent permissible by law. We may assign any or all of our rights and obligations to others at any time. If any provision or part of a provision of these Terms of Use is determined to be unlawful, void, or unenforceable, that provision or part of the provision is deemed severable from these Terms of Use and does not affect the validity and enforceability of any remaining provisions. There is no joint venture, partnership, employment or agency relationship created between you and us as a result of these Terms of Use or use of the Site. You agree that these Terms of Use will not be construed against us by virtue of having drafted them. You hereby waive any and all defenses you may have based on the electronic form of these Terms of Use and the lack of signing by the parties hereto to execute these Terms of Use.\
\
In order to resolve a complaint regarding the Site or to receive further information regarding use of the Site, please contact us at:
Axiom, Inc.\
1390 Market Street, Suite 200, San Francisco, CA 94102\
[legal@axiom.co](mailto:legal@axiom.co)
---
# Interpret Axiom docs with LLMs
Source: https://axiom.co/docs/llms/llms-overview
## AI chat [#ai-chat]
To get an answer about Axiom from the documentation’s built-in AI assistant, press Cmd/Ctrl K , and then type your question.
## Interpret individual pages [#interpret-individual-pages]
To interpret individual pages of the documentation with an LLM, click in the top right, and then choose one of the following options:
* Copy the page in Markdown format and manually pass it to LLMs
* View the page in Markdown format
* Open the page in ChatGPT
* Open the page in Claude
## Interpret the full docs [#interpret-the-full-docs]
To make it easy for LLMs to interpret the documentation, Axiom offers the following based on the [/llms.txt standard](https://llmstxt.org/):
* [List of docs pages](https://axiom.co/docs/llms.txt)
* [Full documentation](https://axiom.co/docs/llms-full.txt)
* [List of query reference pages](/llms-apl.md)
Access one of the above documents and pass it to your LLM to start interpreting the Axiom documentation.
---
# Amp notifier
Source: https://axiom.co/docs/monitor-data/amp-notifier
Use an Amp notifier to send monitor alerts to an Amp orb.
To create an Amp notifier, follow these steps:
1. Create an Amp webhook that accepts a JSON body with a `text` field. For more information, see the [Amp documentation](https://ampcode.com/docs/orbs/automations#webhooks).
2. In Axiom, click **Notifiers** in the sidebar.
3. Click **New notifier**.
4. Name your notifier.
5. Click **Amp**.
6. In **Webhook URL**, enter the HTTPS URL of the webhook.
7. Click **Create**.
---
# Anomaly monitors
Source: https://axiom.co/docs/monitor-data/anomaly-monitors
Anomaly monitors allow you to aggregate your event data and compare the results of this aggregation to what can be considered normal for the query. When the results are too much above or below the value that Axiom expects based on the event history, the monitor enters the alert state. The monitor remains in the alert state until the results no longer deviate from the expected value. This can happen without the results returning to their previous level if they stabilize around a new value. An anomaly monitor sends you a notification each time it enters or exits the alert state.
## Create anomaly monitor [#create-anomaly-monitor]
To create an anomaly monitor, follow these steps:
1. Click the **Monitors** tab, and then click **New monitor**.
2. Click **Anomaly monitor**.
3. Name your monitor and add a description.
4. Configure the monitor using the following options:
* The comparison operator is the rule to apply when comparing the results to the expected value. The possible values are **above**, **below**, and **above or below**.
* The tolerance factor controls the sensitivity of the monitor. Axiom combines the tolerance factor with a measure of how much the results of your query tend to vary, and uses them to determine how much deviation from the expected value to tolerate before triggering the monitor. The higher the tolerance factor, the wider the tolerated range of deviation. When the results of the aggregation stay within this range, the monitor doesn’t trigger. When the results of the aggregation cross this range, the monitor triggers. The tolerance factor can be any positive numeric value.
* The frequency is how often the monitor runs. This is a positive integer number of minutes.
* The range is the time range for your query. This is a positive integer number of minutes. A longer time range allows the anomaly monitor to consider a larger number of datapoints when calculating the expected value.
* **Alert on no data** triggers the monitor when your query doesn’t return any data. Your query returns no data if no events match your filters and an aggregation used in the query is undefined. For example, you take the average of a field not present in any matching events. The monitor sends a notification when data returns after a no-data alert state. Notifications about deviations from the expected value take precedence over notifications about data returning after a no-data state.
* You can group by attributes when defining your query. By default, your monitor enters the alert state if any of the values returned for the group-by attributes deviate from the expected value, and remains in the alert state until none of the values returned deviates from the expected value. To trigger the monitor separately for each group that deviates from the expected value, enable **Notify by group**. At most one trigger notification is sent per monitor run. This option only has an effect if the monitor’s query groups by a non-time field.
* Toggle **Require seasonality** to compare the results to seasonal patterns in your data. For example, your query produces a time series that increases at the same time each morning. Without accounting for seasonality, the monitor compares to recent results only. By toggling **Require seasonality**, the monitor compares the results to the same time of the previous day or week and only triggers if the results deviate from the expected seasonal pattern.
5. Click **Add notifier**, and then select the notifiers that define how you want to receive notifications for this monitor. For more information, see [Notifiers](#notifiers).
6. To define your query, use one of the following options:
* To use the visual query builder, click **Simple query builder**. Click **Visualize** to select an aggregation method, and then click **Run query** to preview the results.
* To use Axiom Processing Language (APL), click **Advanced query language**. Write a query where the final clause uses the `summarize` operator and bins the results by `_time`, and then click **Run query** to preview the results. For more information, see [Introduction to APL](/apl/introduction).
In the preview, the boundary where the monitor triggers is displayed as a dashed line. Where there isn’t enough data to compute a boundary, the chart is grayed out. If the monitor preview shows that it alerts when you don’t want it to, try increasing the tolerance. Inversely, try decreasing the tolerance if the monitor preview shows that it doesn’t alert when you want it to.
7. Click **Create**.
You have created an anomaly monitor. Axiom alerts you when the results from your query are too high or too low compared to what’s expected based on the event history.
In the chart, the red dotted line displays the tolerance range around the expected value over time. When the results of the query cross this range, the monitor triggers.
## Examples [#examples]
For real-world use cases, see [Monitor examples](/monitor-data/monitor-examples).
---
# ChatGPT Workspace Agent notifier
Source: https://axiom.co/docs/monitor-data/chatgpt-workspace-agent-notifier
Use a ChatGPT Workspace Agent notifier to send monitor alerts to a published workspace agent.
To create a ChatGPT Workspace Agent notifier, follow these steps:
1. Publish your workspace agent with an API channel. For more information, see the [OpenAI documentation](https://developers.openai.com/workspace-agents/trigger-runs).
2. Create a Workspace Agent access token. For more information, see the [authentication documentation](https://developers.openai.com/workspace-agents/authentication).
3. In Axiom, click **Notifiers** in the sidebar.
4. Click **New notifier**.
5. Name your notifier.
6. Click **ChatGPT Workspace Agent**.
7. In **API channel trigger ID**, enter the trigger ID of the published API channel.
8. In **Workspace agent token**, enter your Workspace Agent access token.
9. Click **Create**.
---
# Claude Code notifier
Source: https://axiom.co/docs/monitor-data/claude-code-notifier
Use a Claude Code notifier to send monitor alerts to a Claude Code routine.
To create a Claude Code notifier, follow these steps:
1. Create a Claude Code routine with an API trigger. For more information, see the [Claude Code documentation](https://code.claude.com/docs/en/routines#add-an-api-trigger).
2. In the routine prompt, tell Claude Code to investigate the alert in the `routine-fire-payload` block.
3. In Axiom, click **Notifiers** in the sidebar.
4. Click **New notifier**.
5. Name your notifier.
6. Click **Claude Code**.
7. In **Routine ID**, enter the ID between `/routines/` and `/fire` in the routine’s fire URL.
8. In **Claude Code bearer token**, enter the token of the API trigger.
9. Click **Create**.
---
# Configure monitors
Source: https://axiom.co/docs/monitor-data/configure-monitors
## Edit monitors [#edit-monitors]
To edit an existing monitor:
1. Click the Monitors tab.
2. Click the monitor in the list that you want to edit.
3. In the top right, click **Edit monitor**.
4. Make changes to the monitor.
5. Click **Save**.
## Show annotations in monitor charts [#show-annotations-in-monitor-charts]
Threshold and anomaly monitors support annotations in **Recent activity** and in chart previews.
For more information, see [Annotations](/annotations#show-and-hide-annotations-in-monitors).
## Disable monitors [#disable-monitors]
Disable a monitor to prevent it from running for a specific amount of time.
To disable a monitor:
1. Click the Monitors tab.
2. Click the monitor in the list that you want to disable.
3. In the top right, click **Disable monitor**.
4. Select the time period for which you want to disable the monitor.
5. Click **Disable monitor**.
Axiom automatically enables the monitor after the time period you specified.
## Enable monitors [#enable-monitors]
To enable a monitor:
1. Click the Monitors tab.
2. Click the monitor in the list that you want to enable.
3. In the top right, click **Enable monitor**.
4. Click **Enable monitor**.
## Clone monitors [#clone-monitors]
To clone a monitor:
1. Click the Monitors tab.
2. Click the monitor in the list that you want to delete.
3. In the top right, click **More**.
4. Click **Clone monitor**.
## Delete monitors [#delete-monitors]
To delete a monitor:
1. Click the Monitors tab.
2. Click the monitor in the list that you want to delete.
3. In the top right, click **More**.
4. Click **Delete monitor**.
---
# Configure notifiers
Source: https://axiom.co/docs/monitor-data/configure-notifiers
## Disable notifiers [#disable-notifiers]
Disable a notifier to stop notifications for a specific amount of time.
To disable a notifier:
1. In Axiom, click **Notifiers** in the sidebar.
2. Click the notifier in the list that you want to disable.
3. Click **Disable notifier**.
4. Select the time period for which you want to disable the notifier.
5. Click **Disable**.
Axiom automatically enables the notifier after the time period you specified.
## Enable notifiers [#enable-notifiers]
To enable a notifier:
1. In Axiom, click **Notifiers** in the sidebar.
2. Click the notifier in the list that you want to enable.
3. In **Status**, click **Enable**.
## Delete notifiers [#delete-notifiers]
To delete a notifier:
1. In Axiom, click **Notifiers** in the sidebar.
2. Click the notifier in the list that you want to delete.
3. In the top right, click .
4. Click **Delete**.
---
# Cursor notifier
Source: https://axiom.co/docs/monitor-data/cursor-notifier
Use a Cursor notifier to send monitor alerts to a Cursor automation.
To create a Cursor notifier, follow these steps:
1. Create and save a Cursor automation with a webhook trigger. For more information, see the [Cursor documentation](https://cursor.com/docs/cloud-agent/automations#webhook-triggers).
2. In Axiom, click **Notifiers** in the sidebar.
3. Click **New notifier**.
4. Name your notifier.
5. Click **Cursor**.
6. In **Automation webhook URL**, enter the webhook URL of the automation.
7. In **Cursor bearer token**, enter the API key of the webhook trigger.
8. Click **Create**.
---
# Custom webhook notifier
Source: https://axiom.co/docs/monitor-data/custom-webhook-notifier
Use a custom webhook notifier to connect your monitors to internal or external services. The webhook URL receives a POST request with a content type of `application/json` together with any other headers you specify.
To create a custom webhook notifier, follow these steps:
1. In Axiom, click **Notifiers** in the sidebar.
2. Click **New notifier** on the top right.
3. Name your notifier.
4. Click **Custom webhook**.
5. In **Webhook URL**, enter the URL where you want to send the POST request. The URL must use HTTPS. Axiom rejects `http://` URLs when you save or test the notifier.
6. Optional: To customize the content of your webhook, use the [Go template syntax](https://pkg.go.dev/text/template) to interact with these variables:
* `.Action` has value `Open` when the notification corresponds to a match monitor matching, a new values monitor finding a new value, or a threshold monitor triggering, and has value `Closed` when the notification corresponds to a threshold monitor resolving.
* `.MonitorID` is the unique identifier for the monitor associated with the notification.
* `.Body` is the message body associated with the notification. When the notification corresponds to a match monitor, this is the matching event data. When the notification corresponds to a new values monitor, this is a row of the query results that holds the new value. When the notification corresponds to a threshold monitor, this provides information about the value that gave rise to the monitor triggering or resolving.
* `.Description` is the description of the monitor associated with the notification.
* `.QueryEndTime` is the end time applied in the monitor query that gave rise to the notification.
* `.QueryStartTime` is the start time applied in the monitor query that gave rise to the notification.
* `.Timestamp` is the time the notification was generated.
* `.Title` is the name of the monitor associated with the notification.
* `.Value` is the value that gave rise to the monitor triggering or resolving. It’s only applicable if the notification corresponds to a threshold monitor. When a threshold monitor resolves because its query stops returning data for a series (for example, a grouped series that goes idle or drops out), there’s no current value to report and `.Value` is `0`.
* `.MatchedEvent` is a JSON object. It’s only applicable if the notification corresponds to a match monitor or a new values monitor. For a match monitor, it’s the event that matched the criteria of the monitor. For a new values monitor, it’s one row of the query results that holds the new value.
* `.GroupKeys` and `.GroupValues` are JSON arrays that contain the keys and the values returned by the group-by attributes of your query. They’re only applicable if the APL query of the monitor groups by a non-time field.
You can fully customize the content of the webhook to match the requirements of your environment.
7. Optional: Add headers to the POST request sent to the webhook URL.
8. Click **Create**.
## Examples [#examples]
The example below is the default template for a custom webhook notification:
```json
{
"action": "{{.Action}}",
"event": {
"monitorID": "{{.MonitorID}}",
"body": "{{.Body}}",
"description": "{{.Description}}",
"queryEndTime": "{{.QueryEndTime}}",
"queryStartTime": "{{.QueryStartTime}}",
"timestamp": "{{.Timestamp}}",
"title": "{{.Title}}",
"value": {{.Value}},
"matchedEvent": {{jsonObject .MatchedEvent}},
"groupKeys": {{jsonArray .GroupKeys}},
"groupValues": {{jsonArray .GroupValues}}
}
}
```
Using the template above, the body of a POST request sent to the webhook URL for a threshold monitor triggering:
```json
{
"action": "Open",
"event": {
"monitorID": "CabI3w142069etTgd0",
"body": "Current value of 57347 is above or equal to the threshold value of 0",
"description": "",
"queryEndTime": "2024-06-28 14:55:57.631364493 +0000 UTC",
"queryStartTime": "2024-06-28 14:45:57.631364493 +0000 UTC",
"timestamp": "2024-06-28 14:55:57 +0000 UTC",
"title": "Axiom Monitor Test Triggered",
"value": 57347,
"matchedEvent": null,
"groupKeys": null,
"groupValues": null
}
}
```
The example template below formats the webhook message to match the [expectations of incident.io](https://api-docs.incident.io/tag/Alert-Events-V2/) using the monitor ID as the `deduplication_key`. To use the native integration, see [incident.io notifier](/monitor-data/incident-io-notifier).
```json
{
"title": "{{.Title}}",
"description": "{{.Body}}",
"deduplication_key": "{{.MonitorID}}",
"status": "{{ if eq .Action "Open" }}firing{{ else }}resolved{{ end }}",
"metadata": {
"description": "{{.Description}}",
"value": {{.Value}}
},
"source_url": "https://app.axiom.co/{your-org-id-here}/monitors/{{.MonitorID}}"
}
```
---
# Discord notifier
Source: https://axiom.co/docs/monitor-data/discord-notifier
Use a Discord notifier to notify specific channels in your Discord server.
To create a Discord notifier, choose one of the following methods:
* [Create Discord notifier with a token](#create-discord-notifier-with-token)
* [Create Discord notifier with a webhook URL](#create-discord-notifier-with-webhook)
## Create Discord notifier with token [#create-discord-notifier-with-token]
In Discord, create a token and get the channel ID:
1. Go to [Discord .dev](https://discord.com/developers/applications) and create a new app.
2. Click **Bot > Add Bot > Reset Token** to get your Discord token.
3. Click **OAuth2 > URL Generator**, check the Bot scope and the Send Messages permission.
4. Open the generated URL to add the bot to your server.
5. Click **User Settings > Advanced**, and then enable developer mode.
6. Right-click a channel, and then click **Copy ID**.
7. Ensure the **Discord Bot** has the proper allow channel access permissions.
In Axiom:
1. In Axiom, click **Notifiers** in the sidebar.
2. Click **New notifier** on the top right.
3. Name your notifier.
4. Click **Discord**.
5. Enter the token you have previously generated and the channel ID.
6. Click **Create**.
### Create Discord notifier with webhook [#create-discord-notifier-with-webhook]
1. In Discord, generate a webhook. For more information, see the [Discord documentation](https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks).
2. In Axiom, click **Notifiers** in the sidebar.
3. Click **New notifier** on the top right.
4. Name your notifier.
5. Click **Discord Webhook**.
6. Enter the webhook URL you have previously generated.
7. Click **Create**.
---
# Email notifier
Source: https://axiom.co/docs/monitor-data/email-notifier
To create an email notifier, follow these steps:
1. In Axiom, click **Notifiers** in the sidebar.
2. Click **New notifier** on the top right.
3. Name your notifier.
4. Click **Email**.
5. In the **Users** section, add the email addresses where you want to send notifications, and then click **+** on the right.
6. Click **Create**.
---
# incident.io notifier
Source: https://axiom.co/docs/monitor-data/incident-io-notifier
To create an incident.io notifier, follow these steps:
1. In incident.io, create an HTTP alert source and copy its alert events URL and token. For more information, see the [incident.io documentation](https://docs.incident.io/alerts/custom-http-sources).
2. In Axiom, click **Notifiers** in the sidebar.
3. Click **New notifier**.
4. Name your notifier.
5. Click **incident.io**.
6. In **Alert source ID**, enter the last segment of the alert events URL.
7. In **Token**, enter the token of the HTTP alert source.
8. Click **Create**.
---
# Jira Service Management notifier
Source: https://axiom.co/docs/monitor-data/jira-service-management-notifier
To create a Jira Service Management notifier, follow these steps:
1. In Jira Service Management, create an API integration. For more information, see the [Atlassian documentation](https://support.atlassian.com/jira-service-management-cloud/docs/set-up-an-api-integration/).
2. In Axiom, click **Notifiers** in the sidebar.
3. Click **New notifier**.
4. Name your notifier.
5. Click **Jira Service Management**.
6. In **API key**, enter the API key of the integration.
7. Click **Create**.
---
# Match monitors
Source: https://axiom.co/docs/monitor-data/match-monitors
Match monitors allow you to continuously filter your log data and send you matching events. Axiom sends a notification for each matching event. By default, the notification message contains the entire matching event in JSON format. When you define your match monitor using APL, you can control which event attributes to include in the notification message.
Axiom recommends using match monitors for alerting purposes only. A match monitor can send 10 notifications per minute and 500 notifications per day. A notification can usually include events up to 0.1 MB but the maximum size can be smaller depending on the type of the notifier.
## Create match monitor [#create-match-monitor]
To create a match monitor, follow these steps:
1. Click the **Monitors** tab, and then click **New monitor**.
2. Click **Match monitor**.
3. Name your monitor and add a description.
4. Click **Add notifier**, and then select the notifiers that define how you want to receive notifications for this monitor. For more information, see [Notifiers](#notifiers).
5. To define your query, use one of the following options:
* To use the visual query builder, click **Simple query builder**. Select the filters, and then click **Run query** to preview the recent events that match your filters. To preview matching events over a specific period, select the time range.
* To use Axiom Processing Language (APL), click **Advanced query language**. Write a query using the `where` operator to filter for events, and then click **Run query** to preview the results. To transform matching events before sending them to you, use the `extend` and the `project` operators. Don’t use aggregations in your query. For more information, see [Introduction to APL](/apl/introduction).
6. When the preview displays the events that you want to match, click **Create**. You can’t create a match monitor if more than 500 events match your query within the past 24 hours.
You have created a match monitor, and Axiom alerts you about every event that matches the filters you set. Each notification contains the event details as shown in the preview.
If you define your query using APL, you can use the following limited set of tabular operators:
* [extend](/apl/tabular-operators/extend-operator)
* [extend-valid](/apl/tabular-operators/extend-valid-operator)
* [parse](/apl/tabular-operators/parse-operator)
* parse-kv
* [project](/apl/tabular-operators/project-operator)
* [project-away](/apl/tabular-operators/project-away-operator)
* [project-keep](/apl/tabular-operators/project-keep-operator)
* project-rename
* [project-reorder](/apl/tabular-operators/project-reorder-operator)
* [where](/apl/tabular-operators/where-operator)
This restriction only applies to tabular operators.
## Examples [#examples]
For real-world use cases, see [Monitor examples](/monitor-data/monitor-examples).
---
# Microsoft Teams notifier
Source: https://axiom.co/docs/monitor-data/microsoft-teams-notifier
Use a Microsoft Teams notifier to send a notification to a specific channel in your Microsoft Teams instance.
To create a Microsoft Teams notifier, follow these steps:
1. In Microsoft Teams, generate an incoming webhook. For more information, see the [Microsoft documentation](https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook).
2. In Axiom, click **Notifiers** in the sidebar.
3. Click **New notifier** on the top right.
4. Name your notifier.
5. Click **Microsoft Teams**.
6. Enter the webhook URL you have previously generated.
7. Click **Create**.
---
# Monitor examples
Source: https://axiom.co/docs/monitor-data/monitor-examples
## Notify on all occurrences of error [#notify-on-all-occurrences-of-error]
To receive a notification on all occurrences of an error, create a match monitor where the filter conditions match the events reporting the error.
To receive only certain attributes in the notification message, use the `project` operator.
## Notify when error rate above threshold [#notify-when-error-rate-above-threshold]
To receive a notification when the error rate exceeds a threshold, [create a threshold monitor](/monitor-data/threshold-monitors) with an APL query that identifies the rate of error messages.
For example, logs in your dataset `['sample_dataset']` have a `status.code` attribute that takes the value `ERROR` when a log is about an error. In this case, the following example query tracks the error rate every minute:
```apl
['sample_dataset']
| extend is_error = case(['status.code'] == 'ERROR', 1, 0)
| summarize avg(error) by bin(_time, 1m)
```
Other options:
* To trigger the monitor when the error rate is above or equal to 0.01, set the threshold value to 0.01 and the comparison operator to `above or equal`.
* To run the monitor every 5 minutes, set the frequency to 5.
* To keep the monitor in the alert state until 10 minutes have passed with the per-minute error rate remaining below your threshold value, set the range to 10.
## Notify when number of error messages above threshold [#notify-when-number-of-error-messages-above-threshold]
To receive a notification when the number of error message of a given type exceeds a threshold, create a threshold monitor with an APL query that counts the different error messages.
For example, logs in your dataset `['sample_dataset']` have a `error.message` attribute. In this case, the following example query counts errors by type every 5 minutes:
```apl
['sample_dataset']
| summarize count() by ['error.message'], bin(_time, 5m)
```
Other options:
* To trigger the monitor when the count is above or equal to 10 for any individual message type, set the threshold to 10 and the comparison operator to **above or equal**.
* To run the monitor every 5 minutes, set the frequency to 5.
* To run the monitor the query with a range of 10 minutes, set the range to 10.
By default, the monitor enters the alert state when any of the counts returned by the query cross the threshold, and remains in the alert state until no counts cross the threshold. To alert separately for each message value instead, enable **Notify by group**.
## Notify when response times spike [#notify-when-response-times-spike]
To receive a notification whenever your response times spike without having to rely on a single threshold, [create an anomaly monitor](/monitor-data/anomaly-monitors) with an APL query that tracks your median response time.
For example, you have a dataset `['my_traces']` of trace data with the following:
* Route information is in the `route` field.
* Duration information is in the `duration` field.
* For top-level spans, the `parent_span_id` field is empty.
The following query gives median response times by route in one-minute intervals:
```apl
['my_traces']
| where isempty(parent_span_id)
| summarize percentile(duration, 50) by ['route'], bin(_time, 1m)
```
Other options:
* To only trigger the monitor when response times are unusually high for a route, set the comparison operator to **above**.
* To run the monitor every 5 minutes, set the frequency to 5.
* To consider the previous 30 minutes of data when determining what sort of variation is expected for median response times for a route, set the range to 30.
* To notify separately for each route, enable **Notify by group**.
## Notify on new error types [#notify-on-new-error-types]
To receive a notification the first time a new kind of error appears, [create a new values monitor](/monitor-data/new-values-monitors) that watches the column holding the error type.
For example, logs in your dataset `['sample_dataset']` have an `error.type` attribute. In this case, the following example query returns the error types:
```kusto
['sample_dataset']
| where isnotempty(['error.type'])
| project ['error.type']
```
Other options:
* To watch the error types, select the checkbox in the header of the `error.type` column in the results preview.
* To avoid notifications for error types that already occurred in the last month, set **Learn from** to **30 days**.
* To get a notification again when an error type returns after 90 days, set **Forget values after** to 90.
---
# Monitors
Source: https://axiom.co/docs/monitor-data/monitors
A monitor is a background task that periodically runs a query that you define. For example, it counts the number of error messages in your logs over the previous 5 minutes. A notifier defines how Axiom notifies you about the monitor output. For example, Axiom can send you an email.
You can use the following types of monitor:
* [Anomaly monitors](/monitor-data/anomaly-monitors) aggregate event data over time and look for values that are unexpected based on the event history. When the results of the aggregation are too high or low compared to the expected value, Axiom sends you an alert.
* [Match monitors](/monitor-data/match-monitors) filter for key events and send them to you.
* [New values monitors](/monitor-data/new-values-monitors) watch a column of your query results. When the column holds a value that Axiom hasn’t seen recently, Axiom sends you an alert.
* [Threshold monitors](/monitor-data/threshold-monitors) aggregate event data over time. When the results of the aggregation cross a threshold, Axiom sends you an alert.
---
# New values monitors
Source: https://axiom.co/docs/monitor-data/new-values-monitors
New values monitors alert you when a column of your query results holds a value that Axiom hasn’t seen in that column recently. Use them when the first appearance of something is worth knowing about. For example:
* **Reliability:** A new error message in your service after a deploy, or a new exception type in a background job.
* **Security:** A new IP address on your network, a new country that a user signs in from, or a new AWS API call in your audit logs.
* **Infrastructure:** A new host, container image, or service version that starts sending data, or a new domain that your workloads resolve.
* **Product:** A new customer that calls your API, a new client version in the user agents of your requests, or a new tool that your AI agent uses.
Each time the monitor runs, Axiom compares the values of the watched column in the query results with the values that the monitor recorded during the lookback period. Axiom sends a notification for each value that it hasn’t seen in this period, and then records the value so that it doesn’t alert on it again until the lookback period has passed without the value appearing.
## Create new values monitor [#create-new-values-monitor]
To create a new values monitor, follow these steps:
1. Click the **Monitors** tab, and then click **New monitor**.
2. In **Monitor type**, select **New values**.
3. Name your monitor and add a description.
4. Write an Axiom Processing Language (APL) query whose results contain the column you want to watch, and then click **Run** to preview the results. For example, the following query returns the error messages of a service:
```kusto
['my-logs']
| where level == 'error'
| project message
```
The query can filter, transform, and aggregate events. For more information, see [Introduction to APL](/apl/introduction).
5. In the preview, select the checkbox in the header of the column you want to watch. You can watch one column. You can’t watch the result of an aggregation, such as `count()`, or the internal fields `_time`, `_sysTime`, and `_cursor`. Axiom selects the first column that you can watch by default.
6. Configure the monitor using the following options:
* **Run every** is how often the monitor runs.
* **Range** is how much recent data each run queries. It can’t be shorter than **Run every**. For more information, see [Time range of each run](#time-range-of-each-run).
* **Forget values after** is the lookback period in days. A value counts as new when the monitor hasn’t seen it in this many days. The default is 365 days.
* **Learn from** is the number of previous days of events that the monitor records as already seen before it first runs. The possible values are **None**, **1 day**, **7 days**, **14 days**, and **30 days**, and the value can’t exceed **Forget values after**. The default is 30 days. If your query aggregates, select **None**. For more information, see [Learning period](#learning-period).
7. Click **Add notifier**, and then select the notifiers that define how you want to receive notifications for this monitor. For more information, see [Notifiers](/monitor-data/notifiers-overview).
8. Click **Save**.
You have created a new values monitor. Axiom alerts you each time the watched column holds a value that the monitor hasn’t seen during the lookback period.
New values monitors only support APL queries on event datasets. They don’t support metrics datasets.
## Learning period [#learning-period]
When you create a new values monitor, Axiom records the values that the query returns over the learning period as already seen. This prevents the first runs of the monitor from alerting on values that already appear in your data.
If you set **Learn from** to **None**, the monitor doesn’t look at past events. Instead, the first run that returns values records them without sending notifications, and the monitor only alerts on values that appear after this run. Values that appeared before the monitor was created but are rare, such as a weekly job, can trigger notifications when they next appear.
## Queries that aggregate [#queries-that-aggregate]
Aggregate in your query when a value is only worth an alert once it passes a bar. Without an aggregation, the monitor alerts on a value the first time a single event holds it. With an aggregation, you decide how much activity a value needs before it counts.
For example, you want to know about new clients of your API, but not about every scanner that sends a handful of requests. The following query only returns the clients that send at least 200 requests from at least 3 IP addresses within the time range of a run:
```kusto
['http-logs']
| summarize requests = count(), sources = dcount(client_ip) by client
| where requests >= 200 and sources >= 3
```
Watch the `client` column. The monitor alerts you the first time a client passes the bar, and ignores the clients that stay below it.
Other uses of the same pattern include the following:
* A new error message that affects at least 10 users.
* A new country that at least 5 accounts sign in from.
* A new container image that runs on at least 3 hosts.
Each run aggregates over the time set in **Range**. To aggregate over a longer period, for example the last hour while the monitor runs every 5 minutes, see [Time range of each run](#time-range-of-each-run).
Because the results of a query that aggregates depend on the time range it runs over, Axiom recommends setting **Learn from** to **None** for these queries.
## Notifications [#notifications]
A new values monitor sends one notification for each new value. Each notification contains the new value. Notifications sent to [custom webhook notifiers](/monitor-data/custom-webhook-notifier) also contain one row of the query results that holds the new value, in `.MatchedEvent`.
A run sends at most 9 notifications. If a run finds between 10 and 1,000 new values, the monitor doesn’t record the ones it didn’t send notifications for, so they trigger a notification in a later run if they appear again. If a run finds more than 1,000 new values, it fails. For more information, see [Limits](#limits).
A new values monitor doesn’t resolve. It doesn’t send a notification when a value stops appearing.
## Limits [#limits]
* Within the lookback period, the watched column can hold fewer than 50,000 distinct values.
* A single run can find at most 1,000 new values.
If a monitor exceeds a limit, its runs fail. To stay within the limits, watch a column with fewer distinct values, filter your query, or shorten the lookback period. For example, watch an error message after removing the IDs and numbers it contains, rather than the raw message.
## Time range of each run [#time-range-of-each-run]
**Range** sets how much recent data each run of a new values monitor queries. It can’t be shorter than **Run every**. When the two are equal, each run queries the time since the previous run. To query a longer period in each run, set a longer **Range**. In the [API](/restapi/endpoints/createMonitor), this setting is `rangeMinutes`.
For example, a monitor that runs every 5 minutes with **Range** set to 60 minutes checks the last hour of events every 5 minutes. With a query that aggregates, this lets you alert on a new client that sends at least 200 requests within an hour, and still find out within 5 minutes of the client passing the bar.
When the time ranges of consecutive runs overlap, a value doesn’t trigger repeated notifications. The monitor records each value it alerts on, and later runs treat it as already seen.
A longer time range means that each run queries more data.
## Data that arrives late [#data-that-arrives-late]
By default, each run of a new values monitor only checks the events whose `_time` falls within its **Range**, which ends at the time of the run. If an event arrives in Axiom after every run that covers its `_time`, no run checks it, and the monitor doesn’t alert on its value.
If your data can arrive late, set **Delay** in the **Evaluation** settings of the monitor. In the [API](/restapi/endpoints/createMonitor), this setting is `secondDelay`. The delay shifts the time range of each run into the past. For example, with a delay of 15 minutes, a run at 10:15 checks the events up to 10:00.
A [time range](#time-range-of-each-run) longer than the interval between runs also helps. Later runs check a late event as long as its `_time` falls within their time range.
## Edit new values monitor [#edit-new-values-monitor]
When you change the query, the watched column, **Run every**, **Range**, or **Delay** of an existing monitor, Axiom clears the values that the monitor has recorded. The monitor then learns again from the period in **Learn from**, or from its next run if **Learn from** is **None**. The editor warns you before you save a change that clears the recorded values.
Changes to **Forget values after** and **Learn from** keep the recorded values.
## Examples [#examples]
For real-world use cases, see [Monitor examples](/monitor-data/monitor-examples).
---
# Notifiers
Source: https://axiom.co/docs/monitor-data/notifiers-overview
A monitor is a background task that periodically runs a query that you define. For example, it counts the number of error messages in your logs over the previous 5 minutes. A notifier defines how Axiom notifies you about the monitor output. For example, Axiom can send you an email.
By adding a notifier to a monitor, you receive a notification with the following message:
* When a match monitor matches an event, the message contains the full event if you created the monitor using the simple query builder, or the output of the APL query if you created the monitor using APL.
* When a threshold monitor changes state, the message includes a relevant value from the query results. If you enable **Notify by group**, the notification message also contains the relevant group value.
Choose one of the following to learn more about a type of notifier:
---
# Opsgenie notifier
Source: https://axiom.co/docs/monitor-data/opsgenie-notifier
Use an Opsgenie notifier to use all the incident management features of Opsgenie with Axiom.
To create an Opsgenie notifier, follow these steps:
1. In Opsgenie, create an API integration. For more information, see the [Opsgenie documentation](https://support.atlassian.com/opsgenie/docs/create-a-default-api-integration/).
2. In Axiom, click **Notifiers** in the sidebar.
3. Click **New notifier** on the top right.
4. Name your notifier.
5. Click **Opsgenie**.
6. Enter the API key you have previously generated.
7. Select the region of your Opsgenie instance.
8. Click **Create**.
---
# PagerDuty notifier
Source: https://axiom.co/docs/monitor-data/pagerduty
Use a PagerDuty notifier to use all the incident management features of PagerDuty with Axiom.
## Benefits of using PagerDuty with Axiom [#benefits-of-using-pagerduty-with-axiom]
* Increase the performance and availability of your apps and services.
* Use specific insights in your backend, apps, and workloads by running PagerDuty in tandem with Axiom.
* Detect critical issues before any disruption happens to your resources: Axiom automatically opens and closes PagerDuty incidents.
* Obtain deep understanding of the issue root cause by visualising the data using Axiom.
Axiom creates PagerDuty events that arise from critical issues, disruptions, vulnerabilities, or workloads downtime on a service created in PagerDuty. The alert on Axiom side is linked to the PagerDuty Event allowing for Axiom to automatically close the Event incident if the Alert is resolved. This ensures no duplicate Events on PagerDuty side are created for the corresponding ones on Axiom side.
### Prerequisites [#prerequisites]
* Ensure you have [Admin base role](https://support.pagerduty.com/docs/user-roles) in PagerDuty.
## Create PagerDuty notifier [#create-pagerduty-notifier]
To create a PagerDuty notifier, follow these steps:
1. In PagerDuty’s Events V2 API, create a new service named **Axiom** with the default settings. Copy the integration key. For more information, see the [PagerDuty documentation](https://support.pagerduty.com/main/docs/services-and-integrations#create-a-service)
2. In Axiom, click **Notifiers** in the sidebar.
3. Click **New notifier** on the top right.
4. Name your notifier.
5. Click **PagerDuty**.
6. Enter the integration key you have previously generated.
7. Click **Create**.
You can now add your PagerDuty notifier to a specific monitor in Axiom. If any incident happens on your monitor, Axiom notifies you on the PagerDuty Service Activity dashboard.
---
# Slack notifier
Source: https://axiom.co/docs/monitor-data/slack-notifier
Use a Slack notifiers to notify specific channels in your Slack organization.
To create a Slack notifier, follow these steps:
1. In Slack, generate an incoming webhook. For more information, see the [Slack documentation](https://api.slack.com/messaging/webhooks).
2. In Axiom, click **Notifiers** in the sidebar.
3. Click **New notifier** on the top right.
4. Name your notifier.
5. Click **Slack**.
6. Enter the webhook URL you have previously generated.
7. Click **Create**.
---
# Threshold monitors
Source: https://axiom.co/docs/monitor-data/threshold-monitors
Threshold monitors allow you to periodically aggregate your event data and compare the results of this aggregation to a threshold that you define. When the results cross the threshold, the monitor enters the alert state. The monitor remains in the alert state until the results no longer cross the threshold. A threshold monitor sends you a notification each time it enters or exits the alert state.
## Create threshold monitor [#create-threshold-monitor]
To create a threshold monitor, follow these steps:
1. Click the **Monitors** tab, and then click **New monitor**.
2. Click **Threshold monitor**.
3. Name your monitor and add a description.
4. Configure the monitor using the following options:
* The threshold is the value to compare the results of the query to. This can be any numeric value.
* The comparison operator is the rule to apply when comparing the results to the threshold. The possible values are **above**, **above or equal**, **below**, and **below or equal**.
* The frequency is how often the monitor runs. This is a positive integer number of minutes.
* The range is the time range for your query. This is a positive integer number of minutes. The end time is the time the monitor runs.
* **Alert on no data** triggers the monitor when your query doesn’t return any data. Your query returns no data if no events match your filters and an aggregation used in the query is undefined. For example, you take the average of a field not present in any matching events. The monitor sends a notification when data returns after a no-data alert state. Notifications about crossing the threshold take precedence over notifications about data returning after a no-data state.
* You can group by attributes when defining your query. By default, your monitor enters the alert state if any of the values returned for the group-by attributes cross the threshold, and remains in the alert state until none of the values returned cross the threshold. To trigger the monitor separately for each group that crosses the threshold, enable **Notify by group**. At most one trigger notification is sent per monitor run. This option only has an effect if the monitor’s query groups by a non-time field.
5. Click **Add notifier**, and then select the notifiers that define how you want to receive notifications for this monitor. For more information, see [Notifiers](#notifiers).
6. To define your query, use one of the following options:
* To use the visual query builder, click **Simple query builder**. Click **Visualize** to select an aggregation method, and then click **Run query** to preview the results in a chart. The monitor enters the alert state if any points on the chart cross the threshold. Optionally, use filters to specify which events to aggregate, and group by fields to split the aggregation across the values of these fields.
* To use Axiom Processing Language (APL), click **Advanced query language**. Write a query where the final clause uses the `summarize` operator, and then click **Run query** to preview the results. For more information, see [Introduction to APL](/apl/introduction). If your query returns a chart, the monitor enters the alert state if any points on the chart cross the threshold. If your query returns a table, the monitor enters the alert state if any numeric values in the table cross the threshold. If your query uses the `bin_auto` function, Axiom displays a warning. To ensure that the monitor preview gives an accurate picture of future performance, use `bin` rather than `bin_auto`.
7. Click **Create**.
You have created a threshold monitor, and Axiom alerts you when the results from your query cross the threshold.
## Examples [#examples]
For real-world use cases, see [Monitor examples](/monitor-data/monitor-examples).
---
# View monitor status
Source: https://axiom.co/docs/monitor-data/view-monitor-status
To view the status of a monitor:
1. Click the Monitors tab.
2. Click the monitor in the list whose status you want to view.
The monitor status page provides an overview of the monitor’s current status and history.
## View recent activity and history of runs [#view-recent-activity-and-history-of-runs]
On the left, you see the recent activity and the history of the monitor runs:
* The `_time` field displays the time of the monitor run.
* The `Status` field displays the status of the monitor.
* The `Range from` and `Range to` fields display the time range used in the monitor run.
You can change the time range of this overview in the top right corner.
## View information about monitor configuration [#view-information-about-monitor-configuration]
On the right, you see information about the monitor’s configuration.
* Current status
* Monitor type
* Query the monitor periodically runs
* Configuration details
* Notifiers attached to the monitor
* Metadata such as name and description
## Check recent viewers of monitor status [#check-recent-viewers-of-monitor-status]
The status page displays the initials of the users who have recently looked at the monitor. To check which users have recently viewed the status page of monitors, hold the pointer over the initials in the top right of the page.
For example, this can be useful if you want to know who has recently seen that a monitor had been triggered and you can start a conversation with them to understand what’s happening.
---
# Architecture
Source: https://axiom.co/docs/platform-overview/architecture
You don’t need to understand any of the following material to get massive value from Axiom. As a fully managed data platform, Axiom just works. This technical deep-dive is intended for curious minds wondering: Why is Axiom different?
Axiom routes ingestion requests through a distributed edge layer to a cluster of specialized services that process and store data in proprietary columnar formats optimized for different data types. EventDB handles high-volume event data, while MetricsDB is purpose-built for time-series metrics with high-cardinality dimensions. Query requests are executed by ephemeral, serverless workers that operate directly on compressed data stored in object storage.
## Ingestion architecture [#ingestion-architecture]
Data flows through a multi-layered ingestion system designed for high throughput and reliability:
* **Regional Edge Layer:** HTTPS ingestion requests are received by regional edge proxies positioned to meet data jurisdiction requirements. These proxies handle protocol translation, authentication, and initial data validation. The edge layer supports multiple input formats (JSON, CSV, compressed streams) and can buffer data during downstream issues.
* **High-availability routing:** The system provides intelligent routing to healthy database nodes using real-time health monitoring. When primary ingestion paths fail, requests are automatically routed to available nodes or queued in a backlog system that processes data when systems recover.
* **Streaming Pipeline:** Raw events are parsed, validated, and transformed in streaming fashion. Field limits and schema validation occur during this phase.
* **Write-Ahead Logging:** All ingested data is durably written to a distributed write-ahead log before being processed. This ensures zero data loss even during system failures and supports concurrent writes across multiple ingestion nodes.
## Storage architecture [#storage-architecture]
Axiom’s storage layer uses specialized columnar formats optimized for different workload types:
### EventDB storage [#eventdb-storage]
EventDB’s storage is built around a custom columnar format that achieves extreme compression ratios:
* **Columnar organization:** Events are decomposed into columns and stored using specialized encodings optimized for each data type. String columns use dictionary encoding, numeric columns use various compression schemes, and boolean columns use bitmap compression.
* **Block-based storage:** Data is organized into immutable blocks that are written once and read many times. Each block contains:
* Column metadata and statistics
* Compressed column data in a proprietary format
* Separate time indexes for temporal queries
* Field schemas and type information
* **Compression pipeline:** Data flows through multiple compression stages:
1. **Ingestion compression:** Real-time compression during ingestion (25-50% reduction)
2. **Block compression:** Columnar compression within storage blocks (10-20x additional compression)
3. **Compaction compression:** Background compaction further optimizes storage (additional 2-5x compression)
* **Object storage integration:** Blocks are stored in object storage (S3) with intelligent partitioning strategies that distribute load and avoid hot-spotting. The system supports multiple storage tiers and automatic lifecycle management.
### MetricsDB storage [#metricsdb-storage]
MetricsDB uses a specialized columnar format engineered for time-series metrics with high-cardinality tags:
* **High-cardinality optimization:** Unlike traditional metrics datastores that struggle with dimensional complexity, MetricsDB is designed from the ground up to handle high numbers of unique tag combinations efficiently.
* **Intentional design constraints:** MetricsDB makes deliberate trade-offs to optimize for the most common metrics use cases. These constraints are purposeful architectural choices that enable MetricsDB to deliver exceptional performance and cost-efficiency for real-world metrics workloads. Where other systems penalize you for high cardinality or force you to pre-aggregate data, MetricsDB lets you store and query metrics with full dimensional flexibility.
* **Unified observability:** Query metrics alongside logs and traces, enabling powerful correlations across all your telemetry data without switching tools or learning multiple query languages.
## Query architecture [#query-architecture]
Axiom executes queries using a serverless architecture that spins up compute resources on-demand:
* **Query compilation:** The APL (Axiom Processing Language) query is parsed, optimized, and compiled into an execution plan. The compiler performs predicate pushdown, projection optimization, and identifies which blocks need to be read.
* **Serverless Workers:** Query execution occurs in ephemeral workers optimized through "Fusion queries"—a system that runs parallel queries inside a single worker to reduce costs and leave more resources for large queries. Workers download only the necessary column data from object storage, enabling efficient resource utilization. Multiple workers can process different blocks in parallel.
* **Block-level parallelism:** Each query spawns multiple workers that process different blocks concurrently. Workers read compressed column data directly from object storage, decompress it in memory, and execute the query.
* **Result aggregation:** Worker results are streamed back and aggregated by a coordinator process. Large result sets are automatically spilled to object storage and streamed to clients via signed URLs.
* **Intelligent caching:** Query results are cached in object storage with intelligent cache keys that account for time ranges and query patterns. Cache hits dramatically reduce query latency for repeated queries.
## Compaction system [#compaction-system]
A background compaction system continuously optimizes storage efficiency:
* **Automatic compaction:** The compaction scheduler identifies blocks that can be merged based on size, age, and access patterns. Small blocks are combined into larger "superblocks" that provide better compression ratios and query performance.
* **Multiple strategies:** The system supports several compaction algorithms:
* **Default:** General-purpose compaction with optimal compression
* **Clustered:** Groups data by common field values for better locality
* **Fieldspace:** Optimizes for specific field access patterns
* **Concat:** Simple concatenation for append-heavy workloads
* **Compression optimization:** During compaction, data is recompressed using more aggressive algorithms and column-specific optimizations that aren’t feasible during real-time ingestion.
## System architecture [#system-architecture]
The overall system is composed of specialized microservices:
* **Core services:** Handle authentication, billing, dataset management, and API routing. These services are stateless and horizontally scalable.
* **Database layer:** The core database engine processes ingestion, manages storage, and coordinates query execution. It supports multiple deployment modes and automatic failover.
* **Orchestration layer:** Manages distributed operations, monitors system health, and coordinates background processes like compaction and maintenance.
* **Edge services:** Handle real-time data ingestion, protocol translation, and provide regional data collection points.
## Why this architecture wins [#why-this-architecture-wins]
* **Cost efficiency:** Serverless query execution means you only pay for compute during active queries. Extreme compression (25-50x) dramatically reduces storage costs compared to traditional row-based systems.
* **Operational simplicity:** The system is designed to be self-managing. Automatic compaction, intelligent caching, and distributed coordination eliminate operational overhead.
* **Elastic scale:** Each component scales independently. Ingestion scales with edge capacity, storage scales with object storage, and query capacity scales with serverless workers.
* **Fault tolerance:** Write-ahead logging, distributed routing, and automatic failover ensure high availability. The system gracefully handles node failures and storage outages.
* **Real-time performance:** Despite the distributed architecture, the system maintains sub-second query performance through intelligent caching, predicate pushdown, and columnar storage optimizations.
This architecture enables Axiom to ingest millions of events per second while maintaining sub-second query latency at a fraction of the cost of traditional logging and observability solutions.
---
# Features
Source: https://axiom.co/docs/platform-overview/features
| Component | Sub-Component | Feature | Description |
| :-------------------------- | :--------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Data Platform** | Deployment | Axiom Cloud | Axiom hosts and manages all infrastructure in its own cloud. |
| **EventDB** | - | - | Foundation of Axiom’s platform for ingesting, storing, and querying timestamped event data at scale. |
| **EventDB** | Ingest | - | Ingest pipeline that’s coordination-free, durable by default, and scales linearly without requiring Kafka or other heavy middleware. |
| **EventDB** | Storage | - | Custom block-based format on object storage, with extreme compression (average 25×, up to 50× for more structured events) and efficient metadata. |
| **EventDB** | Query | - | Serverless ephemeral runtimes that spin up on demand to process queries, powered by the Axiom Processing Language (APL). |
| **EventDB** | Query | [Axiom Processing Language (APL)](/apl/introduction) | Powerful query language for logs and traces, supporting filtering, aggregations, transformations, and specialized operators. |
| **EventDB** | Query | [Virtual fields](/query-data/virtual-fields) | Ability to derive new values from data in real-time during queries without pre-structuring or transforming data during ingestion. |
| **MetricsDB** | - | - | Dedicated metrics datastore purpose-built for high-cardinality time-series data without the cost penalties of traditional metrics systems. |
| **MetricsDB** | Ingest | [OpenTelemetry Metrics](/send-data/opentelemetry) | Native support for OpenTelemetry (gRPC over HTTP) metrics protocol. |
| **MetricsDB** | Storage | High-cardinality native | Store metrics with high-cardinality tags without performance degradation. |
| **MetricsDB** | Query | [Metrics Processing Language (MPL)](/mpl/introduction) | Query metrics using Metrics Processing Language (MPL) with support for time-series aggregations, dimensional filtering, and cross-metric correlations. |
| **Console** | - | - | Web UI for data management, querying, dashboarding, monitoring, and user administration. |
| **Console** | Query | [Builder](/query-data/explore) | Guided interface to quickly filter and group data. |
| **Console** | Query | [Editor](/query-data/query-editor) | A full text-based query language environment for complex aggregations, transformations, and correlations. |
| **Console** | Query | [Natural-language querying](/query-data/query-editor#generate-query-using-natural-language) | Generate valid APL queries from plain English descriptions using AI. |
| **Console** | Query | [Visualizations](/query-data/visualizations) | Charts, graphs, and other visual components to make sense of query results. |
| **Console** | Query | [Trace waterfall](/query-data/traces) | Dedicated interface for analyzing distributed traces. |
| **Console** | Query | [Saved queries](/query-data/datasets#saved-queries) | Save and share queries with team members for easy reuse. |
| **Console** | Query | [Views](/query-data/views) | Apply filters and transformations to datasets to create reusable virtual tables with scoped access control. |
| **Console** | Stream | [Live tailing](/query-data/stream) | Real-time streaming view of incoming logs and events. |
| **Console** | Dashboards | - | Combine multiple visual elements (charts, tables, logs, etc.) onto a single page. |
| **Console** | Dashboards | [AI-powered dashboard generation](/dashboards/create#generate-dashboards-using-ai) | Describe requirements in natural language and generate complete dashboards instantly. |
| **Console** | Dashboards | [Elements](/dashboard-elements/create) | Various chart types, log streams, notes, and more to tailor each dashboard. |
| **Console** | Monitors | [Threshold monitors](/monitor-data/threshold-monitors) | Checks if aggregated values exceed or fall below a predefined threshold (for example, error counts > 100). |
| **Console** | Monitors | [Match monitors](/monitor-data/match-monitors) | Triggers on specific log patterns or conditions for each event. |
| **Console** | Monitors | [Anomaly monitors](/monitor-data/anomaly-monitors) | Learns from historical data to detect unexpected deviations or spikes. |
| **Console** | Monitors | [New values monitors](/monitor-data/new-values-monitors) | Alerts when a column holds a value it hasn’t seen recently (for example, a new error type). |
| **Console** | [Annotations](/annotations) | - | Mark a point or interval in time on charts in Query, dashboards, and monitors. |
| **Console** | Alerting | [Notifiers](/monitor-data/notifiers-overview) (Webhooks, Email, Slack, and more) | Sends notifications through various channels including email, chat platforms, incident management systems, and custom webhook integrations. |
| **Console** | Governance | [Dataset management](/reference/datasets) | Data retention controls, trim functionality, field vacuuming, and dataset sharing capabilities. |
| **Console** | Governance | [Role-Based Access Control (RBAC)](/reference/settings) | Fine-grained permissions at the organization and dataset levels. |
| **Console** | Governance | [Audit logs](/reference/audit-log) | Track every change and action taken by users within Axiom. |
| **Intelligence** | - | - | AI-powered features that accelerate insights and automate data analysis. |
| **Intelligence** | Analysis | [Spotlight](/console/intelligence/spotlight) | Automatically identify differences between selected events and baseline data for root cause analysis and anomaly investigation. Quickly understand key differences with AI-generated summaries. |
| **Intelligence** | Agent integration | [MCP Server](/console/intelligence/mcp-server) | Model Context Protocol server enabling AI agents to query data, list datasets, and access monitors using APL. |
| **Intelligence** | LLM observability | [GenAI dashboard and traces](/use-cases/llm-observability) | Auto-provisioned GenAI dashboard and waterfall trace view for any dataset containing AI telemetry. Instrument using OpenTelemetry or the Axiom AI SDK. |
| **Integrations** | - | - | A wide range of official and community tools to collect logs, metrics, and traces and send them into Axiom. |
| **Integrations** | Popular connectors | [OpenTelemetry](/send-data/opentelemetry), [Vector](/send-data/vector), [Cribl](/send-data/cribl), and [more](/send-data/methods) | Common shippers and pipeline tools for bridging data sources to Axiom. |
| **Integrations** | AWS | [CloudWatch Forwarder](/send-data/cloudwatch), [Lambda Extension](/send-data/aws-lambda), [Kinesis](/send-data/aws-firehose), [S3](/send-data/aws-s3) | Official AWS-based ingestion solutions. |
| **Integrations** | Language libraries | [Go](/guides/go), [Python](/guides/python), [Node.js](/guides/opentelemetry-nodejs), [Java](/guides/opentelemetry-java), [Ruby](/guides/opentelemetry-ruby), [Rust](/guides/rust), [.NET](/guides/opentelemetry-dotnet) | SDKs to send logs and metrics directly from applications. |
| **APIs and CLI** | - | - | Programmatic and command-line interfaces for ingesting, querying, and managing Axiom resources. |
| **APIs and CLI** | REST API | [Endpoints](/restapi/introduction) | Programmatic interfaces for ingesting data, running queries, retrieving results, and managing annotations and tokens. |
| **APIs and CLI** | REST API | [API tokens and Personal Access Tokens](/reference/tokens) | Authentication mechanisms for API access with basic and advanced tokens, plus personal tokens. |
| **APIs and CLI** | CLI | [Auth and dataset management]() | Create datasets, set tokens, or update config from a shell. |
| **APIs and CLI** | CLI | [Query from terminal](/restapi/query) | Execute queries in APL or simpler filters directly in a command-line session. |
| **APIs and CLI** | [Terraform Provider](https://registry.terraform.io/providers/axiomhq/axiom/latest) | - | Terraform provider for programmatically creating and managing Axiom resources including datasets, notifiers, monitors, and users. |
| **Security and Compliance** | - | - | Axiom’s data protection measures and compliance with major privacy/security frameworks. |
| **Security and Compliance** | [Compliance](/platform-overview/security) | SOC 2 Type II, GDPR, CCPA, HIPAA | Meets industry standards for data handling and privacy. |
## Related links [#related-links]
* Explore Axiom’s interactive demo [Playground](https://play.axiom.co/) to try these features.
* Check Axiom’s [roadmap](/platform-overview/roadmap) for upcoming features.
* [Contact](https://axiom.co/contact) Axiom if you have a feature request.
---
# Roadmap
Source: https://axiom.co/docs/platform-overview/roadmap
## Focus areas [#focus-areas]
Axiom continuously ships improvements to its core platform. Beyond these changes, Axiom’s current product development is focused on transforming the core data platform into an intelligent assistant.
[Contact](https://axiom.co/contact) the Axiom team to request more details about specific roadmap items or to join early access programs.
### Intelligent assistant [#intelligent-assistant]
Axiom’s Console is evolving from a powerful analysis tool into an intelligent assistant that dramatically accelerates time-to-insight. By augmenting human-led investigations with AI, Axiom helps teams move from reactive troubleshooting to proactive action.
Learn more in the [Intelligence](/console/intelligence) docs.
### Platform excellence and scale [#platform-excellence-and-scale]
Supporting ambitious builders requires a rock-solid and scalable foundation. Axiom continues to invest heavily in core performance, reliability, and capabilities of the Axiom platform to ensure it can handle the most demanding workloads.
* **Full observability coverage**: Axiom is working to make **Metrics** a generally available, first-class citizen within the data platform, completing the "three pillars of observability" and providing a unified platform for all your telemetry.
* **Global architecture**: Axiom is being re-architected for global scale and efficiency. This includes building out a multi-region edge infrastructure and overhauling storage to support millions of datasets, ensuring high availability and low latency.
## Feature states [#feature-states]
Each feature of Axiom is in one of the following states:
* **In development:** Axiom is actively building this feature. It’s not available yet but it’s progressing towards Preview.
* **Private preview:** An early access feature available to selected customers which helps Axiom validate the feature with trusted partners.
* **Public preview:** The feature is available for everyone to try but may have some rough edges. Axiom is gathering feedback before making it GA.
* **Generally available (GA):** The feature is fully released, production-ready, and supported. Feel free to use it in your workflows.
* **Planned end of life:** The feature is scheduled to be retired. It’s still working but you should start migrating to alternative solutions.
* **End of life:** The feature is no longer available or supported. Axiom has sunset it in favor of newer solutions.
Private and public preview features are experimental. They aren’t guaranteed to work as expected and may return unexpected query results. Axiom doesn’t guarantee data integrity or accuracy for preview features. Consider the risk you run when you use preview features against production workloads.
{/*
Current private preview features:
*/}
Current public preview features:
* [Cursor-based pagination](/restapi/pagination)
* [`externaldata` operator](/apl/tabular-operators/externaldata-operator)
* [`join` operator](/apl/tabular-operators/join-operator)
* [Metrics Processing Language (MPL)](/mpl/introduction)
---
# Security
Source: https://axiom.co/docs/platform-overview/security
## Compliance [#compliance]
Axiom complies with key standards and regulations.
### ISO 27001 [#iso-27001]
Axiom’s ISO 27001 certification indicates that Axiom has established a robust system to manage information security risks concerning the data it controls or processes.
### SOC2 Type II [#soc2-type-ii]
Axiom’s SOC 2 Type II certification proves that Axiom has strict security measures in place to protect customer data.
If you’re on the Axiom Cloud or the Bring Your Own Cloud plan, you can request a report that outlines the technical and legal details under non-disclosure agreement (NDA). For more information, see the [Axiom Trust Center](https://trust.axiom.co/).
### General Data Protection Regulation (GDPR) [#general-data-protection-regulation-gdpr]
Axiom complies with GDPR and its core principles including data minimization and rights of the data subject.
### California Consumer Privacy Act (CCPA) [#california-consumer-privacy-act-ccpa]
Axiom complies with CCPA and its core principles including transparency on data collection, processing and storage. You can request a Data Processing Addendum that outlines the technical and legal details.
### Health Insurance Portability and Accountability Act (HIPAA) [#health-insurance-portability-and-accountability-act-hipaa]
Axiom complies with HIPAA and its core principles. HIPAA compliance means that Axiom can enter into Business Associate Agreements (BAAs) with healthcare providers, insurers, pharma and health research firms, and service providers who work with protected health information (PHI).
You can request a Business Associate Agreement (BAA) with Axiom if you meet the following requirements:
* You’re on the Axiom Cloud plan.
* You have signed up for all of the following security-related add-ons:
* [Role-Based Access Control (RBAC)](/reference/settings)
* [SAML Single Sign-On (SSO)](/reference/settings#single-sign-on-saml-sso)
* [Audit log](/reference/audit-log)
For more information, see the [Axiom Trust Center](https://trust.axiom.co/) and [Manage add-ons](/reference/usage-billing#manage-add-ons).
After signing a BAA, user sessions in your organization time out after 24 hours to meet HIPAA security requirements.
## Compliance and Axiom AI [#compliance-and-axiom-ai]
## Comprehensive security measures [#comprehensive-security-measures]
Axiom employs a multi-faceted approach to ensure data security, covering encryption, penetration testing, infrastructure security, and organizational measures.
### Data encryption [#data-encryption]
Data at Axiom is encrypted both at rest and in transit. Axiom’s encryption practices align with industry standards and are regularly audited to ensure the highest level of security.
Data is stored in the Amazon Web Services (AWS) infrastructure at rest and encrypted through technologies offered by AWS using AES-256 bit encryption. The same high level of security is provided for data in transit using AES-256 bit encryption and TLS to secure network traffic.
### Penetration testing [#penetration-testing]
Axiom performs regular vulnerability scans and annual penetration tests to proactively identify and mitigate potential security threats.
### System protection [#system-protection]
Axiom systems are segmented into separate networks and protected through restrictive firewall rules. Network access to production environments is tightly restricted. Monitors are in place to ensure that service delivery matches SLA requirements.
### Resilience against system failure [#resilience-against-system-failure]
Axiom maintains daily encrypted backups and full system replication of production platforms across multiple availability zones to ensure business continuity and resilience against system failures. Axiom periodically tests restoration capabilities to ensure your data is always protected and accessible.
### Organizational security practices [#organizational-security-practices]
Axiom’s commitment to security extends beyond technological measures to include comprehensive organizational practices. Axiom employees receive regular security training and follow stringent security requirements like encryption of storage and two-factor authentication.
Axiom supports secure, centralized user authentication through SAML-based SSO (Security Assertion Markup Language-based Single Sign-On). This makes it easy to keep access grants up-to-date with support for the industry standard SCIM protocol. Axiom supports both the flows initiated by the service provider and the identity provider (SP- and the IdP-initiated flows).
Axiom enables you to take control over access to your data and features within Axiom through role-based permissions.
Axiom provides you with searchable audit logs that provide you with comprehensive tracking of all activity in your Axiom organization to meet even the most stringent compliance requirements.
SAML-based SSO, role-based access control (RBAC), and full access to the audit log are available as add-ons on the Axiom Cloud plan. For more information, see [Manage add-ons](/reference/usage-billing#manage-add-ons).
## Sub-processors [#sub-processors]
Axiom works with a limited number of trusted sub-processors. For a full list, see [Sub-processors](https://trust.axiom.co/subprocessors). Axiom regularly reviews all third parties to ensure they meet high standards for security.
## Report vulnerabilities [#report-vulnerabilities]
Axiom takes all reports seriously and has a responsible disclosure process. Please submit vulnerabilities by email to [security@axiom.co](mailto:security@axiom.co).
---
# Correlations
Source: https://axiom.co/docs/query-data/correlations
Correlations connect datasets that describe the same system from different telemetry signals. A correlation group records which logs, traces, and metrics datasets belong together.
Use correlations to move between related signals without manually copying IDs or rebuilding context in another query.
## What correlations are [#what-correlations-are]
A correlation group contains up to three datasets:
* **Logs dataset:** OpenTelemetry log records with trace context.
* **Traces dataset:** OpenTelemetry trace spans.
* **Metrics dataset:** OpenTelemetry metrics stored in MetricsDB.
Axiom uses the datasets in a correlation group to find related data during an investigation. For example, a log event that contains a trace ID links to the matching trace. A trace links back to log records from the correlated logs dataset. A span in a trace links to metrics from the correlated metrics dataset.
## Prerequisites [#prerequisites]
Before you create a correlation group, prepare the datasets that you plan to connect:
* Send logs, traces, and metrics to separate datasets.
* Use a dedicated OpenTelemetry metrics dataset for metrics.
* Ensure logs include `trace_id` and `span_id` for log-to-trace and trace-to-log navigation. This should happen by default if you use `Logger.emit` or the equivalent in your OpenTelemetry library.
* Use OpenTelemetry semantic conventions when possible
## Create a correlation group [#create-a-correlation-group]
1. In Axiom Console, go to **Datasets**.
2. Click **Correlations**.
3. Click **New correlation group**.
4. Enter a **Name**.
5. Enter a **Slug**.
6. Select one or more datasets:
* **Logs dataset**
* **Traces dataset**
* **Metrics dataset**
7. Click **Create correlation group**.
Alternatively, you can create a correlation group from new datasets. This will create logs, traces, and metrics datasets with a prefix and optional suffix of your choice, and create a correlation group that contains them.
## Use correlations [#use-correlations]
Use correlations from query results and trace details to move between telemetry signals.
### Go from logs to traces [#go-from-logs-to-traces]
When a log event belongs to a correlated logs dataset and contains a trace ID, Axiom links the event to the matching trace in the correlated traces dataset.
#### Query view [#query-view]
1. Run a query against a logs dataset that has correlated traces.
2. Click a log event to view details.
3. Click **View trace** to open the matching trace in the Trace view.
#### Stream tab [#stream-tab]
1. Open the stream for a logs dataset that has correlated traces.
2. Click a log event to view details.
3. Click **View trace** to open the matching trace in the Trace view.
### Go from traces to logs [#go-from-traces-to-logs]
When a trace belongs to a correlated traces dataset, Axiom queries the correlated logs dataset for log records in the trace time range.
Use this flow when a trace shows a slow or failed span and the investigation needs nearby log records from the same request.
### Go from traces to metrics [#go-from-traces-to-metrics]
When a trace belongs to a correlated traces dataset and the group has a metrics dataset, Axiom shows relevant span metrics in the span details panel.
Trace-to-metrics correlation uses OpenTelemetry semantic conventions and the metric catalog to show common runtime, process, container, and service metrics. Each metric includes an **Explore** action that opens the generated MPL query in the Query tab.
Use this flow when a span shows latency or errors and the investigation needs resource or service health around the same time.
Trace-to-metrics correlation requires the correlated metrics dataset to use an edge deployment.
## What's next [#whats-next]
* [Explore traces](/query-data/traces)
* [Metrics](/query-data/metrics)
* [Datasets overview](/query-data/datasets)
---
# Datasets overview
Source: https://axiom.co/docs/query-data/datasets
The Datasets tab allows you to gain a better understanding of the fields you have in your datasets.
In Axiom, an individual piece of data is an event, and a dataset is a collection of related events. Datasets contain incoming event data. The Datasets tab provides you with information about each field within your datasets.
## Datasets overview [#datasets-overview]
When you open the Datasets tab, you see the list of datasets.
Right-click a dataset to access the following options:
* **Open dataset:** Open the dataset in the Datasets tab.
* **Open in Stream:** Open the dataset in the Stream tab.
* **Open in Query:** Open the dataset in the Query tab.
* **Edit dataset:** Change the dataset description or data retention period.
* **Copy dataset name:** Copy the name of the dataset to your clipboard.
* **Copy link to dataset:** Copy a link to the dataset to your clipboard.
* **Open in new tab:** Open the dataset in a new browser tab.
* **Delete dataset:** Delete the dataset.
### Explore datasets [#explore-datasets]
To explore the fields in a dataset, select the dataset from the list.
When you select a dataset, Axiom displays the list of fields within the dataset on the left. The field types are the following:
* String
* Number
* Boolean
* Array
* [Virtual fields](#virtual-fields)
This view flattens field names with dot notation. This means that the event `{"foo": { "bar": "baz" }}` appears as `foo.bar`. Field names containing periods (`.`) are folded.
By default, when you ingest an event with a field that isn’t yet part of the dataset’s schema, Axiom adds the new field to the schema. To freeze the set of fields in an event dataset and the type of each field, lock its schema. For more information, see [Lock dataset schema](/reference/datasets#lock-dataset-schema).
On the right, you see the following:
* [Views](#views)
* [Saved queries](#saved-queries)
* [Query history](#query-history)
### Explore metrics datasets [#explore-metrics-datasets]
When you select a metrics dataset, Axiom displays the list of metrics in the dataset instead of a list of fields. Each row displays the type, the name, and the unit of the metric.
Axiom displays the unit of a metric in one of the following ways:
* Units without braces are standard [UCUM](https://ucum.org/) units that Axiom recognizes and displays as readable labels. For example, a metric ingested with the unit `By` appears as `bytes`, and a metric ingested with the unit `ms` appears as `milliseconds`. The dimensionless unit `1` appears as `dimensionless`.
* Units in curly braces are values that Axiom doesn’t translate. These are UCUM annotations like `{requests}` or unit values that aren’t valid UCUM units. Axiom displays the value inside braces as it was ingested.
* Empty braces (`{}`) mean that unit information isn’t available for the metric. This happens when the metric was ingested without a unit or when the unit of the metric isn’t consistent within the selected time range.
### Edit field [#edit-field]
To edit a field:
1. Go to the Datasets tab.
2. Select the dataset that contains the field.
3. Find the field in the list, and then click it.
4. Edit the following:
* Field description.
* Field unit. This is only available for number field types.
* Hidden. This means that the field is still present in the underlying Axiom database, but it doesn’t appear in the Axiom UI. Use this option if you sent the field to Axiom by mistake or you don’t want to use it anymore in Axiom.
To remove fields from the dataset entirely, delete them. For more information, see [Delete fields](/reference/datasets#delete-fields).
## Quick charts [#quick-charts]
Quick charts allow fast charting of fields depending on their field type. For example, for number fields, choose one of the following for easily visualizing the data:
* Percentiles
* Averages
* Histograms
## Virtual fields [#virtual-fields]
Virtual fields are powerful expressions that run on every event during a query to create new fields. The virtual fields are calculated from the events in the query using an APL expression. They’re similar to tools like derived columns in other products but super-charged with an expressive interpreter and with the flexibility to add, edit, or remove them at any time.
To manage a dataset’s virtual fields, click in the toolbar.
For more information, see [Virtual fields](/query-data/virtual-fields).
## Map fields [#map-fields]
Map fields are a special type of field that can hold a collection of nested key-value pairs within a single field. You can think of the content of a map field as a JSON object. The Dataset tab enables you to create map fields, and view unused and removed map fields. For more information, see [Map fields](/apl/data-types/map-fields#create-map-fields).
## Views [#views]
Views allow you to apply commonly used filters and transformations to your dataset. The result is a view that you can use similarly to how you use datasets. The concept of a view in Axiom is similar to the concept of a virtual table in a database.
For more information, see [Views](/query-data/views).
## Queries [#queries]
Every query has a unique ID that you can save and share with your team members. The Datasets tab allows you to do the following:
* Save a query so that you and your team members can easily find it in the future.
* Browse previous queries and find a past query.
### Saved queries [#saved-queries]
To find and run previously saved queries:
1. Select a dataset.
2. Optional: In the top right of the **Saved queries** section, select whether to display your queries or all queries saved by members of your organization, including queries you saved.
3. Find the query in the list, and then click it to run the query.
Saved queries are automatically visible to all members of your Axiom organization.
### Query history [#query-history]
To find and run recent queries:
1. Select a dataset.
2. Optional: In the top right of the **Query history** section, select whether to display your queries or your team’s queries.
3. Find the query in the list, and then click it to run the query.
---
# Query using Builder
Source: https://axiom.co/docs/query-data/explore
Builder allows you query your data using a visual interface in the Console.
## Typical query workflow [#typical-query-workflow]
Creating a query in Builder typically involves the following steps:
1. **Source:** Select the data you want to query.
2. **Filter:** Narrow down the query results.
3. **Transform and aggregate:** Apply functions to shape and summarize the data before viewing results.
4. **Time range:** Specify the time period over which you want to look up data.
Builder adapts to the type of data you query:
* **Logs, traces, and events:** Select dataset as the source, use **Summarize** to aggregate, and **More** for sort and limit options.
* **Metrics:** Select dataset and metric as the source, use **Transformations** to transform and aggregate the data.
## Query data using Builder [#query-data-using-builder]
1. Click the Query tab.
2. Click **Builder** in the top left.
3. Define the query:
* From the list, select the dataset that you want to query.
* In **Where**, [add filters](#add-filters) to narrow down the query results.
* In **Summarize**, [add visualizations](#add-visualizations) to the query results.
* In **More**, [specify additional options](#more-options) such as sorting the results or limiting the number of displayed events.
* In **Dataset**, define the source of your query. Select an OTel metrics dataset, and then select the metric you want to query.
The dataset and metric names are separated by a colon in the Builder interface. For example, `axiom-dev.metrics:alertmanager_alerts`.
* In **Where**, [add filters](#filter) to narrow down the query results. Restrict the query to a set of series whose tag values match the conditions you specify.
* In **Transformations**, [select transformations](#transformations) to apply to the data.
The metric selector only shows metrics that were active during the selected time range. Expand the time range to see more metrics in the dropdown.
4. [Select the time range](#select-time-range).
5. Click **Run**.
While the query runs, the status bar gives you continuous updates about the number of rows examined, matched, and returned.
See below for more information about each of these steps.
## Example query [#example-query]
This example queries the `sample-http-logs` dataset to find all events where the HTTP status code is 200 and groups the results by county.
This example queries the `axiom-dev.metrics` dataset’s `alertmanager_alerts` metric one hour before the current time. It filters results to events where `k8s.namespace.name` is `monitoring` and aggregates events over 30-second time windows into their average value.
## Query logs, traces, and events [#query-logs-traces-and-events]
### Add filters [#add-filters]
Use the **Where** section to filter the results to specific events. For example, to filter for events that originate in a specific geolocation like France.
To add a filter:
1. Click **+** in the **Where** section.
2. Select the field where you want to filter for values. For example, `geo.country`.
3. Select the logical operator of the filter. These are different for each field type. For example, you can use **starts-with** for string fields and **>=** for number fields. In this example, select `==` for an exact match.
4. Specify the value for which you want to filter. In this example, enter `France`.
When you run the query, the results only show events matching the criteria you specified for the filter.
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20where%20%5B'geo.country'%5D%20%3D~%20'France'%22%7D)
### Add multiple filters [#add-multiple-filters]
You can add multiple filters and combine them with AND/OR operators. For example, to filter for events that originate in France or Germany.
To add and combine multiple filters:
1. Add a filter for France as explained in [Add filters](#add-filters).
2. Add a filter for Germany as explained in [Add filters](#add-filters).
3. Click **and** that appears between the two filters, and then select **or**.
The query results display events that originate in France or Germany.
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20where%20\(%5B'geo.country'%5D%20%3D~%20'France'%20or%20%5B'geo.country'%5D%20%3D~%20'Germany'\)%22%7D)
You can add groups of filters using the **New Group** element.
Axiom supports AND/OR operators at the top level and one level deep.
### Add visualizations [#add-visualizations]
Axiom provides powerful visualizations that display the output of aggregate functions across your dataset. The **Summarize** section provides you with several ways to visualize the query results. For example, the `count` visualization displays the number of events matching your query over time. Some visualizations require an argument such as a field or other parameters.
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20summarize%20count\(\)%20by%20bin_auto\(_time\)%22%7D)
For more information about visualizations, see [Visualize data](/query-data/visualizations).
### Segment data [#segment-data]
When visualizing data, segment data into specific groups to see more clearly how the data behaves. For example, to see how many events originate in each geolocation, select the `count` visualization and group by `geo.country`.
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20summarize%20count\(\)%20by%20bin_auto\(_time\)%2C%20%5B'geo.country'%5D%22%7D)
### More options [#more-options]
In the **More** section, specify the following additional options:
* By default, Axiom automatically chooses the best ordering for the query results. To specify the sorting order manually, click **Sort by**, and then select the field according to which you want to sort the results.
* To limit the number of events the query returns, click **Limit**, and then specify the maximum number of returned events.
* Specify whether to display or hide open intervals.
## Query metrics [#query-metrics]
Your metrics data is organized into datasets, metrics, tags, and series:
* **Dataset:** A group of related metrics.
* **Metric:** A measurement that tracks a specific aspect of your system over time.
* **Tag:** A key-value pair identifying a series.
* **Series:** A unique combination of a metric and tag set.
### Filter [#filter]
Use the **Where** section to filter series based on tag values:
1. Click **+** in the **Where** section.
2. Select the tag where you want to filter for values.
3. Select the logical operator of the filter. Available operators are:
* Equality: `==`, `!=`
* Comparisons: `<`, `<=`, `>`, `>=`
4. Specify the value for which you want to filter.
5. Click **+** to add another filter and join them with the logical and operator.
For example, the following joins three filters: `project == /.*metrics.*/ and code >= 200 and code < 300`.
### Transformations [#transformations]
Use the **Transformations** section to transform individual values or series.
1. Click **+** in the **Transformations** section.
2. Select the transformation you want to apply to the data. Available transformations are:
* **map:** Map the data to a new value using the expression you specify.
* **align:** Aggregate data using the function and the time window you specify.
* **group:** Group the data by a set of tags using the aggregation function you specify.
* **bucket** Aggregate the data by time and tag dimensions simultaneously.
#### Map [#map]
Use `map` to transform individual values.
Available mapping functions:
| Function | Description |
| --------------------- | ------------------------------------------------------- |
| `rate` | Computes the per-second rate of change for a metric. |
| `abs` | Returns the absolute value of each data point. |
| `interpolate::linear` | Linear interpolation of missing values. |
| `fill::prev` | Fills missing values using the previous non-null value. |
For example, to calculate rate per second for the metric, use `map rate`. To fill empty values with the latest value, use `map fill::prev`.
#### Align [#align]
Use `align` to aggregate over time windows. You can specify the time window and the aggregation function to apply.
Available aggregation functions:
| Function | Description |
| ------------ | -------------------------------------- |
| `avg` | Averages values in each interval. |
| `count` | Counts non-null values per interval. |
| `max` | Takes the maximum value per interval. |
| `min` | Takes the minimum value per interval. |
| `prom::rate` | PromQL-style rate calculation. |
| `sum` | Sums values in each interval. |
| `last` | Takes the last value in each interval. |
For example, to calculate the average over 5-minute time windows, use `align to 5m using avg`. To count the data points in the last hour, use `align to 1h using count`.
When metrics emit data at regular intervals but with different offsets across time series, `align` maps your data to a fixed set of time intervals. This makes it easier to visualize data from different sources on a single chart. If the alignment interval is shorter than the emission interval, some intervals can have null values. Select how to handle null values in the [chart options](/query-data/query-results#configure-chart-options).
#### Group [#group]
Use `group` to combine series by tags. You can specify the tags to group by and the aggregation function to apply. If you don’t specify tags, Axiom aggregates all series into one group.
Available aggregation functions:
| Function | Description |
| -------- | ---------------------------------- |
| `avg` | Averages values in each group. |
| `count` | Counts non-null values per group. |
| `max` | Takes the maximum value per group. |
| `min` | Takes the minimum value per group. |
| `sum` | Sums values in each group. |
For example:
* To calculate the number of series, use `group using count`.
* To sum the values of all series, use `group using sum`.
* To group data by the `project` and `namespace` tags using the `sum` aggregation, use `group by project, namespace using sum`.
#### Bucket [#bucket]
Use `bucket` to aggregate over time and tag dimensions simultaneously.
Available aggregation functions:
| Function | Description |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `avg` | Averages values in each group and time inverval. |
| `count` | Counts non-null values per group and time inverval. |
| `max` | Takes the maximum value per group and time inverval. |
| `min` | Takes the minimum value per group and time inverval. |
| `sum` | Sums values in each group and time inverval. |
| `quantile` | Computes the specified quantile per group and time inverval. Specify the quantile as a value between 0 and 1. For example, specifying 0.99 corresponds to the 99th percentile. |
For example:
* To calculate the average value per group and time interval, use `bucket using histogram(avg)`.
* To also count the number of data points per group and time interval, use `bucket using histogram(count, avg)`.
To show the results of multiple aggregations in a single chart, use multiple functions.
If you don’t specify tags with `bucket`, Axiom applies the specified aggregations to all tags.
When the underlying metric is a histogram, Axiom computes `bucket` aggregations using the `interpolate_cumulative_histogram` and `interpolate_delta_histogram` functions depending on the temporality used. For quantile aggregations, this estimates the quantile using the underlying histogram data.
## Select time range [#select-time-range]
When you select the time range of a query, you specify the time interval where you want to look for events.
To select the time range, choose one of the following options:
1. In the top left, click **Time range**.
2. Choose one of the following options:
* Use the **Quick range** items to quickly select popular time ranges.
* To the right of the **Start date** and **End date** fields, click **Select date and time** to select specific times.
* Enter the specific time in the **Start date** and **End date** fields using natural language. For example, `1 hour ago` or `last Monday at 3pm`. For more information on the supported natural language inputs, see the [Sugar documentation](https://sugarjs.com/docs/#/DateParsing). Don’t use the `from` and `after` keywords in your input.
---
# Create dashboards with filters
Source: https://axiom.co/docs/query-data/filters
Filters let you choose the data you want to display in your dashboard. This page explains how to create and configure dashboards with filters.
Try out all the examples explained on this page in the [HTTP logs dashboard of the Axiom Playground](https://play.axiom.co/axiom-play-qf1k/dashboards/gZXp8KNJy68q7yGsuA).
## Filter types [#filter-types]
You can use two types of filter in your dashboards:
* Search filters let you enter any text, filter for data that matches the text input, and then narrow down the results displayed by the charts in the dashboard. For example, you enter **Mac OS**, filter for results that contain this string in the user agent field, and then only display the corresponding results in the charts.
* Select filters let you choose one option from a list of options, filter for data that matches the chosen option, and then narrow down the results displayed by the charts in the dashboard. For example, you choose **France** from the list of countries, filter for results that match the chosen geographical origin, and then only display the corresponding results in the charts.
## Use dashboards with filters [#use-dashboards-with-filters]
To see different filters in action, check out the [HTTP logs dashboard of the Axiom Playground](https://play.axiom.co/axiom-play-qf1k/dashboards/gZXp8KNJy68q7yGsuA). The search filter on the top right lets you search for a specific phrase in the user agent field to only display HTTP requests from a specific user agent. The select filters on the top left let you choose country and city to only display HTTP requests from a specific geographical origin.
In each chart on your dashboard, you can use all, some, or none of the filters to narrow down the data displayed in the chart. For example, in the [HTTP logs dashboard of the Axiom Playground](https://play.axiom.co/axiom-play-qf1k/dashboards/gZXp8KNJy68q7yGsuA), the charts **Popular data centers** and **Popular countries** aren’t affected by your choices in the select filters. You choose to use a filter in a chart by [referencing the unique ID of the filter in the chart query](#reference-filters-in-chart-query) as explained later on this page.
Filters can be interdependent. For example, in the [HTTP logs dashboard of the Axiom Playground](https://play.axiom.co/axiom-play-qf1k/dashboards/gZXp8KNJy68q7yGsuA), the values you can choose in the city filter depend on your choice in the country filter. You make a filter dependent on another by [referencing the unique ID of the filter](#create-select-filters) as explained later on this page.
For each filter, you define a unique ID when you create the filter. When you create multiple filters, all of them must have a different ID. You can later use this ID to reference the filter in dashboard charts and other filters.
Each filter must have a unique ID. This means that the filter IDs must be different from each other and from the field names in your data. In general, starting filter IDs with an underscore (`_`) can help avoid naming conflicts with fields in your data. For example, if you have a field named `user_agent`, you can define the filter ID as `_user_agent_filter`.
Filters are visually displayed in your dashboard in a filter bar that you can create and move as any other chart. You can add different types of filter to a single filter bar. A filter bar can contain maximum one search filter and any number of select filters.
## Create search filters [#create-search-filters]
1. In the empty dashboard, click **Edit dashboard**.
2. Click **Add element**.
3. In **Chart type**, select **Filter bar**.
4. In **Filter type**, select **Search**.
5. In **Filter name**, enter the placeholder text you want to display in your search filter.
6. Specify a unique filter ID that you later use to reference the filter. For example, `user_agent_filter`.
Try out this filter in the [HTTP logs dashboard of the Axiom Playground](https://play.axiom.co/axiom-play-qf1k/dashboards/gZXp8KNJy68q7yGsuA).
## Create select filters [#create-select-filters]
1. In the empty dashboard, click **Edit dashboard**.
2. Click **Add element**.
3. In **Chart type**, select **Filter bar**.
4. In **Filter type**, select **Select**.
5. In **Filter name**, enter the text you want to display above the select filter.
6. Specify a unique filter ID that you later use to reference the filter. For example, `country_filter`.
7. In the **Value** section, define the list of options to choose from in the select filter as key-value pairs. Axiom displays the key in the list of options in the filter dropdown, and uses the value to filter your data. For example, the key `France` is displayed in the list of options, and the value `FR` is used to filter data in your charts. Define the key-value pairs in one of the following ways:
* Choose **List** to manually define a static list of options. Enter the options as a list of key-value pairs.
* Choose **Query** to define a dynamic list of options. In this case, Axiom determines the list of options displayed in the filter dynamically based on a query. You can use an APL query or an MPL metrics query, as explained in [Define options with an APL query](#define-options-with-an-apl-query) and [Define options with a metrics query](#define-options-with-a-metrics-query).
### Define options with an APL query [#define-options-with-an-apl-query]
To populate the list of options from an APL query, the results must contain a `key` and a `value` field, which Axiom interprets as key-value pairs. Use the `project` command to create these fields from any output.
The value in the key-value pairs must be a string. To use number or Boolean fields, convert their values to strings using [`tostring()`](/apl/scalar-functions/conversion-functions#tostring\(\)).
The example APL query below uses the distinct values in the `geo.country` field to populate the list of options. It projects these values as both the key and the value and sorts them in alphabetical order.
```kusto
['sample-http-logs']
| distinct ['geo.country']
| project key=['geo.country'] , value=['geo.country']
| sort by key asc
```
See this filter in action in the [HTTP logs dashboard of the Axiom Playground](https://play.axiom.co/axiom-play-qf1k/dashboards/gZXp8KNJy68q7yGsuA).
### Define options with a metrics query [#define-options-with-a-metrics-query]
To populate the list of options from an MPL metrics query, group by exactly one tag. Axiom uses the distinct values of that tag as the filter options.
Add `align using last` before the `group by` clause to simplify the query and reduce the data Axiom processes when generating the options.
The example MPL query below populates the list of options with the distinct values of the `service.name` tag in the `http.server.request.duration` metric:
```mpl
`otel-demo-metrics`:`http.server.request.duration`
| align using last
| group by `service.name` using count
```
### Create dependent select filters [#create-dependent-select-filters]
Sometimes it makes sense that filters depend on each other. For example, in one filter you select the country, and in the other filter the city. In this case, the list of options in the city filter depends on your choice in the country filter.
To create a filter that depends on another filter, follow these steps:
1. Create a filter. In this example, the ID of the independent filter is `country_filter`.
2. Create a dependent select filter. In this example, the ID of the dependent select filter is `city_filter`. The dependent filter must be a select filter.
3. In the dependent filter, use `declare query_parameters` at the beginning of your query to reference the independent filter’s ID. For example, `declare query_parameters (country_filter:string = "")`. This lets you use `country_filter` as a parameter in your query even though it doesn’t exist in your data. For more information, see [Declare query parameters](#declare-query-parameters).
4. Use the `country_filter` parameter to filter results in the dependent filter’s query.
The example APL query below defines the dependent filter. It uses the value of the independent filter with the ID `country_filter` to determine the list of options in the dependent filter. Based on the selected country, the APL query uses the distinct values in the `geo.city` field to populate the list of options. It projects these values as both the key and the value and sorts them in alphabetical order.
```kusto
declare query_parameters (country_filter:string = "");
['sample-http-logs']
| where isnotempty(['geo.country']) and isnotempty(['geo.city'])
| where ['geo.country'] == country_filter
| summarize count() by ['geo.city']
| project key = ['geo.city'], value = ['geo.city']
| sort by key asc
```
Check out this filter in the [HTTP logs dashboard of the Axiom Playground](https://play.axiom.co/axiom-play-qf1k/dashboards/gZXp8KNJy68q7yGsuA).
### Filter to select datasets [#filter-to-select-datasets]
Use a select filter to choose the dataset whose values you want to display in the dashboard:
1. Create a select filter where you specify the dataset names as the keys and the values. In this example, the ID of the independent filter is `dataset_filter`.
2. Create a dashboard element based on an APL query:
* Use `declare query_parameters` at the beginning of your query to reference the filter’s ID. For example, `declare query_parameters (dataset_filter:string = "")`.
* Use the `dataset_filter` parameter as the value of the `table` operator to filter for dataset names in the query.
The APL query below defines a chart where the data displayed depends on your choice in the filter with the ID `dataset_filter`. The chart only displays data from the selected dataset.
```kusto
declare query_parameters (dataset_filter:string = "");
table(dataset_filter)
| summarize count() by bin_auto(_time)
```
## Reference filters in chart queries [#reference-filters-in-chart-queries]
After creating a filter, specify how you want to use the value chosen in the filter. Include the filter in the APL query of each chart where you want to use the filter to narrow down results. To do so, use `declare query_parameters` at the beginning of the chart’s APL query to reference the filter’s ID. For example, `declare query_parameters (country_filter:string = "")`. This lets you use `country_filter` as a parameter in the chart’s query even though it doesn’t exist in your data. For more information, see [Declare query parameters](#declare-query-parameters).
The APL query below defines a statistic chart where the data displayed depends on your choice in the filter with the ID `country_filter`. For example, if you choose **France** in the filter, the chart only displays the number of HTTP requests from this geographical origin.
```kusto
declare query_parameters (country_filter:string = "");
['sample-http-logs']
| where isempty(country_filter) or ['geo.country'] == country_filter
| summarize count() by bin_auto(_time)
```
## Combine filters [#combine-filters]
You can combine several filters of different types in a chart’s query. For example, the APL query below defines a statistic chart where the data displayed depends on three filters:
* A select filter that lists countries.
* A select filter that lists cities within the chosen country.
* A search filter that lets you search in the `user_agent` field.
```kusto
declare query_parameters (country_filter:string = "",
city_filter:string = "",
user_agent_filter:string = "");
['sample-http-logs']
| where isempty(country_filter) or ['geo.country'] == country_filter
| where isempty(city_filter) or ['geo.city'] == city_filter
| where isempty(user_agent_filter) or user_agent contains user_agent_filter
| summarize count() by bin_auto(_time)
```
See this filter in action in the Total requests chart in the [HTTP logs dashboard of the Axiom Playground](https://play.axiom.co/axiom-play-qf1k/dashboards/gZXp8KNJy68q7yGsuA).
## Declare query parameters [#declare-query-parameters]
Use `declare query_parameters` at the beginning of an APL query to reference a filter’s ID. For example, `declare query_parameters (country_filter:string = "")`. This lets you use `country_filter` as a parameter in the chart’s query even though it doesn’t exist in your data.
You must define unique IDs for each filter. This means that the filter IDs must be different from each other and from the field names in your data. In general, starting filter IDs with an underscore (`_`) can help avoid naming conflicts with fields in your data. For example, if you have a field named `user_agent`, you can define the filter ID as `_user_agent_filter`.
The `declare query_parameters` statement defines the data type of the parameter. In the case of filters, the data type is always string.
## Set filter values in the URL [#set-filter-values-in-the-url]
To set the value of a filter when a dashboard loads, add `v_FILTER_ID=VALUE` to the dashboard URL. Replace `FILTER_ID` with the ID of the filter.
## Use different queries depending on filters [#use-different-queries-depending-on-filters]
A table chart can hold several APL queries. Axiom runs the first query whose required filters all have a value.
* Separate queries with exactly one empty line. Don’t add spaces or tabs to the empty line, and don’t add empty lines within a query. Otherwise, the chart fails with the error `unexpected token "declare" (expected )`.
* To specify the filters a query requires, add the comment `// requires-variable: FILTER_ID` to the query. Separate several filter IDs with commas.
* To display a title when Axiom runs a query, add the comment `// title: TITLE` to the query.
* Start comments at the beginning of the line. Axiom ignores indented comments.
* Place a query without `// requires-variable:` last. Axiom runs it if none of the queries before it match.
* Declare query parameters in each query.
## Choose default option in select filter [#choose-default-option-in-select-filter]
The default option of a select filter is the option chosen when the dashboard loads. In most cases, this means that no filter is applied. This option is added automatically as the first in the list of options when you create the filter with the key **All** and an empty value. To choose another default value, reorder the list of options.
## Handle empty values [#handle-empty-values]
The examples on this page assume that you use the default setting where the **All** key means an empty value, and the empty value in a filter means that the data isn’t filtered in the chart. The example chart queries above handle this empty (null) value in the `where` clause. For example, `where isempty(country_filter) or [‘geo.country’] == country_filter` means that if no option is chosen in the country filter, `isempty(country_filter)` is true and the data isn’t filtered. If any other option is chosen with a non-null value, the chart only displays data where the `geo.country` field’s value is the same as the value chosen in the filter.
## Use filters with metrics queries [#use-filters-with-metrics-queries]
Filter bars work with MPL metrics queries as well as APL queries.
### Reference filter variables [#reference-filter-variables]
In an MPL query, reference a filter by prefixing its ID with `$`. For example, a filter with ID `service_filter` is referenced as `$service_filter`.
Use `$filter_id` in a `where` clause to filter metric series by the selected value:
```mpl
dataset:metric
| where tag_name == $filter_id
| align to $__interval using avg
```
**Example:**
The query below filters `http.server.request.duration` to a specific service chosen in the filter bar with ID `service_filter`:
```mpl
`otel-demo-metrics`:`http.server.request.duration`
| where `service.name` == $service_filter
| align to $__interval using avg
```
### Optional filters [#optional-filters]
By default, a filter must have a value selected for the query to run. To make a filter optional — so the query returns all data when no value is selected — use the **Unset** default and an `ifdef` block.
**Configure the filter bar:**
1. Create a select filter as described in [Create select filters](#create-select-filters).
2. In the filter options, check the **Unset** box for the default value.
Checking **Unset** tells Axiom to treat the variable as optional. When no option is selected, the variable isn't passed to the query.
**Write the query:**
Wrap the `where` clause in an `ifdef` block so it only runs when the variable is set:
```mpl
dataset:metric
| ifdef($filter_id) { where tag_name == $filter_id }
| align to $__interval using avg
```
**Example:**
The query below filters by `service.name` only when a value is selected. When the filter is unset, the query returns data for all services.
```mpl
`otel-demo-metrics`:`http.server.request.duration`
| ifdef($service_filter) { where `service.name` == $service_filter }
| align to $__interval using avg
```
---
# Metrics
Source: https://axiom.co/docs/query-data/metrics
Axiom’s dedicated MetricsDB provides a purpose-built metrics datastore that handles high-cardinality time-series data without the cost penalties and performance degradation common in traditional metrics systems. This section explains how to work with OpenTelemetry (OTel) metrics in Axiom.
## What makes MetricsDB different [#what-makes-metricsdb-different]
MetricsDB is engineered from the ground up to embrace dimensional complexity:
* **High-cardinality as a design principle**: Store metrics with high-cardinality tags. Where other metrics datastore penalize you with higher costs or degraded performance, MetricsDB treats high cardinality as a core capability.
* **Intentional architecture**: The storage format, query engine, and compression algorithms are specifically optimized for time-series metrics workloads. These design constraints are thoughtful trade-offs that deliver exceptional performance and cost-efficiency for real-world metrics use cases.
* **Unified observability**: Query metrics alongside logs, traces, and events, enabling powerful correlations across all your telemetry data without switching tools or learning multiple query languages.
### MetricsDB vs EventDB [#metricsdb-vs-eventdb]
Logs, traces, events, and metrics are different forms of machine data. It’s often possible to represent metrics as events, but a dedicated metrics datastore comes with the following benefits:
* **Efficient compression**: Instrumentation aggregates measurements on the client and sends summaries at regular intervals instead of individual events. This dramatically reduces data volume for high-frequency measurements.
* **Standardized data types**: OpenTelemetry defines a small set of metric types with clear semantics. The metric type tells you how to query the data—no guessing how to aggregate or calculate rates.
* **Faster queries**: Metrics data is stored in a format optimized for producing time series and other popular metrics visualizations. No need to process the data at query time.
### When to use MetricsDB or EventDB for metrics [#when-to-use-metricsdb-or-eventdb-for-metrics]
| Use MetricsDB when | Use EventDB when |
| ---------------------------------------------------------------------------- | ------------------------------------- |
| You can send metrics using the OTel Collector or another OTel-compatible SDK | You can’t use OTel-compatible tooling |
| High-frequency measurements (many per second) | Low-frequency point-in-time gauges |
| You need rate calculations or percentiles | Simple aggregations are sufficient |
When in doubt, use MetricsDB. It’s designed for metrics workloads and scales better as volume grows.
You must use a dedicated dataset for OTel metrics. When you create a dataset, select the type of OTel data you want to send to it. For more information, see [Create dataset](/reference/datasets#create-dataset).
## Ingest metrics [#ingest-metrics]
You can ingest OTel metrics the same way you ingest other types of OTel data.
For more information, see [Send OpenTelemetry data to Axiom](/send-data/opentelemetry).
For the maximum request size and the other limits that apply to metrics ingestion, see [Limits on ingested metrics](/reference/limits#limits-on-ingested-metrics).
The `/v1/metrics` endpoint accepts OTLP data encoded as Protobuf (`application/x-protobuf`) or JSON (`application/json`). Protobuf payloads are smaller, so prefer Protobuf when you send large volumes of metrics.
### Try it quickly with axiom-hostmetrics [#try-it-quickly-with-axiom-hostmetrics]
[axiom-hostmetrics](https://github.com/axiomhq/axiom-hostmetrics) is a small CLI that scrapes host metrics (CPU, memory, disk, network, and more) using the OpenTelemetry `hostmetricsreceiver` and ships them to Axiom via OTLP/HTTP. It’s a fast way to get real metrics data flowing so you can explore MetricsDB and MPL without setting up a full OTel Collector.
Install with Homebrew:
```sh
brew install axiomhq/tap/axiom-hostmetrics
```
Or install with Go:
```sh
go install github.com/axiomhq/axiom-hostmetrics/cmd/axiom-hostmetrics@latest
```
Run `axiom-hostmetrics` with no arguments to launch a setup wizard that asks for your dataset, API token, and endpoint, then starts streaming metrics immediately.
## Query metrics [#query-metrics]
You can query metric data in one of the following ways:
* **Builder**: A visual interface for building queries step by step. For more information, see [Query data using Builder](/query-data/explore).
* **MPL**: A text-based query language (Metrics Processing Language) for writing expressive queries directly. For more information, see [Query metrics using MPL](/mpl/introduction) and [Sample queries](/mpl/sample-queries).
Support for MPL (Metrics Processing Language) is currently in public preview. For more information, see [Feature states](/platform-overview/roadmap#feature-states).
* **MCP**: Use the [Axiom MCP server](/console/intelligence/mcp-server) to allow an MCP-compatible client to query your metrics data.
Histogram and summary metrics carry several components, so you query them differently from other metric types. For more information, see [Query histogram and summary metrics](/mpl/histograms-summaries).
## Migrate PromQL queries [#migrate-promql-queries]
You can translate your existing PromQL queries to MPL with minimal changes. MPL also offers features not available in PromQL, such as native support for non-string tag types and custom transformation pipelines.
For more information, see [Migrate PromQL queries to Axiom](/mpl/migrate-metrics).
## Dashboards and monitors [#dashboards-and-monitors]
You can use OTel metrics in dashboards and monitors the same way you use other data types.
* Build visualizations using metrics queries.
* Set alerts on derived metrics such as error rate or latency percentiles.
* Combine multiple signals in a single panel.
For more information, see [Dashboards](/dashboards/overview) and [Monitors](/monitor-data/monitors).
## Design choices and constraints [#design-choices-and-constraints]
MetricsDB makes intentional architectural trade-offs to optimize for the most common metrics use cases while maintaining exceptional performance at scale.
### Query scope [#query-scope]
You can query one dataset per query.
### Supported data types [#supported-data-types]
MetricsDB focuses on the core OpenTelemetry metric types that cover the vast majority of observability scenarios.
Axiom supports the following OpenTelemetry metric types:
* **Gauge**: Point-in-time measurements. For example, CPU usage or temperature.
* **Histogram**: Distribution of values with configurable buckets. For example, request latency.
* **Sum**: Sum of values. For example, request count.
* **Summary**: Summary of values. For example, request latency.
Axiom accepts up to 256 buckets per histogram data point and up to 256 quantiles per summary data point. Axiom rejects data points that exceed these limits and reports them in the `partial_success` message of the ingest response. For more information, see [Limits on ingested metrics](/reference/limits#limits-on-ingested-metrics).
Axiom doesn’t currently support the following data types:
* Exponential histograms
* `bytes`, `kvlist` tag value types
* Exemplar, baggage, and context data
* Nanosecond-precision timestamps
### Data model optimizations [#data-model-optimizations]
MetricsDB applies the following transformations to improve query performance and reduce storage costs:
* **Timestamp precision**: Truncate nanosecond timestamps to second precision. MetricsDB is built for use cases where second-level granularity is sufficient, and this optimization significantly improves compression ratios and query speed.
* **Unified tag namespace**: Flatten resource, scope, and metric tags into a single namespace. This simplification makes queries more straightforward and enables faster dimensional filtering. You don’t need to remember which tags came from which scope.
* **Histogram handling**: Assume equal-width histograms and don’t preserve histogram metadata. This trade-off supports the most common histogram analysis patterns (percentiles, distribution visualization) while reducing storage requirements.
These design choices reflect real-world metrics usage patterns. If your use case requires capabilities not currently supported, [contact Axiom](https://axiom.co/contact) to discuss your requirements. Your feedback helps shape MetricsDB’s evolution.
---
# Query using Editor
Source: https://axiom.co/docs/query-data/query-editor
Query your data using the text-based query editor in Console:
1. Click the Query tab.
2. Click **Editor** in the top left.
3. Write your query in the editor.
4. Click **Run**.
The Editor of the Query tab accepts both APL (Axiom Processing Language) and MPL (Metrics Processing Language) queries and automatically detects the query language you use:
* APL is a data processing language that supports filtering, extending, and summarizing data. For more information, see [Introduction to APL](/apl/introduction).
* MPL is a metric-focused query language that combines the simplicity of APL with the expressive power of PromQL. It enables effective querying, transformation, and aggregation of metric data, supporting diverse observability use cases. For more information, see [Introduction to MPL](/mpl/introduction).
## Generate query using natural language [#generate-query-using-natural-language]
Instead of writing the query yourself, you can use Axiom AI to generate a query for you. Explain what you want to infer from your data in your own words and Axiom AI generates the valid APL query.
Query using natural language isn't currently supported for metrics datasets.
To generate a query using natural language:
1. Click the Query tab.
2. Click **APL**, and then click in the query editor.
3. Press Cmd/Ctrl K .
4. Type what you want to infer from your data in your own words using natural language, and then click **Generate**. For example, type `Show me the most common status responses in HTTP logs.`
5. Axiom’s AI generates the APL query based on your prompt and gives you the following options:
* Click **Accept** to update the editor with the generated query and change the generated query before running it. Any previous input in the query editor is lost.
* Click **Accept and run** to update the editor with the generated query and run it immediately. Any previous input in the query editor is lost.
* Click **Reject** to go back to your previous input in the query editor and close the query generator.
### Iterate over prompt history [#iterate-over-prompt-history]
Axiom saves the prompts you type in the query generator. To find one of your previous prompts and generate an APL query for it:
1. Click the Query tab.
2. Click **APL**, and then click in the query editor.
3. Press Cmd/Ctrl K .
4. Cycle through your history using the arrow keys and to find the prompt.
5. Click **Generate**.
## APL examples [#apl-examples]
Some APL queries are explained below. The pipe symbol `|` separates the operations as they flow from left to right, and top to bottom.
APL is case-sensitive for everything: dataset names, field names, operators, functions, etc.
Use double forward slashes (`//`) for comments.
### `count` operator [#count-operator]
The below query returns the number of events from the `sample-http-logs` dataset.
```kusto
['sample-http-logs']
| summarize count()
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20summarize%20count\(\)%22%7D)
### `limit` operator [#limit-operator]
The `limit` operator returns a random subset of rows from a dataset up to the specified number of rows. This query returns a thousand rows from `sample-http-logs` randomly chosen by APL.
```kusto
['sample-http-logs']
| limit 1000
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20limit%201000%22%7D)
### `summarize` operator [#summarize-operator]
The `summarize` operator produces a table that aggregates the content of the dataset. This query returns a chart of the `avg(req_duration_ms)`, and a table of `geo.city` and `avg(req_duration_ms)` of the `sample-http-logs` dataset from the time range of 2 days and time interval of 4 hours.
```kusto
['sample-http-logs']
| where _time > ago(2d)
| summarize avg(req_duration_ms) by _time=bin(_time, 4h), ['geo.city']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20where%20_time%20%3E%20ago\(2d\)%5Cn%7C%20summarize%20avg\(req_duration_ms\)%20by%20_time%3Dbin\(_time%2C%204h\)%2C%20%5B'geo.city'%5D%22%7D)
## MPL examples [#mpl-examples]
### `align` operator [#align-operator]
The `align` operator aggregates metric values over time windows. This query returns the average value of the `go.memory.used` metric from the `otel-demo-metrics` dataset, grouped into 5-minute intervals.
```mpl
`otel-demo-metrics`:`go.memory.used`
| align to 5m using avg
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%60otel-demo-metrics%60%3A%60go.memory.used%60%20%7C%20align%20to%205m%20using%20avg%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
### `where` operator [#where-operator]
The `where` operator restricts results to series whose tag values match the specified conditions. This query returns the average value of the `go.memory.used` metric from the `otel-demo-metrics` dataset for the `checkout` deployment, aligned over 5-minute windows.
```mpl
`otel-demo-metrics`:`go.memory.used`
| where `k8s.deployment.name` == "checkout"
| align to 5m using avg
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%60otel-demo-metrics%60%3A%60go.memory.used%60%20%7C%20where%20%60k8s.deployment.name%60%20%3D%3D%20%5C%22checkout%5C%22%20%7C%20align%20to%205m%20using%20avg%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
### `group` operator [#group-operator]
The `group` operator combines multiple series by tag values into a single aggregated series. This query returns the sum of `go.memory.used` per deployment, aligned to 5-minute windows, showing memory usage broken down by `k8s.deployment.name`.
```mpl
`otel-demo-metrics`:`go.memory.used`
| align to 5m using avg
| group by `k8s.deployment.name` using sum
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%60otel-demo-metrics%60%3A%60go.memory.used%60%20%7C%20align%20to%205m%20using%20avg%20%7C%20group%20by%20%60k8s.deployment.name%60%20using%20sum%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
## What's next [#whats-next]
* [Interpret query results](/query-data/query-results)
* [Visualize data](/query-data/visualizations)
* [Views](/query-data/views)
* [Virtual fields](/query-data/virtual-fields)
---
# Query results
Source: https://axiom.co/docs/query-data/query-results
The results view adapts to the query. This means that it adds and removes components as necessary to give you the best experience. The toolbar is always visible and gives details on the currently running or last-run query.
The features explained on this page are available for the results of both APL and MPL queries.
{/*
## Interpret query results
TODO
*/}
## Configure chart options [#configure-chart-options]
Click to access the following options for each chart:
* In **Null values**, specify how to treat missing or undefined values.
* In **Variant**, specify the chart type. Select from area, bar, or line charts.
* In **Y-Axis**, specify the scale of the vertical axis. Select from linear or log scales.
* In **Annotations**, specify the types of annotations to display in the chart.
For more information on each option, see [Configure dashboard elements](/dashboard-elements/configure).
## Merge charts [#merge-charts]
When you run a query that produces several visualizations, Axiom displays the charts separately. For example:
```kusto
['sample-http-logs']
| summarize percentiles_array(req_duration_ms, 50, 90, 95) by status, bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20summarize%20percentiles_array\(req_duration_ms%2C%2050%2C%2090%2C%2095\)%20by%20status%2C%20bin_auto\(_time\)%22%7D)
To merge the separately displayed charts into a single chart, click , and then select **Merge charts**.
## APL query results [#apl-query-results]
When you run an APL query without specifying a visualization, Axiom displays a table with the raw query results.
When you run an APL query with visualizations:
* Axiom displays all the visualizations that you add to the query. Hold the pointer over charts to get extra detail on each result set.
* Below the charts, Axiom displays a table with the totals from each of the aggregate functions for the visualizations you specify.
* If the query includes group-by clauses, there is a row for each group. Hold the pointer over a group row to highlight the group’s data on time series charts. Select the checkboxes on the left to display data only for the selected rows.
This section explains how to work with the results of APL queries in Console.
The features explained in this section are only available for the results of APL queries.
### View event details [#view-event-details]
To view the details for an event, click the event in the table.
To configure the event details view, select one of the following in the top right corner:
* Click **Navigate up** or **Navigate down** to display the details of the next or previous event.
* Click **Fit panel to results** or **Fit panel to viewport height** to change the height of the event details view.
In the event details view, click **More** for additional options:
* **View in context** opens the event in the stream of other events in the Stream tab.
* **Copy link to event**
* **Copy JSON**
* **Show nulls** or **Hide nulls** toggles whether to display fields with null values.
### Select displayed fields [#select-displayed-fields]
To select the fields to be highlighted or displayed in the table, click **Toggle fields panel**, and then click the fields in the list.
Select **Single column for event** to highlight the selected fields below the raw data for each event. Alternatively, select **Column for each field** to display each selected field in a different column without showing the raw event data. In this view, you can resize the width of columns by dragging the borders.
### Configure table options [#configure-table-options]
To configure the table options, click , and then select one of the following:
* Select **Fit columns** to automatically adjust the width of columns to fit the viewport.
* Select **Wrap lines** to keep the whole table within the viewport and avoid horizontal scrolling.
* Select **Show timestamp** to display the time field.
* Select **Show event** to display the raw event data in a single column and highlight the selected fields below the raw data for each event. Alternatively, clear **Show event** to display each selected field in a different column without showing the raw event data. In this view, you can resize the width of columns by dragging the borders.
* Select **Hide nulls** to hide empty data points.
### Event timeline [#event-timeline]
Axiom can also display an event timeline about the distribution of events across the selected time range. In the event timeline, each bar represents the number of events matched within that specific time interval. Holding the pointer over a bar reveals a blue line marking the total events and shows when those events occurred in that particular time range. To display the event timeline, click , and then click **Show chart**.
To show annotations on the timeline, open **Chart options** and enable **Show annotations**.
### Highlight time range [#highlight-time-range]
In the event timeline, line charts, and heat maps, you can drag the pointer over the chart to highlight a specific time range, and then choose one of the following:
* **Zoom** enlarges the section of the chart you highlighted.
* **Show events** displays events in the selected time range in the event details view.
The time range of your query automatically updates to match what you selected.
### Search within query results [#search-within-query-results]
To quickly search for an expression and highlight its occurrences within the query results:
1. In the query results view, press Cmd/Ctrl F .
2. Type the expression that you want to search for. Axiom automatically highlights the matches and jumps to the first match.
3. Press Enter repeatedly to go forward in the list of matches, and press Enter Shift to go backward.
Axiom’s search overrides the browser’s native search. Axiom’s search is more powerful because it highlights matching entries in all results returned by the query (while still respecting automatic limits). In contrast, the browser’s search can only highlight matching entries in the events rendered on your screen.
### Compare time periods [#compare-time-periods]
On time series charts, holding the pointer over a specific time shows the same marker on similar charts for easy comparison.
When you run a query with a time series visualization, you can use the **Compare period** menu to select a historical time against which to compare the results of your time range. For example, to compare the last hour’s average response time to the same time yesterday, select `1 hr` in the time range menu, and then select `-1 day` from the **Compare period** menu. The dotted line represents results from the base date, and the totals table includes the comparative totals.
---
# Save and export queries
Source: https://axiom.co/docs/query-data/save-export-query
Save and export queries and their results to use them in other contexts.
## Save query [#save-query]
Save a query so that you and your team members can easily find it in the future. A saved query only includes the APL query itself, not the query results. Saved queries are automatically visible to all members of your Axiom organization. You can later [find saved queries](/query-data/datasets#saved-queries) in the Datasets tab.
### Create new saved query [#create-new-saved-query]
1. Click **Save** in the top bar.
2. Axiom AI generates a descriptive name based on the query. Accept it or edit it to fit your needs.
3. Click **Save**.
### Replace previously saved query [#replace-previously-saved-query]
1. Click **Save** in the top bar.
2. Click **Replace previously saved query**.
3. Select the existing saved query that you want to overwrite.
4. Click **Save**.
## Export query [#export-query]
To export a query and its results, click **More** in the top bar to access the following options:
* **Add to dashboard** lets you create dashboard elements based on the query and add them to a dashboard. For more information, see [Create dashboard elements](/dashboard-elements/create).
* **Create new monitor** lets you create a monitor based on the query. For more information, see [Monitors](/monitor-data/monitors).
* **Copy results** lets you copy the query results to your clipboard in JSON, CSV, TOON (structured), or TOON (list) format. TOON is a structured data format that's more efficient when sharing data with LLMs and other tools. Choose TOON (structured) for hierarchical data or TOON (list) for flat representations. For more information, see the [TOON documentation](https://github.com/toon-format/toon).
* **Download results** lets you download the query results in JSON, CSV, TOON (structured), or TOON (list) format.
* **Copy link with relative time** copies a link to the query where the time range is relative to the time when you open the link. For example, if the time range of the query is the last 30 minutes, using the link shows query results for the 30-minute time range before opening the link.
* **Copy link with absolute time** copies a link to the query where the time range is fixed to the same time range that you see in the query when you create the link. This link shows query results for the same time range, irrespective of when you open the link.
---
# Stream data with Axiom
Source: https://axiom.co/docs/query-data/stream
The Stream tab allows you to inspect individual events and watch as they’re ingested live.
It can be incredibly useful to be able to live-stream events as they’re ingested to know what’s going on in the context of the entire system. Like a supercharged terminal, the Stream tab in Axiom allows you to view streams of events, filter them to only see important information, and finally inspect each individual event.
This section introduces the Stream tab and its components that unlock powerful insights from your data.
## Choose a dataset [#choose-a-dataset]
The default view is one where you can easily see which datasets are available and also see some recent saved queries in case you want to jump directly into a stream:
Select a dataset from the list of datasets to continue.
## Event stream [#event-stream]
Upon selecting a dataset, you are immediately taken to the live event stream for that dataset:
You can click an event to be taken to the event details slide-out:
On this slide-out, you can copy individual field values, or copy the entire event as JSON.
You can view and copy the raw data:
## Filter data [#filter-data]
The Stream tab provides access to a powerful filter builder right on the toolbar:
For more information, see the [filters documentation](/dashboard-elements/create#filters).
## Time range selection [#time-range-selection]
The stream has two time modes:
* Live stream (default)
* Time range
Live stream continuously checks for new events and presents them in the stream.
Time range only shows events that fall between a specific start and end date. This can be useful when investigating an issue. The time range menu has some options to quickly choose some time ranges, or you can input a specific range for your search.
When you are ready to return to live streaming, click this button:
Click the button again to pause the stream.
## View settings [#view-settings]
The Stream tab is customizable via the view settings menu:
Options include:
* Wrap lines
* Highlight severity (this is automatically extracted from the event)
* Show the raw event details
* Fields to display in their own column
## Saved queries [#saved-queries]
The saved queries slide-out is activated via the toolbar:
For more information, see [Saved queries](/query-data/datasets#saved-queries).
## Highlight severity [#highlight-severity]
Stream highlights log levels in different colors. For supported fields and detection rules, see [Requirements for log level fields](/reference/limits#requirements-for-log-level-fields).
To turn on highlighting, click in the top right of Stream, and then select **Highlight severity**.
Hover over a severity marker to see the field and value that determined the level. In the event details, click the level badge to highlight the source field.
---
# Explore traces
Source: https://axiom.co/docs/query-data/traces
Distributed tracing in Axiom allows you to observe how requests propagate through your distributed systems. This could involve a user request going through several microservices, and resources until the requested information is retrieved and returned. By tracing these requests, you’re able to understand the interactions between these microservices, pinpoint issues, understand latency, and trace the life of the request through your app’s architecture.
### Traces and spans [#traces-and-spans]
A trace is a representation of a single operation or transaction as it moves through a system. A trace is made up of multiple spans.
A span represents a logical unit of work in the system with a start and end time. For example, an HTTP request handling process might be a span. Each span includes metadata like unique identifiers (`trace_id` and `span_id`), start and end times, parent-child relationships with other spans, and optional events, logs, or other details to help describe the span’s operation.
### Trace schema overview [#trace-schema-overview]
| Field | Type | Description |
| ---------------- | -------- | -------------------------------------------------------- |
| `trace_id` | String | Unique identifier for a trace |
| `span_id` | String | Unique identifier for a span within a trace |
| `parent_span_id` | String | Identifier of the parent span |
| `name` | String | Name of the span for example, the operation |
| `kind` | String | Type of the span (for example, client, server, producer) |
| `duration` | Timespan | Duration of the span |
| `error` | Boolean | Whether this span contains an error |
| `status.code` | String | Status of the span (for example, null, OK, error) |
| `status.message` | String | Status message of the span |
| `attributes` | Object | Key-value pairs providing additional metadata |
| `events` | Array | Timestamped events associated with the span |
| `links` | Array | Links to related spans or external resources |
| `resource` | Object | Information about the source of the span |
This guide explains how you can use Axiom to analyze and interrogate your trace data from simple overviews to complex queries.
## Browse traces with the OpenTelemetry app [#browse-traces-with-the-opentelemetry-app]
The Axiom OpenTelemetry app automatically detects any OpenTelemetry trace data flowing into your datasets and publishes an OpenTelemetry Traces dashboard to help you browse your trace data.
The following fields are expected to display the OpenTelemetry Traces dashboard: `duration`, `kind`, `name`, `parent_span_id`, `service.name`, `span_id`, and `trace_id`.
### Navigate the app [#navigate-the-app]
* Use the **Filter Bar** at the top of the app to narrow the charts to a specific service or operation.
* Use the **Search Input** to find a trace ID in the selected time period.
* Use the **Slowest Operations** chart to identify performance issues across services and traces.
* Use the **Top Errors** list to quickly identify the worst-offending causes of errors.
* Use the **Results** table to get an overview and navigate between services, operations, and traces.
### View a trace [#view-a-trace]
Click a trace ID in the results table to show the waterfall view. This view allows you to see that span in the context of the entire trace from start to finish.
### Customize the app [#customize-the-app]
To customize the app, use the fork button to create an editable duplicate for you and your team.
## Query traces [#query-traces]
In Axiom, trace events are just like any other events inside datasets. This means they’re directly queryable in the UI. While this is can be a powerful experience, it’s important to note some important details to consider before querying:
* Directly aggregating upon the `duration` field produces aggregate values across every span in the dataset. This is usually not the desired outcome when you want to inspect a service’s performance or robustness.
* For request, rate, and duration aggregations, it’s best to only include the root span using `isnull(parent_span_id)`.
## Waterfall view of traces [#waterfall-view-of-traces]
To see how spans in a trace are related to each other, explore the trace in a waterfall view. In this view, each span in the trace is correlated with its parent and child spans.
### Traces in OpenTelemetry Traces dashboard [#traces-in-opentelemetry-traces-dashboard]
To explore spans within a trace using the OpenTelemetry Traces app, follow these steps:
1. Click the `Dashboards` tab.
2. Click `OpenTelemetry Traces`.
3. In the `Slowest Operations` chart, click the service that contains the trace.
4. In the list of trace IDs, click the trace you want to explore.
5. Explore how spans within the trace are related to each other in the waterfall view. To reveal additional options such as collapsing and expanding child spans, right-click a span.
To try out this example, go to the Axiom Playground.
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/dashboards/otel.traces.otel-demo-traces)
### Traces in Query tab [#traces-in-query-tab]
To access the waterfall view from the Query tab, follow these steps:
1. Ensure the dataset you work with has trace data.
2. Click the Query tab.
3. Run a query that returns the `_time` and `trace_id` fields. For example, the following query returns the number of spans in each trace:
```kusto
['otel-demo-traces']
| summarize count() by trace_id
```
4. In the list of trace IDs, click the trace you want to explore. To reveal additional options such as copying the trace ID, right-click a trace.
5. Explore how spans within the trace are related to each other in the waterfall view. To reveal additional options such as collapsing and expanding child spans, right-click a span. Event names are displayed on the timeline for each span.
To try out this example, go to the Axiom Playground.
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%5Cn%7C%20summarize%20count\(\)%20by%20trace_id%22%7D)
### Customize waterfall view [#customize-waterfall-view]
To toggle the display of the span details on the right, click **Span details**.
To resize the width of the waterfall view and the span details panel, drag the border.
### Span duration histogram [#span-duration-histogram]
In the waterfall view of traces, Axiom warns you about slow and fast spans. These spans are outliers because they’re at least a standard deviation over or under the average duration of spans that have the same span name and service name. Hold the pointer over the **SLOW** or **FAST** label to see additional information about the span type such as average and maximum duration. In addition, Axiom displays a histogram about the durations of spans that have the same span name and service name as the span you selected. By default, the histogram shows a one-hour window around the selected span.
The span duration histogram can be useful in the following cases, among others:
* You look at a span and you’re not familiar with the typical behavior of the service that created it. You want to know if you look at something normal in terms of duration or an outlier. The histogram helps you determine if you look at an outlier and might drill down further.
* You’ve found an outlier. You want to investigate and look at other outliers. The histogram shows you what the baseline is and what’s not normal in terms of duration. You want to filter for the outliers and see what they have in common.
* You want to see if there was a recent change in the typical duration for the selected span type.
To narrow the time range of the histogram, click and select an area in the histogram.
## Example queries [#example-queries]
Below are a collection of queries that can help get you started with traces inside Axiom. Queries are all executable on the [Axiom Play sandbox](https://axiom.co/play).
Number of requests, average response
```kusto
['otel-demo-traces']
| where isnull(parent_span_id)
| summarize count(),
avg(duration),
percentiles_array(duration, 95, 99, 99.9)
by bin_auto(_time)
```
Top five slowest services by operation
```kusto
['otel-demo-traces']
| summarize count(), avg(duration) by name
| sort by avg_duration desc
| limit 5
```
Top five errors per service and operation
```kusto
['otel-demo-traces']
| summarize topk(['status.message'], 5) by ['service.name'], name
| limit 5
```
## Semantic conventions [#semantic-conventions]
[OpenTelemetry semantic conventions](https://opentelemetry.io/docs/specs/semconv/) specify standard attribute names and values for different kinds of operations and data. For more information on Axiom’s support for OTel semantic conventions and what it means for your data, see [Semantic conventions](/reference/semantic-conventions).
## Span links [#span-links]
Span links allow you to associate one span with one or more other spans, establishing a relationship between them that indicates the operation of one span depends on the other. Span links can connect spans within the same trace or across different traces.
Span links are useful for representing asynchronous operations or batch-processing scenarios. For example, an initial operation triggers a subsequent operation, but the subsequent operation may start at some unknown later time or even in a different trace. By linking the spans, you can capture and preserve the relationship between these operations, even if they’re not directly connected in the same trace.
### How it works [#how-it-works]
Span links in Axiom are based on the [OpenTelemetry specification](https://opentelemetry.io/docs/concepts/signals/traces/#span-links). When instrumenting your code, you create span links using the OpenTelemetry API by passing the `SpanContext` (containing `trace_id` and `span_id`) of the span to which to link. Links are specified when starting a new span by providing them in the span configuration. The OpenTelemetry SDK includes the link information when exporting spans to Axiom. Links are recorded at span creation time so that sampling decisions can consider them.
### View span links [#view-span-links]
1. Run the following APL query to find traces with span links, for example:
```kusto
['dataset']
| where isnotempty(links)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%20%22%5B%27otel-demo-traces%27%5D%5Cn%7C%20where%20isnotempty%28links%29%22%7D)
2. Click on a trace in the results and select the `trace_id`.
3. In the trace details view, find the links section. This displays the `trace_id` and `span_id` associated with each linked span, as well as other attributes of the link.
4. Click **View span** to navigate to a linked span, either in the same trace or a different trace.
---
# Views
Source: https://axiom.co/docs/query-data/views
Views allow you to apply commonly used filters and transformations to your dataset. The result is a view that you can use like you use datasets:
* You can reference views in queries, dashboards, and monitors in the same way you reference datasets. For example, you can create queries that look for data in a view and you can use this query to [visualize data](/query-data/explore) in the Query tab, create a [dashboard element](/dashboard-elements/create), or set up a [monitor](/monitor-data/monitors).
* You can share and control access to views in the same way you do with datasets using role-based access control (RBAC). For example, views allow you to grant other users scoped access to your datasets. This means that instead of sharing the whole dataset with other users, you have the option to share only a filtered and transformed representation of the data. You define a view using a query that applies filters and transformations to your dataset, and then you only share the results of this query with another user.
Contrary to datasets:
* You can’t ingest directly to a view.
* You can’t trim or delete data from a view.
* You can’t create a view from another view.
The concept of a view in Axiom is similar to the concept of a virtual table in a database.
Views aren't currently supported for metrics datasets.
### Create view [#create-view]
1. Select a dataset.
2. In the top right of the **Views** section, click **+ Create view**.
3. Create the query using [Builder](/query-data/explore) or [Editor](/query-data/query-editor).
4. Below the query, check the preview of the events and the fields that your query returns.
5. Name the view and optionally add a description.
6. Click **Create view**.
### Display view [#display-view]
1. Select a dataset.
2. In the **Views** section on the right, click the view you want to display.
### Grant access to view [#grant-access-to-view]
All views are available to users with organization-level read access to views. You can allow users without these permissions to access an individual view in the same way you grant access to individual datasets:
1. Click **Settings > Roles**.
2. Click the role with which you want to share the view or create a new role.
3. In the **Individual datasets** section, click **Add dataset**.
4. Start typing the name of the view. In the list, find the view that you want to share, and then click **Add**.
It’s enough to grant access to the view. You don’t need to grant access to the underlying dataset.
5. Click **Save**.
---
# Virtual fields
Source: https://axiom.co/docs/query-data/virtual-fields
Virtual fields allow you to derive new values from your data in real time. They eliminate the need for up-front planning of how to structure or transform your data. Instead, send your data as-is and then use virtual fields to manipulate your data in real-time during queries. The feature is also known as derived fields, but Axiom’s virtual fields have some unique properties that make them much more powerful.
Virtual fields are query-time representations only. They don't create new data in storage.
Virtual fields aren't currently supported for metrics datasets.
## Creating a virtual field [#creating-a-virtual-field]
To create a virtual field, follow these steps:
1. Go to the Datasets tab.
2. Select the dataset where you want to create the virtual field.
3. Click **Virtual fields** in the top right. You see a list of all the virtual fields for the dataset.
4. Click **Add virtual field**.
5. Fill in the following fields:
* **Name** and **Description** help your team understand what the virtual field is about.
* **Expression** is the formula applied to every event to calculate the virtual field. The expression produces a result such as a `boolean`, `string`, `number`, or `object`.
The **Preview** section displays the result of applying the expression to some of your data. Use this section to verify the expression and the resulting values of the virtual field.
The power of virtual fields is in letting you manipulate data on read instead of on write, allowing you to adjust and update virtual fields over time as well as easily add new ones without worrying that the data has already been indexed.
## Usage [#usage]
### Visualizations [#visualizations]
Virtual fields are available as parameters to visualizations but, as the type of a virtual field can be any of the supported types, it’s important to make sure that you use a virtual field that produces the correct type of argument.
### Filters [#filters]
Virtual fields are available in the filter menu and all filter options are presented. It’s important to ensure that you are using a supported filter operation for the type of result your virtual field produces.
## Group By [#group-by]
Virtual fields can be used for segmentation in the same way as any standard field.
## Virtual fields vs ingest-time parsing [#virtual-fields-vs-ingest-time-parsing]
When deciding how to structure your data, consider the trade-offs between using virtual fields (query-time parsing) and parsing fields at ingest time.
### When to use virtual fields [#when-to-use-virtual-fields]
Virtual fields are ideal when:
* You need flexibility to experiment with different data transformations.
* Your query patterns are still evolving and you're not sure which fields you'll need.
* You want to derive new fields without re-ingesting historical data.
* The fields are used infrequently or for ad-hoc analysis.
### When to parse at ingest time [#when-to-parse-at-ingest-time]
For high-performance use cases, parsing fields at ingest time is often the better choice:
* **Query performance**: Virtual fields re-parse data on every query execution. For frequently queried fields, especially during incident response when teams run many ad-hoc queries, this adds latency. Parsed fields at ingest time reduce your storage and query hours usage. For more information, see [Virtual fields for simple transformations](/reference/performance#virtual-fields-for-simple-transformations).
* **Compression benefits**: When you parse fields from a JSON body to top-level fields, Axiom uses specialized data-aware compression techniques based on the detected data types. This results in more efficient storage compared to keeping data as unparsed strings. For more information, see [Overusing runtime JSON parsing](/reference/performance#overusing-runtime-json-parsing-parse_json).
### Storage considerations [#storage-considerations]
Parsing fields from a body to top-level attributes doesn't double your storage usage. Axiom's compression is optimized for typed, structured data at the top level, and stores parsed fields efficiently. However, there is some data redundancy if you keep the original body field alongside the parsed fields. To minimize redundancy, remove the parsed fields from the body after extraction during your ingest pipeline.
For a balance between flexibility and performance, parse your most frequently queried fields at ingest time while using virtual fields for less common or experimental transformations.
## Reference [#reference]
Virtual fields are APL expressions and share all the same functions and syntax as APL expressions. For more information, see [Introduction to APL](/apl/introduction).
The list of APL scalar functions:
* [String functions](/apl/scalar-functions/string-functions)
* [Math functions](/apl/scalar-functions/mathematical-functions)
* [Array functions](/apl/scalar-functions/array-functions)
* [Conversion functions](/apl/scalar-functions/conversion-functions)
* [Hash functions](/apl/scalar-functions/hash-functions)
* [DateTime/Timespan functions](/apl/scalar-functions/datetime-functions)
* [Rounding functions](/apl/scalar-functions/rounding-functions)
* [Conditional functions](/apl/scalar-functions/conditional-function)
* [IP functions](/apl/scalar-functions/ip-functions)
Virtual fields may reference other virtual fields. The order of the fields is important. Ensure that the referenced field is specified before the field that references it.
{/*
### Literals
| Functions | Description |
| ------------- | --------------------------------------- |
| `strings` | single and double quotes are supported. |
| `numbers` | `101`, `101.1` |
| `booleans` | `true` and `false` |
| `arrays` | `["one", "two", "three"]` |
| `maps` | `{ region: "us-east-1" }` |
| `nil` - | `nil` |
### Arithmetic operators
| Operator | Description |
| ------------ | --------------- |
| `+` | addition |
| `-` | subtraction |
| `*` | multiplication |
| `/` | division |
| `%` | modulus |
| `**` | pow |
### Comparison operators
| Operator | Description |
| ------------ | ------------------------ |
| `==` | equal |
| `!=` | not equal |
| `<` | less than |
| `>` | greater than |
| `<=` | less than or equal to |
| `>=` | greater than or equal to |
### Logical operators
| Operator |
| -------------------------------------- |
| `and` or `&&` |
| `or` or ` |
| `not` or `!` |
| `success ? 'yes' : 'no'` - ternary |
### String operators
| Operator | Description |
| ------------ | --------------- |
| `+` | concatenation |
| `matches` | regular expression match |
| `contains` | string contains |
| `startsWith` | has prefix |
| `endsWith` | has suffix |
To test the negative case of not matching, wrap the operator in a `not()` operator:
`not ("us-east-1" contains "us")`
Use parenthesis because the operator `not` has precedence over the operator `contains`.
### Numeric operators
In addition to the [arithmetic operators](#arithmetic-operators):
- `..` - numeric range
`age in 18..45`
The range is inclusive: `1..3 == [1, 2, 3]`
### Membership operators
| Operator | Description |
| ------------ | -------------------- |
| `in` | contains |
| `not in` | doesn’t contain |
Examples:
`{Arrays: metadata.region in ["us-east-1", "us-east-2"]}`
`{Maps: 'region' in { region: 'us-east-1 } // true}`
### Built-ins
| Operator | Description |
| ------------ | ---------------------------------------------------------------- |
| `len` | length of an array, map, or string |
| `all` | return true if all element satisfies the predicate |
| `none` | return true if all element doesn’t satisfies the predicate |
| `any` | return true if any element satisfies the predicate |
| `one` | return true if exactly ONE element satisfies the predicate |
| `filter` | filter array by the predicate |
| `map` | map all items with the closure |
| `count` | returns number of elements what satisfies the predicate |
{'all(comments, {.Size < 280})'}
{'one(repos, {.private})'}
### Closures
- `{...}` - closure
Closures allowed only with builtin functions. To access the current item, used the `#` symbol.
{'`map(0..9, {# / 2})`'}
If the item of array is struct, it’s possible to access fields of struct with omitted `#` symbol (`#.Value` becomes `.Value`).
{'filter(comments, {len(.body) > 280})'}
### Slices
- `myArray[:]` - slice
Slices can work with arrays or strings
The variable `myArray` is `[1, 2, 3, 4, 5]`
`myArray[1:5] == [2, 3, 4] myArray[3:] == [4, 5] myArray[:4] == [1, 2, 3] myArray[:] == myArray`
*/}
---
# Visualize
Source: https://axiom.co/docs/query-data/visualizations
Visualizations are powerful aggregations of your data to produce insights that are easy to understand and monitor. With visualizations, you can create and obtain data stats, group fields, and observe methods in running deployments.
This page introduces you to the visualizations supported by Axiom and some tips on how best to use them.
The visualizations explained on this page are only available for APL queries.
To visualize metrics data, see [MPL language features](/mpl/introduction).
## `count` [#count]
The `count` visualization counts all matching events and produces a time series chart.
#### Arguments [#arguments]
This visualization doesn’t take an argument.
#### Group-by behaviour [#group-by-behaviour]
The visualization produces a separate result for each group plotted on a time series chart.
## `distinct` [#distinct]
The `distinct` visualization counts each distinct occurrence of the distinct field inside the dataset and produce a time series chart.
#### Arguments [#arguments-1]
`field: any` is the field to aggregate.
#### Group-By Behaviour [#group-by-behaviour-1]
The visualization produces a separate result for each group plotted on a time series chart.
## `avg` [#avg]
The `avg` visualization averages the values of the field inside the dataset and produces a time series chart.
#### Arguments [#arguments-2]
`field: number` is the number field to average.
#### Group-by behaviour [#group-by-behaviour-2]
The visualization produces a separate result for each group plotted on a time series chart.
## `max` [#max]
The `max` visualization finds the maximum value of the field inside the dataset and produces a time series chart.
#### Arguments [#arguments-3]
`field: number` is the number field where Axiom finds the maximum value.
#### Group-by behaviour [#group-by-behaviour-3]
The visualization produces a separate result for each group plotted on a time series chart.
## `min` [#min]
The `min` visualization finds the minimum value of the field inside the dataset and produces a time series chart.
#### Arguments [#arguments-4]
`field: number` is the number field where Axiom finds the minimum value.
#### Group-by behaviour [#group-by-behaviour-4]
The visualization produces a separate result for each group plotted on a time series chart.
## `sum` [#sum]
The `sum` visualization adds all the values of the field inside the dataset and produces a time series chart.
#### Arguments [#arguments-5]
`field: number` is the number field where Axiom calculates the sum.
#### Group-by behaviour [#group-by-behaviour-5]
The visualization produces a separate result for each group plotted on a time series chart.
## `percentiles` [#percentiles]
The `percentiles` visualization calculates the requested percentiles of the field in the dataset and produces a time series chart.
#### Arguments [#arguments-6]
* `field: number` is the number field where Axiom calculates the percentiles.
* `percentiles: number [, ...]` is a list of percentiles , each a float between 0 and 100. For example, `percentiles(request_size, 95, 99, 99.9)`.
#### Group-by behaviour [#group-by-behaviour-6]
The visualization produces a separate result for each group plotted on a horizontal bar chart, allowing for visual comparison across the groups.
## `histogram` [#histogram]
The `histogram` visualization buckets the field into a distribution of N buckets, returning a time series heatmap chart.
#### Arguments [#arguments-7]
* `field: number` is the number field where Axiom calculates the distribution.
* `nBuckets` is the number of buckets to return. For example, `histogram(request_size, 15)`.
#### Group-by behaviour [#group-by-behaviour-7]
The visualization produces a separate result for each group plotted on a time series histogram. Hovering over a group in the totals table shows only the results for that group in the histogram.
## `topk` [#topk]
The `topk` visualization calculates the top values for a field in a dataset.
#### Arguments [#arguments-8]
* `field: number` is the number field where Axiom calculates the top values.
* `nResults` is the number of top values to return. For example, `topk(method, 10)`.
#### Group-by behaviour [#group-by-behaviour-8]
The visualization produces a separate result for each group plotted on a time series chart.
## `variance` [#variance]
The `variance` visualization calculates the variance of the field in the dataset and produces a time series chart.
The `variance` aggregation returns the sample variance of the fields of the dataset.
#### Arguments [#arguments-9]
`field: number` is the number field where Axiom calculates the variance.
#### Group-by behaviour [#group-by-behaviour-9]
The visualization produces a separate result for each group plotted on a time series chart.
## `stddev` [#stddev]
The `stddev` visualization calculates the standard deviation of the field in the dataset and produces a time series chart.
The `stddev` aggregation returns the sample standard deviation of the fields of the dataset.
#### Arguments [#arguments-10]
`field: number` is the number field where Axiom calculates the standard deviation.
#### Group-by behaviour [#group-by-behaviour-10]
The visualization produces a separate result for each group plotted on a time series chart.
---
# Track activity in Axiom
Source: https://axiom.co/docs/reference/audit-log
The audit log allows you to track who did what and when within your Axiom organization.
Tracking activity in your Axiom organization with the audit log is useful for legal compliance reasons. For example, you can investigate the following:
* Track who has accessed the Axiom platform.
* Track organization access over time.
* Track data access over time.
The audit log also make it easier to manage your Axiom organization. They allow you to do the following, among others:
* Track changes made by your team to your observability posture.
* Track monitoring performance and identify which monitors generate the most query load.
* Monitor query costs and optimize expensive queries before they impact your budget.
* Trace queries back to their source (monitors or direct queries) for debugging.
The audit log is available to all organizations. By default, you can query the audit log for the previous 30 days. You can purchase full access to the audit log as an add-on on the Axiom Cloud plan. For more information, see [Manage add-ons](/reference/usage-billing#manage-add-ons).
## Explore audit log [#explore-audit-log]
1. Go to the Query tab, and then click **APL**.
2. Query the `axiom-audit` dataset. For example, run the query `['axiom-audit']` to display the raw audit log data in a table.
3. Optional: Customize your query to filter or summarize the audit log. For more information, see [Query data](/query-data/explore).
4. Click **Run**.
The `action` field specifies the type of activity that happened in your Axiom organization.
## Export audit log [#export-audit-log]
1. Run the query to [display the audit log](#explore-audit-log).
2. Click **More > Download as JSON**.
## Give access to audit log [#give-access-to-audit-log]
The audit log is only accessible to users with the Owner role. To allow other users to access the audit log:
1. [Create a view](/query-data/views) that defines the parts of the audit log that you want the user to access.
2. [Give the user access](/reference/settings) to the view.
## Use cases and examples [#use-cases-and-examples]
The audit log captures rich context about queries run in your organization:
* **Query representation**: Privacy-safe representations of queries help you understand query patterns without exposing sensitive data.
* **Query source**: Track whether queries originated from monitors or direct queries.
* **Query cost**: Monitor resource consumption in query units for cost optimization.
* **Storage bytes scanned**: Understand data volumes processed by each query.
The examples below illustrate how the audit log can help you optimize performance, manage costs, and debug issues by tracing queries back to their origin.
### Monitor high-cost queries [#monitor-high-cost-queries]
Identify queries that consume significant resources:
```kusto
['axiom-audit']
| where action == 'runAPLQueryCost'
| where ['properties.query_cost_gbms'] > 1000
```
This query lists queries costing more than 1000 query units and helps you spot expensive queries and optimize them before they impact your budget.
[Create a threshold monitor](/monitor-data/threshold-monitors) using this query to receive alerts when expensive queries run. Adjust the `query_cost_gbms` threshold based on your organization’s usage patterns.
### Track monitor query load [#track-monitor-query-load]
Understanding which monitors generate the most query activity helps you optimize performance:
```kusto
['axiom-audit']
| where action == 'runAPLQueryCost'
| where source == 'monitor'
| summarize
total_queries = count(),
total_cost = sum(['properties.query_cost_gbms']),
avg_cost = avg(['properties.query_cost_gbms'])
by ['resource.id']
| sort by total_cost desc
```
Use this to identify monitors that might benefit from query optimization or frequency adjustments.
### Analyze dataset usage [#analyze-dataset-usage]
Find out which datasets are used the most:
```kusto
['axiom-audit']
| where action == 'runAPLQuery'
| where isnotnull(['properties.datasets'])
| summarize
query_count = count()
by ['properties.datasets'], bin(_time, 1d)
| sort by query_count desc
```
This query helps you understand how your team interacts with Axiom and identifies datasets that may need optimization.
### Track ingest by dataset [#track-ingest-by-dataset]
Track how much data each dataset ingests over time:
```kusto
['axiom-audit']
| where action == "usageCalculated"
| extend ingest_gb = tolong(['properties.hourlyIngestBytes']) / pow(1024, 3)
| summarize IngestGB = sum(ingest_gb) by bin_auto(_time), tostring(['properties.dataset'])
| sort by IngestGB desc
```
### Determine total data ingest [#determine-total-data-ingest]
Determine total data ingest across all datasets over time:
```kusto
['axiom-audit']
| where action == "usageCalculated"
| extend ingest_gb = tolong(['properties.hourlyIngestBytes']) / pow(1024, 3)
| summarize TotalIngestGB = sum(ingest_gb) by bin_auto(_time)
```
[Create a dashboard](/dashboards/overview) with these queries to continuously monitor your ingestion patterns.
[Create a threshold monitor](/monitor-data/threshold-monitors) to alert you when ingestion exceeds a threshold.
### Track query sources [#track-query-sources]
See the distribution of queries across different sources:
```kusto
['axiom-audit']
| where action == 'runAPLQuery'
| summarize query_count = count() by source
| sort by query_count desc
```
This helps you understand how your team interacts with Axiom and where queries originate.
## List of trackable actions [#list-of-trackable-actions]
The `action` field specifies the type of activity that happened in your Axiom organization. The actions that Audit logs allow you to track are the following:
* aplDelete
* createAnnotation
* createAPIToken
* createDashboard
* createDataset
* createEndpoint
* createFlowConfiguration
* createFlowDestination
* createFlowReplay
* createFlowStream
* createGroup
* createMapField
* createMonitor
* createNotifier
* createOrg
* createOrgStorage
* createPersonalToken
* createRole
* createUser
* createView
* createVirtualField
* deleteAnnotation
* deleteAPIToken
* deleteDashboard
* deleteDataset
* deleteDatasetFields
* deleteEndpoint
* deleteFlowConfiguration
* deleteFlowDestination
* deleteGroup
* deleteMapField
* deleteMonitor
* deleteNotifier
* deleteOrg
* deletePersonalToken
* deleteRepo
* deleteRole
* deleteSession
* deleteShareLink
* deleteView
* downgradeOrg
* downgradePlan
* fieldLimitApproached
* fieldLimitExceeded
* getDashboard
* getDatasetFields
* getField
* getSharedRepos
* logout
* logoutEverywhere
* messageSent
* notifierFailed
* notifierTriggered
* notifyCustomerIOIssues
* postRepos
* regenerateAPIToken
* regeneratePersonalToken
* removeRBAC
* removeUserFromOrg
* resolveMonitor
* resolveMonitorAll
* resumeFlowReplay
* resumeFlowStream
* rotateSharedAccessKeys
* runAPLQuery
* sendOrgDeletedEmails
* sendOrgMonthlyIngestedExceededEmail
* sendOrgMonthlyIngestedNearLimitEmail
* sendUserDeletedEmail
* sendWelcomeEmail
* setEnableAI
* shareRepo
* stopFlowReplay
* stopFlowStream
* streamDataset
* triggerNotifier
* triggerNotifierWithID
* trimDataset
* unShareRepo
* updateDashboard
* updateDataset
* updateDatasetSettings
* updateEndpoint
* updateField
* updateFlowConfiguration
* updateFlowDestination
* updateGroup
* updateMapFields
* updateMonitor
* updateNotifier
* updateOrg
* updatePersonalToken
* updateRepo
* updateRole
* updateUser
* updateUserSettings
* updateView
* updateVirtualField
* upgradeOrg
* upgradePlan
* usageCalculated
* useShareLink
* vacuumDataset
---
# Axiom CLI
Source: https://axiom.co/docs/reference/cli
Axiom’s command line interface (CLI) is an Axiom tool that lets you test, manage, and build your Axiom organizations by typing commands on the command-line.
You can use the command line to ingest data, manage authentication state, and configure multiple organizations.
## Installation [#installation]
### Install using go install [#install-using-go-install]
To install Axiom CLI, make sure you have [Go](https://golang.org/dl/) installed, then run this command from any directory in your terminal.
```bash
go install github.com/axiomhq/cli/cmd/axiom@latest
```
### Install using Homebrew [#install-using-homebrew]
You can also install the CLI using [Homebrew](https://brew.sh/)
```bash
brew install --cask axiomhq/tap/axiom
```
This installs Axiom command globally so you can run `axiom` commands from any directory.
To update:
```bash
brew upgrade --cask axiom
```
### Install from source [#install-from-source]
```bash
git clone https://github.com/axiomhq/cli.git
cd cli
make install # Build and install binary into $GOPATH
```
### Run the Docker image [#run-the-docker-image]
Docker images are available on [DockerHub.](https://hub.docker.com/r/axiomhq/cli)
```bash
docker pull axiomhq/cli
docker run axiomhq/cli
```
You can check the version and find out basic commands about Axiom CLI by running the following command:
```bash
axiom
```
## Authentication [#authentication]
The recommended way to authenticate Axiom CLI is with a personal access token. A personal access token starts with `xapt-` and lets you do everything you can do in the Axiom Console, including querying and streaming data.
1. In the Axiom Console, go to **Settings → Profile → Personal Tokens** and create a token. Copy the token value (it starts with `xapt-`).
2. Log in with the token. Use one of the following methods.
Interactive login (you’re prompted for your token and organization ID):
```bash
axiom auth login --auto-login=false
```
Non-interactive login (useful for scripts and CI). When you pipe the token, both `--alias` (a local name for the deployment) and `--org-id` are required:
```bash
echo "xapt-your-token" | axiom auth login --alias "axiom" --org-id "your-org-id" -f
```
Alternatively, skip `axiom auth login` entirely and set environment variables. `AXIOM_ORG_ID` is optional with a personal access token—the token resolves to your default organization, so set it only when your account belongs to more than one organization and you want to target a specific one:
```bash
export AXIOM_TOKEN="xapt-your-token"
export AXIOM_URL="https://api.axiom.co"
export AXIOM_ORG_ID="your-org-id" # optional; only needed to target a specific organization
```
To confirm you’re authenticated, run `axiom dataset list`.
Running `axiom auth login` without `--auto-login=false` starts a browser-based login flow. This flow is currently affected by a known issue: after you authorize the application, the login can fail with an OAuth error (`oauth2: "invalid_request"`). Until this is resolved, use the personal access token method described above.
For more information about tokens, see [Tokens](/reference/tokens).
## Managing multiple organizations [#managing-multiple-organizations]
While most users will only need to manage a single Axiom deployment, Axiom CLI provides the capability to switch between multiple organizations for those who require it. You can easily switch between organizations using straightforward CLI commands. For example, `axiom auth switch-org` lets you change your active organization, or you can set the `AXIOM_ORG_ID` environment variable for the same purpose.
Every setting in Axiom CLI can be overwritten via environment variables configured in the `~/.axiom.toml` file. Specifically, `AXIOM_URL`, `AXIOM_TOKEN`, and `AXIOM_ORG_ID` are important for configuring your environment. Set `AXIOM_URL` to your Axiom domain. For more information, see [Edge deployments](/reference/edge-deployments). You can switch between environments using the `axiom auth select` command.
To view available environment variables, run `axiom help environment` for an up to date list of env vars:
```
AXIOM_DEPLOYMENT: The deployment to use. Overwrites the choice loaded
from the configuration file.
AXIOM_ORG_ID: The organization ID of the organization the access
token is valid for.
AXIOM_PAGER, PAGER (in order of precedence): A terminal paging
program to send standard output to, for example, "less".
AXIOM_TOKEN: Token The access token to use. Overwrites the choice
loaded from the configuration file.
AXIOM_URL: The deployment url to use. Overwrites the choice loaded
from the configuration file.
VISUAL, EDITOR (in order of precedence): The editor to use for
authoring text.
NO_COLOR: Set to any value to avoid printing ANSI escape sequences
for color output.
CLICOLOR: Set to "0" to disable printing ANSI colors in output.
CLICOLOR_FORCE: Set to a value other than "0" to keep ANSI colors in
output even when the output is piped.
```
## One-Click Login [#one-click-login]
The One-Click Login is an easier way to authenticate Axiom-CLI and log in to your Axiom deployments and account resources directly on your terminal using the Axiom CLI.
## Tokens [#tokens]
You can generate an ingest and personal token manually in your Axiom user settings.
See [Tokens](/reference/tokens) to know more about managing access and authorization.
## Configuration and Deployment [#configuration-and-deployment]
Axiom CLI lets you ingest, authenticate, and stream data.
For more information about Configuration, managing authentication status, ingesting, streaming, and more,
visit the [Axiom CLI](https://github.com/axiomhq/cli) repository on GitHub.
Axiom CLI supports the ingestion of different formats of data **( JSON, NDJSON, and CSV)**
## Querying [#querying]
Get deeper insights into your data using [Axiom Processing Language](/apl/introduction)
## Ingestion [#ingestion]
Import, transfer, load, and process data for later use or storage using the Axiom CLI. With [Axiom CLI](https://github.com/axiomhq/cli) you can Ingest the contents of a **JSON, NDJSON, CSV** logfile into a dataset.
**To view a list of all the available commands run `axiom` on your terminal:**
```bash
➜ ~ axiom
The power of Axiom on the command-line.
USAGE
axiom [flags]
CORE COMMANDS
ingest: Ingest structured data
query: Query data using APL
stream: Livestream data
MANAGEMENT COMMANDS
auth: Manage authentication state
config: Manage configuration
dataset: Manage datasets
ADDITIONAL COMMANDS
completion: Generate shell completion scripts
help: Help about any command
version: Print version
web: Open Axiom in the browser
FLAGS
-O, --auth-org-id string Organization ID to use
-T, --auth-token string Token to use
-C, --config string Path to configuration file to use
-D, --deployment string Deployment to use
-h, --help Show help for command
--no-spinner Disable the activity indicator
-v, --version Show axiom version
EXAMPLES
$ axiom auth login
$ axiom version
$ cat http-logs.json | axiom ingest http-logs
AUTHENTICATION
See 'axiom help credentials' for help and guidance on authentication.
ENVIRONMENT VARIABLES
See 'axiom help environment' for the list of supported environment variables.
LEARN MORE
Use 'axiom --help' for more information about a command.
Read the manual at https://axiom.co/reference/cli
```
## Command Reference [#command-reference]
Below are the commonly used commands on Axiom CLI
**Core Commands**
| Commands | Description |
| ---------------- | -------------------- |
| **axiom ingest** | Ingest data |
| **axiom query** | Query data using APL |
| **axiom stream** | Live stream data |
**Management Commands**
| Commands | Description |
| --------------------------- | ----------------------------------------- |
| **axiom auth login** | Login to Axiom |
| **axiom auth logout** | Logout of Axiom |
| **axiom auth select** | Select an Axiom environment configuration |
| **axiom auth status** | View authentication status |
| **axiom auth switch-org** | Switch the organization |
| **axiom auth update-token** | Update the token used to authenticate |
| **axiom config edit** | Edit the configuration file |
| **axiom config get** | Get a configuration value |
| **axiom config set** | Set a configuration value |
| **axiom config export** | Export the configuration values |
| **axiom dataset create** | Create a dataset |
| **axiom dataset delete** | Delete a dataset |
| **axiom dataset list** | List all datasets |
| **axiom dataset trim** | Trim a dataset to a given size |
| **axiom dataset update** | Update a dataset |
**Additional Commands**
| Commands | Description |
| ------------------------------- | ----------------------------------------------- |
| **axiom completion bash** | Generate shell completion script for bash |
| **axiom completion fish** | Generate shell completion script for fish |
| **axiom completion powershell** | Generate shell completion script for powershell |
| **axiom completion zsh** | Generate shell completion script for zsh |
| **axiom help** | Help about any command |
| **axiom version** | Print version |
| **axiom web** | Open Axiom in the browser |
## Get help [#get-help]
To get usage tips and learn more about available commands from within Axiom CLI, run the following:
```bash
axiom help
```
For more information about a specific command, run `help` with the name of the command.
```bash
axiom help auth
```
This also works for sub-commands.
```bash
axiom help auth status
```
**if you have questions, or any opinions you can [start an issue](https://github.com/axiomhq/cli/issues) on Axiom CLI’s open source repository.**
**You can also visit the [Discord community](https://axiom.co/discord) to start or join a discussion. Axiom would love to hear from you.**
---
# Manage datasets
Source: https://axiom.co/docs/reference/datasets
This reference article explains how to manage datasets in Axiom, including creating new datasets, importing data, deleting fields, and deleting datasets.
## What datasets are [#what-datasets-are]
Axiom’s datastore is tuned for the efficient collection, storage, and analysis of timestamped event data. An individual piece of data is an event, and a dataset is a collection of related events. Datasets contain incoming event data.
## Best practices for organizing datasets [#best-practices-for-organizing-datasets]
Use datasets to organize your data ready for querying based on the event schema. Common ways to separate include environment, signal type, and service.
### Separate by environment [#separate-by-environment]
If you work with data sourced from different environments, separate them into different datasets. For example, use one dataset for events from production and another dataset for events from your development environment.
You might be tempted to use a single `environment` attribute instead, but this risks causing confusion when results show up side-by-side in query results. Although some organizations choose to collect events from all environments in one dataset, they’ll often rely on applying an `environment` filter to all queries, which becomes a chore and is error-prone for newcomers.
### Separate by signal type [#separate-by-signal-type]
If you work with distributed applications, consider splitting your data into different datasets. For example:
* A dataset with traces for all services
* A dataset with app logs for all services
* A dataset with frontend web vitals
* A dataset with infrastructure logs
* A dataset with security logs
* A dataset with CI logs
If you look for a specific event in a distributed system, you are likely to know its signal type but not the related service. By splitting data into different datasets using the approach above, you can find data easily.
### Separate by service [#separate-by-service]
Another common practice is to separate datasets by service. This approach allows for easier access control management.
For example, you might separate engineering services with datasets like `kubernetes`, `billing`, or `vpn`, or include events from your wider company collectors like `product-analytics`, `security-logs`, or `marketing-attribution`.
This separation enables teams to focus on their relevant data and simplifies querying within a specific domain. It also works well with Axiom’s role-based access control feature as you can restrict access to sensitive datasets to those who need it.
While separating by service is beneficial, avoid over-segmentation. Creating a dataset for every microservice or function can lead to unnecessary complexity and management overhead. Instead, group related services or functions into logical datasets that align with your organizational structure or major system components.
When you work with OpenTelemetry trace data, keep all spans of a given trace in the same dataset. To investigate spans for different services, don’t send them to different datasets. Instead, keep the spans in the same dataset and filter on the `service.name` field. For more information, see [Send OpenTelemetry data to Axiom](/send-data/opentelemetry).
### Avoid the “kitchen sink” [#avoid-the-kitchen-sink]
While it might seem convenient to send all events to a single dataset, this “kitchen sink” approach is generally not advisable for several reasons:
* Field count explosion: As you add more event types to a single dataset, the number of fields grows rapidly. This can make it harder to understand the structure of your data and impacts query performance.
* Query inefficiency: With a large, mixed dataset, queries often require multiple filters to isolate the relevant data. This is tedious, but without those filters, queries take longer to execute since they scan through more irrelevant data.
* Schema conflicts: Different event types may have conflicting field names or data types, leading to unnecessary type coercion at query time.
* Access management: With all data in one dataset, it becomes challenging to provide granular access controls. You might end up giving users access to more data than they need.
Don’t create multiple Axiom organizations to separate your data. For example, don’t use a different Axiom organization for each deployment. If you’re on the Axiom Cloud (Personal) plan, this might go against [Axiom’s fair use policy](https://axiom.co/terms). Instead, separate data by creating a different dataset for each deployment within the same Axiom organization.
## Limits on ingested data [#limits-on-ingested-data]
For more information on limits and requirements imposed by Axiom, see [Limits](/reference/limits).
## Create dataset [#create-dataset]
To create a dataset using Console, follow these steps:
1. Click **Settings > Datasets and views**.
2. Click **New dataset**.
3. Name the dataset and add an optional description.
4. In **Kind**, select one of the following:
* Select **Events** if you plan to use the dataset for logs or traces data.
* Select **Metrics** if you plan to send OTel metrics data to the dataset.
5. In **Data retention**, select for how long to store your data in this dataset. For more information, see [Specify data retention period](#specify-data-retention-period).
6. In **Edge deployment**, select the edge deployment you want to use for this dataset. You can select from the list of edge deployments you have added to the organization. For more information, see [Edge deployments](/reference/edge-deployments) and [Add edge deployments](/reference/usage-billing#manage-add-ons).
7. Click **Save dataset**.
To create a dataset using the Axiom API, send a POST request to the [datasets endpoint](/restapi/endpoints/createDataset).
Dataset names are 1 to 128 characters in length. They only contain ASCII alphanumeric characters and the hyphen (`-`) character.
## Import data [#import-data]
You can import data to your dataset in one of the following formats:
* Newline delimited JSON (NDJSON)
* Arrays of JSON objects
* CSV
To import data to a dataset, follow these steps:
1. Click **Settings > Datasets and views**.
2. In the list, find the dataset where you want to import data, and then click **Import** on the right.
3. Optional: Specify the timestamp field. This is only necessary if your data contains a timestamp field and it’s different from `_time`.
4. Upload the file, and then click **Import**.
## Trim dataset [#trim-dataset]
Trimming permanently deletes data stored in blocks that are older than a date you specify. Note that this action doesn’t delete data that’s older than the specified date but shares a block with newer data.
This can be useful if your dataset takes up too much storage space and you want to reduce its size to ensure you stay within the [allowed limits](/reference/limits#pricing-based-limits). If your dataset contains too many fields, [delete the fields](#delete-fields) you don’t need instead.
Trimming a dataset deletes all data blocks before the specified date.
Trimming is an asynchronous operation. When you submit a trim request, Axiom queues the deletion and processes it in the background. The trimmed data may take several hours to be fully removed from your dataset. During this time:
* The trim operation appears as successful in the [audit log](/reference/audit-log).
* Query results may still include data that's queued for deletion.
* The storage usage displayed in your settings may not immediately reflect the reduction.
To trim a dataset, follow these steps:
1. Click **Settings > Datasets and views**.
2. In the list, find the dataset that you want to trim, and then click **Trim dataset** on the right.
3. Specify the date before which you want to delete blocks of data.
4. Enter the name of the dataset, and then click **Trim**.
## Vacuum fields [#vacuum-fields]
The data schema of your dataset is defined on read. Axiom continuously creates and updates the data structures during the data ingestion process. At the same time, Axiom only retains data for the [retention period you specify](#specify-data-retention-period). This means that the data schema can contain fields that you ingested into the dataset in the past, but these fields are no longer present in the data currently associated with the dataset. This can be an issue if the number of fields in the dataset exceeds the [allowed limits](/reference/limits#pricing-based-limits).
In this case, vacuuming fields in a dataset can help you reduce the number of fields associated with a dataset and stay within the allowed limits. Vacuuming fields resets the number of fields associated with a dataset to the fields that occur in events within your retention period. Technically, it wipes the data schema and rebuilds it from the data you currently have in the dataset, which is partly defined by the retention period. For example, you have ingested 500 fields over the last year and 50 fields in the last 95 days, which is your retention period. In this case, before vacuuming, your data schema contains 500 fields. After vacuuming, the dataset only contains 50 fields.
Vacuuming fields doesn’t delete any events from your dataset. To delete events, [trim the dataset](#trim-dataset). Vacuuming only removes fields that no longer occur in any event within your retention period. If you accidentally ingested events with fields you didn’t want to send to Axiom, and these events are within your retention period, vacuuming alone doesn’t solve your problem. In this case, [delete the unintended fields](#delete-fields) instead. Deleting fields also vacuums the dataset.
You can vacuum the fields of a dataset whose schema is locked. In this case, Axiom vacuums the fields and then regenerates the locked schema so that it matches the vacuumed fields. For more information, see [Lock dataset schema](#lock-dataset-schema).
You can only vacuum fields once per day for each dataset.
To vacuum fields, follow these steps:
1. Click **Settings > Datasets and views**.
2. In the list, find the dataset where you want to vacuum fields, and then click **Vacuum fields** on the right.
3. Select the checkbox, and then click **Vacuum**.
## Delete fields [#delete-fields]
Deleting fields removes specific fields from the data schema of an event dataset. This is useful if you accidentally ingested fields you don’t want in Axiom, or if the number of fields in the dataset approaches the [allowed limits](/reference/limits#pricing-based-limits) and you want to remove the fields you don’t need.
Deleting fields differs from the other ways of reducing the number of fields:
* [Vacuuming fields](#vacuum-fields) only removes fields that no longer occur in any event within your retention period. Deleting fields removes the fields you select, even if events within your retention period contain them. Deleting fields also vacuums the dataset, so fields that vacuuming would remove are removed as well.
* [Trimming a dataset](#trim-dataset) deletes events. Deleting fields doesn’t delete any events. All other fields of the events remain queryable.
Deleting fields can’t be undone. After deletion, you can’t query the values of the deleted fields in events you ingested before the deletion.
Deleting fields works in the following way:
* Axiom removes the deleted fields from the schema, the list of fields in the Datasets tab, and query autocomplete. Field descriptions, units, and hidden settings for the deleted fields are removed as well.
* The values of the deleted fields stay in storage but you can’t access them anymore. Deleting fields doesn’t reduce the storage usage of your dataset.
* As the last step of the deletion, Axiom vacuums the fields of the dataset. This rebuilds the data schema from the events currently in the dataset, so fields that no longer occur in any event within your retention period disappear together with the fields you selected. For more information, see [Vacuum fields](#vacuum-fields).
* After the deletion completes, saved queries, dashboards, monitors, and virtual fields that reference a deleted field return an error. Review these before you delete fields.
* Deleting fields doesn’t prevent Axiom from adding the fields again. If you ingest events that contain a deleted field after the deletion, Axiom adds the field to the schema again and you can query the newly ingested values. The values you ingested before the deletion remain inaccessible. To stop a field from coming back, fix the data source before you delete the field, or [lock the schema](#lock-dataset-schema) after the deletion completes. If Axiom keeps receiving the field while the deletion runs, the field might remain in the dataset after the deletion finishes.
* Field deletion is an asynchronous operation. When you submit a request, Axiom queues the deletion and processes it in the background. The deletion can take several hours to complete, depending on the size of the dataset. During this time, the fields still appear in the Fields panel, and queries might return the values of the deleted fields for some events but not for others. The request appears as `deleteDatasetFields` in the [audit log](/reference/audit-log).
- You can delete fields from event datasets only. Metrics datasets don’t support deleting fields.
- To delete fields, you need the same permissions as for [vacuuming fields](/reference/settings#assign-capabilities-to-roles). Without these permissions, Axiom doesn’t display the menu option below.
- You can delete fields from a dataset once every 5 minutes. If a field deletion started on the dataset less than 5 minutes ago, wait and try again.
- You can’t delete fields while the schema of the dataset is locked. [Unlock the schema](#lock-dataset-schema) first, delete the fields, and then lock the schema again after the deletion completes.
- You can’t delete fields from a dataset that another organization has shared with your organization.
- You can’t delete fields from datasets that Axiom manages, such as `axiom-audit`.
- You can’t delete the fields that Axiom creates automatically, such as `_time` and `_sysTime`.
- You can’t delete a field that’s configured as a [map field](/apl/data-types/map-fields). To delete it, first remove the map field configuration, and then delete the field.
- Virtual fields don’t store data. To delete a virtual field, see [Virtual fields](/query-data/virtual-fields).
To delete fields, follow these steps:
1. Go to the Datasets tab.
2. In the list, select the dataset from which you want to delete fields.
3. In the **Fields** panel, click **More > Delete fields**.
4. Enter a pattern that matches the names of the fields you want to delete, and then click **Find fields**. Axiom lists all fields whose name contains the pattern. The pattern is case-insensitive. Leave the pattern empty to list all fields.
5. If you entered a pattern, Axiom selects all matching fields that you can delete. If you left the pattern empty, Axiom doesn’t select any fields. Select the fields you want to delete and clear the ones you want to keep. Use **Check all** and **Uncheck all** to change the selection of all matching fields. Fields you can’t delete appear greyed out with an explanation.
6. Click **Delete *N* fields**, where *N* is the number of fields you selected.
7. Review the list of fields, and then click **Delete *N* fields** to confirm.
Axiom displays a message that the deletion started. The deleted fields disappear from the Fields panel when the deletion completes.
To delete fields using the Axiom API, send a POST request to the [delete fields endpoint](/restapi/endpoints/deleteDatasetFields) with the list of field names in the request body. To delete a single field, send a DELETE request to the [delete field endpoint](/restapi/endpoints/deleteFieldForDataset). Both endpoints return the status code 202 when the deletion is queued, and the status code 429 with a `Retry-After` header if a field deletion started on the dataset in the last 5 minutes.
The API doesn’t match field names by pattern. Specify each field name exactly as it appears in the schema of the dataset. To get the field names, use the [list fields endpoint](/restapi/endpoints/getFieldsForDataset). If any field in the request doesn’t exist in the dataset, is a system field, or is a map field, Axiom rejects the whole request with the status code 400 and doesn’t delete any fields. If the field in a DELETE request doesn’t exist in the dataset, the delete field endpoint returns the status code 404.
## Lock dataset schema [#lock-dataset-schema]
By default, the data schema of a dataset grows together with your data. When you ingest an event with a field that isn’t yet part of the data schema, Axiom adds the new field to the schema. Similarly, when you ingest an event where the value of an existing field has a new type, Axiom extends the field’s type to support both the existing and the new type.
Locking the schema of a dataset freezes its set of fields and the type of each field. While the schema is locked, Axiom discards the following during the data ingestion process:
* Fields that aren’t part of the locked schema.
* Field values whose type doesn’t match the type of the field in the locked schema and can’t be promoted to that type. For example, if the locked schema defines a field as a number and you ingest an event where the field contains a string, Axiom drops the field’s value from that event. Axiom keeps values that it can promote to the locked type. For example, if the locked type of a field is float, Axiom accepts integer values in that field. Null values never violate a locked schema.
Axiom still ingests the events themselves and only drops the fields that don’t match the locked schema. When Axiom drops a field, the response to the ingest request contains a warning message that identifies the field and the reason. For example:
```json
"messages": [
{
"priority": "warn",
"code": "schema_rules_drop:debug",
"count": 1,
"msg": "field \"debug\" dropped: not in declared schema"
},
{
"priority": "warn",
"code": "schema_rules_drop:status",
"count": 1,
"msg": "field \"status\" dropped: type rule violated (allowed integer, saw string)"
}
]
```
Axiom calculates ingest usage based on the data as it arrives. Fields that Axiom discards because the schema is locked still count towards your ingest usage.
Locking the schema can be useful if you want to protect a dataset with a well-defined schema from unexpected fields, ensure that fields have consistent types, or keep the number of fields within the [allowed limits](/reference/limits#pricing-based-limits). To reduce the number of fields already associated with a dataset, [delete fields](#delete-fields) or [vacuum its fields](#vacuum-fields).
Locking and unlocking the schema take effect immediately and don’t change the data stored in the dataset. When you unlock the schema, Axiom restores the default behavior and adds new fields to the schema during the data ingestion process. Unlocking doesn’t restore fields or values that Axiom discarded while the schema was locked.
* You can only lock the schema of event datasets. Metrics datasets don’t support schema locking.
* To lock or unlock the schema, you need update permissions for datasets. Without these permissions, Axiom doesn’t display the menu options below.
* You can’t lock the schema of a dataset that another organization has shared with your organization.
* You can’t lock the schema of a dataset that you have set up through the [Cloudflare Logpush](/apps/cloudflare-logpush), [Vercel](/apps/vercel), or [Netlify](/apps/netlify) integration.
To lock the schema of a dataset, follow these steps:
1. Go to the Datasets tab.
2. In the list, select the dataset whose schema you want to lock.
3. In the **Fields** panel, click **More > Lock schema**.
Axiom displays a **Schema locked** message. While the schema is locked, the title of the Fields panel is **Fields (Locked)**.
To unlock the schema of a dataset, follow these steps:
1. Go to the Datasets tab.
2. In the list, select the dataset whose schema you want to unlock.
3. In the **Fields** panel, click **More > Unlock schema**.
Axiom displays a **Schema unlocked** message.
## Share datasets [#share-datasets]
You can share your datasets with other Axiom organizations. The receiving organization:
* can query the shared dataset.
* can create other Axiom resources that rely on query access such as dashboards and monitors.
* can’t ingest data into the shared dataset.
* can‘t modify the shared dataset.
No ingest usage associated with the shared dataset accrues to the receiving organization. Query usage associated with the shared dataset accrues to the organization running the query.
To share a dataset with another Axiom organization:
1. Ensure you have the necessary privileges to share datasets. By default, only users with the Owner role can share datasets.
2. Click **Settings > Datasets and views**.
3. In the list, find the dataset that you want to share, and then click **Share dataset** on the right.
4. In the Sharing links section, click **+** to create a new sharing link.
5. Copy the URL and share it with the receiving user in the organization with which you want to share the dataset. For example, `https://app.axiom.co/s/dataset/{sharing-token}`.
6. Ask the receiving user to open the sharing link. When opening the link, the receiving user sees the name of the dataset and the email address of the Axiom user that created the sharing link. They click **Add dataset** to confirm that they want to receive the shared dataset.
### Delete sharing link [#delete-sharing-link]
Organizations can gain access to the dataset with an active sharing link. To deactivate the sharing link, delete the sharing link. Deleting a sharing link means that organizations that don’t have access to the dataset can’t use the sharing link to join the dataset in the future. Deleting a sharing link doesn’t affect the access of organizations that already have access to the shared dataset.
To delete a sharing link:
1. Click **Settings > Datasets and views**.
2. In the list, find the dataset, and then click **Share dataset** on the right.
3. To the right of the sharing link, click **Delete**.
4. Click **Delete sharing link**.
### Remove access to shared dataset [#remove-access-to-shared-dataset]
If your organization has previously shared a dataset with a receiving organization, and you want to remove the receiving organization’s access to the dataset, follow these steps:
1. Click **Settings > Datasets and views**.
2. In the list, find the dataset, and then click **Share dataset** on the right.
3. In the list, find the organization whose access you want to remove, and then click **Remove**.
4. Click **Remove access**.
### Remove shared dataset [#remove-shared-dataset]
If your organization has previously received access to a dataset from a sending organization, and you want to remove the shared dataset from your organization, follow these steps:
1. Ensure you have Delete permissions for the shared dataset.
2. Click **Settings > Datasets and views**.
3. In the list, click the shared dataset that you want to remove, and then click **Remove dataset**.
4. Enter the name of the dataset, and then click **Remove**.
This procedure only removes the shared dataset from your organization. The underlying dataset in the sending organization isn’t affected.
## Specify data retention period [#specify-data-retention-period]
The data retention period determines how long Axiom stores your data. By default, the data retention period is the same for all datasets. You can configure custom retention periods for individual datasets. As a result, Axiom automatically trims data after the specified time period instead of the default period. For example, this can be useful if your dataset contains sensitive event data that you don’t want to retain for a long time.
The retention period of a dataset is set to **Default** unless you select a different value. Datasets set to **Default** follow your organization’s [default dataset retention period](/reference/organization-settings#set-default-dataset-retention-period). Changing the default therefore also changes the retention period of these datasets, and deletes data in them if you lower the default. When you select any other retention period for a dataset, the dataset uses that custom retention period and becomes independent of the default.
The custom retention period you can set for an individual dataset depends on your plan:
* On the Axiom Cloud plan, you can set any retention period, including a period that’s longer than your organization’s default, or **Forever**.
* On other plans, the custom retention period must be shorter than the default data retention period. For example, if you’re on the Personal plan, the default data retention period is 30 days and you can only specify a shorter period.
For more information, see [Pricing-based limits](/reference/limits#pricing-based-limits) and [Set default dataset retention period](/reference/organization-settings#set-default-dataset-retention-period).
When you specify a data retention period for a dataset that’s shorter than the previous setting, all data older than the new retention period is automatically deleted. This process can’t be undone.
The retention period determines how long Axiom stores your data, but not how far back you can query it. How far back you can query is limited by the maximum query window of your organization, which is determined by your plan. The maximum query window doesn’t change when you change the default dataset retention period or the retention period of individual datasets.
To change the data retention period for a dataset, follow these steps:
1. Click **Settings > Datasets and views**.
2. In the list, find the dataset for which you want to change the retention period, and then click **Edit dataset retention** on the right.
3. Select a retention period, or select **Custom** to enter your own retention period in days. To make the dataset follow your organization’s default dataset retention period, select **Default**.
4. Click **Submit**.
## Delete dataset [#delete-dataset]
Deleting a dataset deletes all data contained in the dataset.
To delete a dataset, follow these steps:
1. Click **Settings > Datasets and views**.
2. In the list, click the dataset that you want to delete, and then click **Delete dataset**.
3. Enter the name of the dataset, and then click **Delete**.
## Manage apps [#manage-apps]
Apps allow you to enrich your Axiom organization with dedicated apps. For more information, see [Introduction to apps](/apps/introduction).
### Edit app [#edit-app]
1. Click **Settings > Apps**.
2. Find the app in the list, and then click **More > Edit**.
### Disconnect app [#disconnect-app]
1. Click **Settings > Apps**.
2. Find the app in the list, and then click **More > Disconnect**.
---
# Edge deployments
Source: https://axiom.co/docs/reference/edge-deployments
Axiom is a unified data platform built on edge deployments.
When you create an organization, you choose a primary edge deployment like `US East 1 (AWS)`, and your event data is stored at rest in that infrastructure. You manage everything through Axiom’s Console at `app.axiom.co` regardless of which edge deployment you select.
This edge deployment model provides flexibility that isn’t possible with separate regional instances. Within a single organization, you can create datasets in different edge deployments while maintaining unified management and billing.
## Available edge deployments [#available-edge-deployments]
Axiom currently supports the following edge deployments:
The base domain of all other API endpoints is `api.axiom.co`.
Axiom prioritizes new edge deployments based on interest. [Contact Axiom](https://www.axiom.co/contact) to discuss your requirements.
## Current capabilities [#current-capabilities]
Your organization’s default edge deployment determines where Axiom stores event data at rest and where queries execute. When you run a query, both the execution and results remain within your selected edge deployment.
| Operation | Behavior |
| :------------------ | :----------------------- |
| **Data ingest** | Selected edge deployment |
| **Data storage** | Selected edge deployment |
| **Query execution** | Selected edge deployment |
| **Query results** | Selected edge deployment |
| **Account data** | US infrastructure |
When you select an edge deployment, event data is ingested, stored, and queried entirely within that edge deployment. Query results are returned directly from the edge without routing through other infrastructure. Account management operations (user settings, billing, organization configuration) are processed through Axiom’s centralized US infrastructure.
### Compliance considerations [#compliance-considerations]
Axiom’s edge deployment architecture supports data-sovereignty requirements by keeping event data ingestion, storage, query execution, and query results within your selected edge deployment. This architecture is designed to meet frameworks that require both storage and processing of data to take place entirely within a designated region.
Account management operations (user authentication, billing, organization settings) are processed through Axiom’s centralized US infrastructure. Evaluate whether this meets your specific compliance requirements. For most data-sovereignty frameworks, the critical factor is where event data is stored and processed, which remains entirely within your selected edge deployment.
### Determine your organization’s edge deployment [#determine-your-organizations-edge-deployment]
In multi-region organizations, you can specify the edge deployment for each dataset. This means that you can select where Axiom stores your event data when creating a new dataset. You can't change the edge deployment of a dataset after creating the dataset.
The default edge deployment of your organization is the option automatically selected when you create a new dataset. You can’t change your default edge deployment after creating your organization.
To determine your organization’s default edge deployment:
1. Click **Settings > General**.
2. Find your organization’s default edge deployment in the **Edge deployment** section.
## Multi-edge organizations [#multi-edge-organizations]
To create datasets in an edge deployment other than your organization’s default edge deployment:
1. [Buy the add-on](/reference/usage-billing#manage-add-ons) associated with the new edge deployment.
2. When you [create a new dataset](/reference/datasets#create-dataset), select the new edge deployment.
Add-on must remain active to retain access to datasets located outside your organization’s default edge deployment.
In multi-edge organizations, each query can only access data from a single edge deployment. Wildcard operators in queries only match datasets within the organization’s default edge deployment.
## SDKs and edge deployments [#sdks-and-edge-deployments]
Axiom SDKs will support edge deployments through environment variables. The SDKs will default to `US East 1 (AWS)`. Until Axiom updates all SDKs, configure ingest endpoints manually.
## Axiom-hosted MCP server [#axiom-hosted-mcp-server]
Axiom hosts the MCP Server in the US at `https://mcp.axiom.co/mcp` and in the EU at `https://mcp.eu.axiom.co/mcp`. Both send each query to the edge deployment that holds the dataset. The US MCP Server handles query results in data centers worldwide. The EU MCP Server handles them only in data centers in the EU. Both send sign-in and other requests that aren’t queries to Axiom’s US API.
For more information, see [Axiom MCP Server](/console/intelligence/mcp-server#choose-a-region).
---
# Limits
Source: https://axiom.co/docs/reference/limits
Axiom applies certain limits and requirements to guarantee good service across the platform. Some of these limits depend on your pricing plan, and some of them are applied system-wide. This reference article explains all limits and requirements applied by Axiom.
Limits are necessary to prevent potential issues that could arise from the ingestion of excessively large events or data structures that are too complex. Limits help maintain system performance, allow for effective data processing, and manage resources effectively.
## Pricing-based limits [#pricing-based-limits]
The table below summarizes the limits applied to each pricing plan. For more details on pricing and contact information, see the [Axiom pricing page](https://axiom.co/pricing).
| | Personal | Axiom Cloud |
| :-------------------------------------------------------- | :------------------ | :------------------- |
| Always Free storage | 25 GB | 100 GB |
| Always Free data loading | 500 GB / month | 1,000 GB / month |
| Always Free query compute | 10 GB-hours / month | 100 GB-hours / month |
| Maximum data loading | 500 GB / month | – |
| Maximum data retention | 30 days | Custom |
| [Datasets](/reference/datasets) | 3 | 100 \* |
| Fields per dataset | 256 | 1,024 \* |
| Users | 1 | 1,000 \* |
| [Monitors](/monitor-data/monitors) | 3 | 500 \* |
| [Notifiers](/monitor-data/notifiers-overview) | Email, Discord | All supported |
| [Supported edge deployments](/reference/edge-deployments) | US | US |
\* Soft limit that can be increased upon request.
If you’re on the Axiom Cloud plan and you exceed the Always Free allowances outlined above, additional charges apply based on your usage above the allowance. For more information, see the [Axiom pricing page](https://axiom.co/pricing).
All plans include unlimited bandwidth, API access, and data sources subject to the [Fair Use Policy](https://axiom.co/terms).
To see how much of your allowance each dataset uses, go to **Settings > Usage**.
For more information on how to save on data loading, data retention, and querying costs, see [Optimize usage](/reference/optimize-usage).
### Restrictions on datasets and fields [#restrictions-on-datasets-and-fields]
Axiom restricts the number of datasets and the number of fields in your datasets. The number of datasets and fields you can use is based on your pricing plan and explained in the table above.
If you ingest a new event that would exceed the allowed number of fields in a dataset, Axiom returns an error and rejects the event. To prevent this error, ensure that the number of fields in your events are within the allowed limits.
To reduce the number of fields in a dataset, use one of the following approaches:
* [Delete the fields](/reference/datasets#delete-fields) you don’t need.
* [Vacuum the fields](/reference/datasets#vacuum-fields) to remove fields that no longer occur in events within your retention period. If necessary, [trim the dataset](/reference/datasets#trim-dataset) first.
* Use [map fields](/apl/data-types/map-fields).
To prevent new fields from being added to an event dataset, [lock its schema](/reference/datasets#lock-dataset-schema).
## System-wide limits [#system-wide-limits]
The following limits are applied to all accounts, irrespective of the pricing plan.
### Limits on ingested data [#limits-on-ingested-data]
The table below summarizes the limits Axiom applies to each data ingest. These limits are independent of your pricing plan. For metrics, see [Limits on ingested metrics](#limits-on-ingested-metrics).
| | Limit |
| ------------------------- | --------- |
| Maximum field size | 1 MB |
| Maximum events in a batch | 10,000 |
| Maximum field name length | 200 bytes |
If you try to ingest data that exceeds these limits, Axiom does the following:
* Replaces strings that are too long with ``.
* Replaces binary with ``.
* Truncates maps and slices that nest deeper than 100 levels and replaces them with `nil` at the cut-off level.
* Converts the following float values to `nil`:
* NaN
* +Infty
* -Infty
### Limits on ingested metrics [#limits-on-ingested-metrics]
The limits below apply to OpenTelemetry metrics that you send to the `/v1/metrics` endpoint. They’re separate from the event ingest limits above and independent of your pricing plan.
| | Limit |
| ---------------------------------------- | ----------------------- |
| Maximum request size | 4 MiB (4,194,304 bytes) |
| Maximum metric name length | 256 bytes |
| Maximum attribute name length | 256 bytes |
| Maximum attribute value length | 1 KiB (1,024 bytes) |
| Maximum buckets per histogram data point | 256 |
| Maximum quantiles per summary data point | 256 |
The maximum request size applies to the uncompressed payload. Axiom accepts gzip, zstd, brotli, and deflate compression, and compressing requests reduces the bandwidth you use. Axiom checks the request size after decompressing the request, so compression doesn’t allow you to send more data in a single request.
If a request exceeds the maximum request size, Axiom rejects it with the HTTP status code `413`. The OpenTelemetry Collector treats this status code as a permanent error, so it drops the batch instead of retrying it.
To keep requests within the limit, use the `batch` processor in your OpenTelemetry Collector configuration and set `send_batch_max_size`. Whether a given batch size stays within 4 MiB depends on the number of attributes that your data points carry. If you receive `413` responses, reduce `send_batch_max_size`. For an example configuration, see [Send OpenTelemetry data to Axiom](/send-data/opentelemetry).
The maximum number of buckets applies to each histogram data point and counts the entries in its `explicit_bounds` list. The implicit overflow bucket that catches values above the last boundary doesn’t count towards the limit. For summary data points, the limit counts the entries in the `quantile_values` list.
If a metric name, an attribute, or the number of buckets or quantiles exceeds the limits above, Axiom doesn’t reject the whole request. It rejects the affected data points, responds with the HTTP status code `200`, and returns an OpenTelemetry `partial_success` message that reports the number of rejected data points and the reason. For example, a histogram data point with too many buckets is reported as `[http.server.duration] metric limit violation: Bucket count 300 (explicit_bounds/quantile_values) exceeds limit 256`.
### Special fields [#special-fields]
Axiom creates the following two fields automatically for a new dataset:
* `_time` is the timestamp of the event. If the data you ingest doesn’t have a `_time` field, Axiom assigns the time of the data ingest to the events. If you ingest data using the [Ingest data](/restapi/endpoints/ingestToDataset) API endpoint, you can specify the timestamp field with the [timestamp-field](/restapi/endpoints/ingestToDataset#parameter-timestamp-field) parameter.
* `_sysTime` is the time when you ingested the data.
In most cases, use `_time` to define the timestamp of events. In rare cases, if you experience clock skews on your event-producing systems, `_sysTime` can be useful.
### Reserved field names [#reserved-field-names]
Axiom reserves the following field names for internal use:
* `_blockInfo`
* `_cursor`
* `_rowID`
* `_source`
* `_sysTime`
Don’t ingest data that contains these fields names. If you try to ingest a field with a reserved name, Axiom renames the ingested field to `_user_FIELDNAME`. For example, if you try to ingest the field `_sysTime`, Axiom renames it to `_user_sysTime`.
In general, avoid ingesting field names that start with `_`.
### Requirements for timestamp field [#requirements-for-timestamp-field]
The most important field requirement is about the timestamp.
All events stored in Axiom must have a `_time` timestamp field. If the data you ingest doesn’t have a `_time` field, Axiom assigns the time of the data ingest to the events. To specify the timestamp yourself, include a `_time` field in the ingested data.
If you include the `_time` field in the ingested data, follow these requirements:
* Timestamps are specified in the `_time` field.
* The `_time` field contains timestamps in a valid time format. Axiom accepts many date strings and timestamps without knowing the format in advance, including Unix Epoch, RFC3339, or ISO 8601.
* The `_time` field is a field with UTF-8 encoding.
* The `_time` field isn’t used for any other purpose.
* The timestamp isn’t more than 24 hours in the future or before the Unix epoch (`1970-01-01T00:00:00Z`).
Axiom rejects events with a timestamp more than 24 hours in the future or before the Unix epoch and doesn’t store them. If a request contains both valid and rejected events, Axiom stores the valid events, responds with the HTTP status code `200`, counts the rejected events in `failed`, and lists them in `failures`. If every event in a request is rejected, Axiom responds with the HTTP status code `400`.
### Requirements for log level fields [#requirements-for-log-level-fields]
Stream, query results, trace logs, and the event timeline use the same rules to choose an event's display level. These rules leave stored event fields and monitor conditions unchanged.
An explicit log level takes priority over words in a message. For example, an event with `level: "info"` and `message: "error error error"` displays as `info`.
#### Field priority [#field-priority]
Axiom checks the following fields in order and stops at the first recognized value. Missing fields and unrecognized values fall through to the next field. Within each table row, fields are checked from left to right.
| Priority | Fields | Accepted values |
| -------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| 1 | `_row_status` | A dashboard query's display override. Accepts the text levels below. |
| 2 | `severity_id` with `class_uid` | [OCSF severity IDs](/reference/limits#supported-schemas). |
| 3 | `severity_text`, `severity_number`, `severityText`, `severityNumber` | OpenTelemetry text or numeric levels, according to the field name. |
| 4 | `level`, `severity`, `log.level`, `@level`, `@severity` | Text levels. `severity` also accepts Syslog codes when the event has [Syslog headers](/reference/limits#supported-schemas). |
| 5 | `record.level`, `record.severity` | Text levels. |
| 6 | `data.log_level` | Convex levels: `DEBUG`, `INFO`, `LOG`, `WARN`, and `ERROR`. |
| 7 | `record.error` | Text levels. Exception objects and error descriptions aren't recognized. |
| 8 | `log.syslog.severity.code`, `log.syslog.severity.name` | Syslog codes or names. |
| 9 | `type` and `record` fields | [AWS Lambda platform events](/reference/limits#aws-lambda-platform-events). |
Axiom reads dotted field names and their nested equivalents, including objects stored as JSON text. For example, both `{"record.level": "info"}` and `{"record": {"level": "info"}}` supply `record.level`. If both forms exist, a non-null dotted field takes precedence.
#### Recognized values [#recognized-values]
Text values match exactly, ignoring capitalization. For example, `ERROR` matches, but `errorful` and `error: request failed` don't.
| Display level | Text values |
| ------------- | -------------------- |
| `error` | `err`, `error` |
| `warn` | `warn`, `warning` |
| `info` | `info` |
| `success` | `success` |
| `trace` | `trace` |
| `debug` | `debug` |
| `notice` | `notice` |
| `critical` | `crit`, `critical` |
| `fatal` | `fatal` |
| `alert` | `alert` |
| `emergency` | `emerg`, `emergency` |
| `unknown` | `unknown` |
Levels keep their names and timeline groups, even when they share a color.
#### Supported schemas [#supported-schemas]
Numeric levels depend on the schema: `5` means `debug` in OpenTelemetry, `notice` in Syslog, and `critical` in OCSF.
OpenTelemetry numeric fields accept integers from 1 to 24:
| Numeric value | Display level |
| ------------- | ------------- |
| 1–4 | `trace` |
| 5–8 | `debug` |
| 9–12 | `info` |
| 13–16 | `warn` |
| 17–20 | `error` |
| 21–24 | `fatal` |
These fields also accept decimal strings such as `"17"`. Values such as `0`, `25`, `"017"`, and `"Severity(17)"` aren't recognized.
OpenTelemetry text fields also accept numbered names such as `WARN2` and `FATAL4`. For more information, see [OpenTelemetry severity fields](https://opentelemetry.io/docs/specs/otel/logs/data-model/#severity-fields).
For Convex's `data.log_level`, `DEBUG` displays as `debug`, `INFO` and `LOG` as `info`, `WARN` as `warn`, and `ERROR` as `error`. The value `LOG` has no special meaning in other fields or message text.
Axiom reads `severity_id` when `class_uid` is a nonnegative integer, including `0`.
| ID | Display level |
| -- | ---------------------------------------------------------------------------------------------------------- |
| 0 | `unknown` |
| 1 | `informational` |
| 2 | `low` |
| 3 | `medium` |
| 4 | `high` |
| 5 | `critical` |
| 6 | `fatal` |
| 99 | The event's `severity` text, converted to lowercase. Missing, empty, or non-string values produce `other`. |
For more information, see the severity attributes in the [OCSF schema](https://schema.ocsf.io/1.2.0/classes/authentication).
Axiom reads codes from `log.syslog.severity.code` and names from `log.syslog.severity.name`.
| Code | Display level |
| ---- | ------------- |
| 0 | `emergency` |
| 1 | `alert` |
| 2 | `critical` |
| 3 | `error` |
| 4 | `warn` |
| 5 | `notice` |
| 6 | `info` |
| 7 | `debug` |
Names accept the text levels above, plus `informational` as `info`. Axiom also reads these codes and names from `severity` when `hostname`, `application`, and `message` are all strings, including empty strings.
Axiom does not read severity from the combined Syslog priority value (PRI) or from `event.severity`. For more information, see [Syslog severity levels](https://www.rfc-editor.org/rfc/rfc5424.html#section-6.2.1).
##### AWS Lambda platform events [#aws-lambda-platform-events]
Axiom uses these rules when earlier fields do not supply a level. Event types include the `platform.` prefix, and their field values are case-sensitive.
| Event type | Condition | Display level |
| ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | ------------- |
| `platform.start`, `platform.logsSubscription`, `platform.logSubscription`, `platform.telemetrySubscription` | Any | `info` |
| `platform.logsDropped` | Any | `warn` |
| `platform.fault` | Any | `error` |
| `platform.initStart`, `platform.restoreStart` | `record.runtimeVersion` is a nonempty string | `info` |
| `platform.initStart`, `platform.restoreStart` | `record.runtimeVersion` is missing or empty | `debug` |
| `platform.initRuntimeDone`, `platform.restoreRuntimeDone`, `platform.runtimeDone` | `record.status` is `success` | `debug` |
| `platform.report`, `platform.restoreReport` | `record.status` is `success` or absent | `info` |
| `platform.initReport` | `record.initializationType` is `on-demand` | `debug` |
| `platform.initReport` | `record.initializationType` is `provisioned-concurrency`, `snap-start`, or `lambda-managed-instances` | `info` |
| `platform.extension` | `record.state` is `Ready` | `info` |
| `platform.extension` | `record.state` is `InitError`, `ExitError`, `ShutdownFailed`, or `LaunchError` | `warn` |
For runtime and report events, `record.status` values of `failure`, `error`, and `timeout` produce `warn`. On `platform.initReport`, a failure status takes priority over the initialization type.
Other or malformed values produce `unknown`, without continuing to message fallback. Lambda application logs use explicit level fields or message fallback. For more information, see [AWS Lambda log levels](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-cloudwatchlogs-log-level.html).
#### Message fallback [#message-fallback]
If no field supplies a recognized level, Axiom checks string values in `message`, `msg`, `@message`, `text`, `record`, and `data.message`, in that order. For each value, Axiom checks only the first 100 characters and first two lines. The first complete severity keyword wins. The word `unknown` is excluded. Axiom doesn't scan the entire event or count repeated keywords.
For example:
| Event | Display level | Reason |
| ----------------------------------------------------------------------------------- | ------------- | ------------------------------------------- |
| `{"level": "info", "message": "error error error"}` | `info` | The explicit level wins. |
| `{"message": "WARN retry; error"}` | `warn` | The first keyword wins. |
| `{"message": "request started\nerror: connection refused\nretry scheduled"}` | `error` | The keyword is on the second line. |
| `{"message": "request started\nconnecting to database\nerror: connection refused"}` | `unknown` | The keyword is outside the first two lines. |
| `{"severityNumber": 17}` | `error` | The numeric level is recognized. |
If nothing matches, the event displays as neutral `unknown`.
#### Inspect a log level [#inspect-a-log-level]
Hover over an event's severity marker to see its display level, the field that determined it, and that field's original value. The tooltip also links to documentation for that format.
The tooltip shows the matching format: OTel, AWS Lambda, Convex, OCSF, or Syslog. Text levels means no single schema was identified. Message indicates a keyword match, and Override indicates `_row_status`.
In the event details view, click a level badge with a source field to highlight that field. If the value is inside JSON text, Axiom highlights the containing field.
#### Map a custom field [#map-a-custom-field]
To use a custom severity field, create a [virtual field](/query-data/virtual-fields#creating-a-virtual-field) named `level` or `severity` that returns a recognized value. For example, if `app_log_level` contains values such as `INFO` and `ERROR`, create a virtual field named `level` with this expression:
```kusto
tostring(app_log_level)
```
Virtual fields follow the same field priority as stored fields. A virtual field named `severity` doesn't override a recognized `level` or an earlier field.
## Temporary account-specific limits [#temporary-account-specific-limits]
If you send a large amount of data in a short amount of time and with a high frequency of API requests, Axiom may temporarily restrict or disable your ability to send data to Axiom. This is to prevent abuse of the platform and to guarantee consistent and high-quality service to all customers. In this case, Axiom kindly asks you to reconsider your approach to data collection. For example, to reduce the total number of API requests, try sending your data in larger batches. This adjustment both streamlines Axiom operations and improves the efficiency of your data ingest. If you often experience these temporary restrictions and have a good reason for changing these limits, please [contact Support](https://axiom.co/contact).
---
# Optimize usage
Source: https://axiom.co/docs/reference/optimize-usage
## Optimize data loading [#optimize-data-loading]
When you send data via the [Ingest data](/restapi/endpoints/ingestToDataset) API endpoint, ingest volume is based on the uncompressed size of the HTTP request. In this case, body size dominates and metadata overhead is usually negligible.
If you ingest data via API, using the CSV format comes with the following trade-offs:
* **Pro:** CSV doesn’t repeat field names. This means lower ingest volume and lower ingest costs.
* **Con:** Every value is a string. You need to do type casting at query time. This means higher cost and latency.
* **Con:** Numbers as strings don’t compress well. This means higher storage and query costs.
For higher volume, using a [dedicated ingestion method](/send-data/methods) is a better choice than sending data via API.
## Optimize storage [#optimize-storage]
The amount of storage you use depends on the following:
* The amount of data you ingest to Axiom.
* The data retention period you specify.
The data retention period defines how long Axiom stores your data. After this period, Axiom trims the data and it doesn’t count towards your storage costs. You can define a custom data retention period for each dataset. For more information, see [Specify data retention period](/reference/datasets#specify-data-retention-period).
### Adaptive Tiering [#adaptive-tiering]
On Axiom Cloud, Adaptive Tiering automatically moves your data between three access tiers based on how recently you queried it:
| Access tier | Data in this access tier |
| :--------------------- | :------------------------------------------------------------- |
| Frequent Access | Newly ingested data, and any data queried in the last 30 days. |
| Infrequent Access | Data that hasn’t been queried for 30 consecutive days. |
| Archive Instant Access | Data that hasn’t been queried for 90 consecutive days. |
Every access tier delivers the same low latency and high throughput. You query data in Infrequent Access and Archive Instant Access exactly as you query data in Frequent Access: there’s no restore step, no rehydration, and no wait. The only thing that changes is the price. For the rates of each access tier, see the [Axiom pricing page](https://axiom.co/pricing).
Adaptive Tiering needs no configuration. When you query data in Infrequent Access or Archive Instant Access, it returns to Frequent Access, then moves down again after 30 and 90 consecutive days without a query. A query reads all data in its time range, so a broad time range returns more data to Frequent Access than a narrow one.
Because Axiom stores machine data in a highly compressed columnar block format, storage is typically a small proportion of an Axiom bill. Adaptive Tiering reduces it further the longer data goes unqueried, so keeping a long retention period costs less.
To see how much of your data is in each access tier, go to **Settings > Usage**. For more information, see [Usage](/reference/usage-billing#usage).
## Optimize queries [#optimize-queries]
Axiom measures the resources used to execute queries in terms of GB-hours.
### What GB-hours are [#what-gb-hours-are]
When you run queries, your usage of the Axiom platform is measured in query-hours. The unit of this measurement is GB-hours which reflects the duration (measured in milliseconds) serverless functions are running to execute your query multiplied by the amount of memory (GB) allocated to execution. This metric is important for monitoring and managing your usage against the monthly allowance included in your plan.
### How Axiom measures query-hours [#how-axiom-measures-query-hours]
Axiom uses serverless computing to execute queries efficiently. The consumption of serverless compute resources is measured along two dimensions:
* Time: The duration (in milliseconds) for which the serverless function is running to execute your query.
* Memory allocation: The amount of memory (in GB) allocated to the serverless function during execution.
### What counts as a query [#what-counts-as-a-query]
In calculating query costs, Axiom considers any request that queries your data as a query. For example, the following all count as queries:
* You initiate a query in the Axiom user interface.
* You query your data with an API token or a personal access token.
* Your match monitor runs a query to determine if any new events match your criteria.
Each query is charged at the same rate, irrespective of its origin.
### Cap query costs per token or role [#cap-query-costs-per-token-or-role]
To put a hard cap on the query costs of an API token or a member, set hourly and daily query cost limits on API tokens and roles. This is particularly useful for AI agents and other automated query workloads. For more information, see [Set query cost limits for AI agents](/console/intelligence/query-cost-limits).
Each monitor run counts towards your query costs. For this reason, the frequency (how often the monitor runs) can have a slight effect on query costs.
### Run queries and understand costs [#run-queries-and-understand-costs]
When you run queries on Axiom, the cost in GB-hours is determined by the shape and size of the events in your dataset and the volume of events scanned to return a query result. After executing a query, you can find the associated query cost in the response header labeled as `X-Axiom-Query-Cost-Gbms`.
### Determine query cost [#determine-query-cost]
Send a `POST` request to the [Run APL query to edge deployment](/restapi/endpoints/queryEdge) endpoint with the following configuration:
* `Content-Type` header with the value `application/json`.
* `Authorization` header with the value `Bearer API_TOKEN`. Replace `API_TOKEN` with your Axiom API token.
* In the body of your request, enter your query in JSON format. For example:
```json
{
"apl": "telegraf | count",
"startTime": "2024-01-11T19:25:00Z",
"endTime": "2024-02-13T19:25:00Z"
}
```
`apl` specifies the Axiom Processing Language (APL) query to run. In this case, `"telegraf | count"` indicates that you query the `telegraf` dataset and use the `count` operator to aggregate the data.
`startTime` and `endTime` define the time range of your query. In this case, `"2024-01-11T19:25:00Z"` is the start time, and `"2024-02-13T19:25:00Z"` is the end time, both in ISO 8601 format. This time range limits the query to events recorded within these specific dates and times.
In the response to your request, the information about the query cost in GB-milliseconds is in the `X-Axiom-Query-Cost-Gbms` header.
### Example of GB-hour calculation [#example-of-gb-hour-calculation]
As an example, a typical query analyzing 1 million events might consume approximately 1 GB-second. There are 3,600 seconds in an hour which means that an organization can run 3,600 of these queries before reaching 1 GB-hour of query usage. This is an example and the actual usage depends on the complexity of the query and the input data.
### Plan and GB-hours allowance [#plan-and-gb-hours-allowance]
Your GB-hours allowance depends on your pricing plan. To learn more about the plan offerings and find the one that best suits your needs, see [Axiom Pricing](https://axiom.co/pricing).
### Optimize queries to lower costs [#optimize-queries-to-lower-costs]
This section explains ways you can optimize your queries to save on query costs. For more information optimizing your queries for performance, see [Optimize performance](/reference/performance).
#### Optimize the order of field-specific filters [#optimize-the-order-of-field-specific-filters]
Field-specific filters narrow your query results to events where a field has a given value. For example, the APL query `where ["my-field"] == "axiom"` filters for events where the `my-field` field takes the value `axiom`.
Include field-specific filters near the beginning of your query for modest savings in query costs. For more information, see [Poor filter order in queries](/reference/performance#poor-filter-order-in-queries)
#### Optimize `search` operator and non-field-specific filters [#optimize-search-operator-and-non-field-specific-filters]
Non-field-specific filters narrow your query results by searching across multiple datasets and fields for a given value. Examples of non-field-specific filters are the `search` operator and equivalent expressions such as `where * contains` or `where * has`.
Using non-field-specific filters can have a significant impact on query costs. For more information, see [Use the `search` operator efficiently](/apl/tabular-operators/search-operator#use-the-search-operator-efficiently) and [Regular expressions when simple filters suffice](/reference/performance#regular-expressions-when-simple-filters-suffice).
### Optimize dashboard refresh rates [#optimize-dashboard-refresh-rates]
Each time your dashboard refreshes, it runs a query on your data which results in query costs. Selecting a short refresh rate (such as 15 seconds) for a long time range (such as 90 days) means that your dashboard frequently runs large queries in the background.
To optimize query costs, choose a refresh rate that's appropriate for the time range of your dashboard. For more information, see [Select refresh rate](/dashboards/configure#select-refresh-rate).
## Monitor costs proactively [#monitor-costs-proactively]
Proactive cost monitoring helps you identify unexpected cost increases before they impact your budget. Use the following strategies to stay on top of your usage.
### Use Axiom Skills [#use-axiom-skills]
Use the [Control costs skill](/console/intelligence/skills/control-costs) to automate cost control tasks. The skill helps you:
* Create a cost monitoring dashboard.
* Set up cost alert monitors.
* Analyze your datasets to identify data that isn't queried and is a good candidate for dropping at the collector level.
### Track data ingest [#track-data-ingest]
The [audit log](/reference/audit-log) captures hourly ingestion data for each dataset.
Identify which datasets contribute most to your ingestion costs:
```kusto
['axiom-audit']
| where action == "usageCalculated"
| extend ingest_gb = tolong(['properties.hourlyIngestBytes']) / pow(1024, 3)
| summarize IngestGB = sum(ingest_gb) by bin_auto(_time), tostring(['properties.dataset'])
| sort by IngestGB desc
```
Determine total data ingest across all datasets over time:
```kusto
['axiom-audit']
| where action == "usageCalculated"
| extend ingest_gb = tolong(['properties.hourlyIngestBytes']) / pow(1024, 3)
| summarize TotalIngestGB = sum(ingest_gb) by bin_auto(_time)
```
### Create a cost monitoring dashboard [#create-a-cost-monitoring-dashboard]
Build a dashboard that displays your key cost metrics at a glance:
1. **Ingest over time**: Track daily or hourly ingestion trends per dataset.
2. **Query costs**: Monitor which queries and monitors consume the most resources.
3. **High-cost queries**: List queries that exceed a cost threshold.
For dashboard creation, see [Create a dashboard](/dashboards/create).
### Set up cost alerts [#set-up-cost-alerts]
Create monitors to alert you when costs exceed expected thresholds:
* **Ingest spike alert**: Notify when hourly ingestion exceeds a threshold.
* **Query cost alert**: Notify when a single query exceeds a cost threshold.
* **Daily cost summary**: Send a daily digest of total costs.
Example monitor query for ingestion spikes:
```kusto
['axiom-audit']
| where action == "usageCalculated"
| extend ingest_gb = tolong(['properties.hourlyIngestBytes']) / pow(1024, 3)
| summarize HourlyIngestGB = sum(ingest_gb) by bin(_time, 1h)
| where HourlyIngestGB > 10
```
Adjust the threshold for `HourlyIngestGB` based on your expected ingestion patterns. For more information, see [Threshold monitors](/monitor-data/threshold-monitors).
### Set a spending limit [#set-a-spending-limit]
Set a monthly spending limit to automatically pause cost-generating actions when you reach a specified amount. For more information, see [Spending limit](/reference/usage-billing#spending-limit).
### Set refresh rate for dashboards [#set-refresh-rate-for-dashboards]
To optimize query costs, choose a refresh rate that’s appropriate for the time range of your dashboard. For more information, see [Select refresh rate](/dashboards/configure#select-refresh-rate).
---
# Configure Axiom organization
Source: https://axiom.co/docs/reference/organization-settings
## Determine organization ID [#determine-organization-id]
1. Click **Settings > General**.
2. Find organization ID in the **ID** section.
## Determine organization edge deployment [#determine-organization-edge-deployment]
1. Click **Settings > General**.
2. Find your organization’s default edge deployment in the **Edge deployment** section.
For more information, see [Edge deployments](/reference/edge-deployments).
## Set default dataset retention period [#set-default-dataset-retention-period]
The default dataset retention period determines how long Axiom stores data in datasets that don’t have their own custom retention period. Datasets without a custom retention period inherit this value. You can only set the default dataset retention period on the Axiom Cloud plan.
Changing the default dataset retention period affects **existing datasets**, not only datasets you create later. When you lower the default, Axiom immediately deletes all data older than the new period in every dataset that inherits the default. This process can’t be undone.
Before you lower the default, set a custom retention period on each dataset whose data you want to keep. For more information, see [Specify data retention period](/reference/datasets#specify-data-retention-period).
The default dataset retention period doesn’t affect the maximum query window of your organization. The maximum query window is determined by your plan and stays the same when you change the default dataset retention period.
To store data for longer, increase the default dataset retention period. Increasing the default doesn’t delete any data.
To set the default dataset retention period, follow these steps:
1. Click **Settings > General**.
2. Click next to the **Default dataset retention** section.
3. Specify the default dataset retention period.
4. Click **Submit**.
## Turn Axiom AI on or off [#turn-axiom-ai-on-or-off]
## Delete organization [#delete-organization]
This is a destructive action. After you delete your organization, you lose access to all data within that org.
To delete your organization:
1. Back up your data. You aren’t able to access the data after deleting the org.
2. Click **Settings > General**
3. Click **Delete organization**.
---
# Optimize performance
Source: https://axiom.co/docs/reference/performance
Axiom is optimized for storing and querying timestamped event data. However, certain ingest and query practices can degrade performance and increase cost. This page explains pitfalls and provides guidance on how you can avoid them to keep your Axiom queries fast and efficient.
## Summary of pitfalls [#summary-of-pitfalls]
| Practice | Severity | Impact |
| :-------------------------------------------------------------------------------------------------------------------------- | :------- | :------------------------------------------------------------- |
| [Mixing unrelated data in datasets](#mixing-unrelated-data-in-datasets) | Critical | Combining unrelated data inflates schema, slows queries |
| [Excessive backfilling, big difference between \_time and \_sysTime](#excessive-backfilling-and-large-time-vs-systime-gaps) | Critical | Creates overlapping blocks, breaks time-based indexing |
| [Large number of fields in a dataset](#large-number-of-fields-in-a-dataset) | High | Very high dimensionality slows down query performance |
| [Failing to use \_time](#failing-to-use-the-_time-field-for-event-timestamps) | High | No efficient time-based filtering |
| [Query exceeds memory constraints](#query-exceeds-memory-constraints) | High | Queries can exceed memory limits and fail with HTTP 432 errors |
| [Overly wide queries (project \*)](#overly-wide-queries-returning-more-fields-than-needed) | High | Returns massive unneeded data |
| [Mixed data types in the same field](#mixing-unrelated-data-in-datasets) | Moderate | Reduces compression, complicates queries |
| [Using regex when simpler filters suffice](#regular-expressions-when-simple-filters-suffice) | Moderate | More CPU-heavy scanning |
| [Overusing runtime JSON parsing (parse\_json)](#overusing-runtime-json-parsing-parse_json) | Moderate | CPU overhead, no indexing on nested fields |
| [Virtual fields for simple transformations](#virtual-fields-for-simple-transformations) | Low | Extra overhead for trivial conversions |
| [Poor filter order in queries](#poor-filter-order-in-queries) | Low | Suboptimal scanning of data |
## Mixing unrelated data in datasets [#mixing-unrelated-data-in-datasets]
### Problem [#problem]
A “kitchen-sink” dataset is one in which events from multiple, unrelated apps or services get lumped together, often resulting in:
* **Excessive width (too many fields)**: Adding more and more unique fields bloats the schema, reducing query throughput.
* **Mixed data types in the same field**: For example, some events store `user_id` as a string, while others store it as a number in the same `user_id` field.
* **Unrelated schemas in a single dataset**: Fields that make sense for one app might be `null` or typed differently for another.
These issues reduce compression efficiency and force Axiom to scan more data than necessary.
### Why it matters [#why-it-matters]
* **Slower queries**: Each query must scan wider blocks of data and handle inconsistent field types.
* **Higher resource usage**: Wide schemas reduce row packing in blocks, harming throughput and potentially raising costs.
* **Harder data exploration**: When fields differ drastically between events, discovering the correct fields or shaping queries becomes more difficult.
### How to fix it [#how-to-fix-it]
* **Keep datasets narrowly focused:** Group data from the same app or service in its own dataset. For example, keep `k8s_logs` separate from `web_traffic`.
* **Avoid mixing data types for the same field:** Enforce consistent types during ingest. If a field is numeric, always send numeric values.
* **Consider using map fields:** If you have sparse or high-cardinality nested data, consider storing it in a single map (object) field instead of flattening every key. This reduces the total number of top-level fields. Axiom’s [map fields](/apl/data-types/map-fields#map-fields) are optimized for large objects.
## Excessive backfilling and large `_time` vs. `_sysTime` gaps [#excessive-backfilling-and-large-_time-vs-_systime-gaps]
### Problem [#problem-1]
Axiom’s `_time` index is critical for query performance. Ideally, incoming events for a block lie in a closely bounded time range. However, backfilling large amounts of historical data after the fact (especially out of chronological order) creates wide time overlaps in blocks. If `_time` is far from `_sysTime` (the time the event was ingested), Axiom’s time index effectiveness is weakened.
### Why it matters [#why-it-matters-1]
* **Poor performance on time-based queries**: Blocks must be scanned despite time filters, because many blocks overlap the query time window.
* **Inefficient block filtering**: Queries that filter on time must scan blocks that contain data from a wide time range.
* **Large data merges**: Compaction processes that rely on time ordering become less efficient.
### How to fix it [#how-to-fix-it-1]
* **Minimize backfill:** Try to ingest events close to their actual creation time whenever possible. Ingest events close to the time they occur.
* **Backfill in dedicated batches:** If you must backfill older data, do it in dedicated batches that don’t mix with live data.
* **Use discrete backfill intervals:** When backfilling data, ingest one segment at a time (for example, day-by-day).
* **Avoid wide time ranges in a single batch:** If you are sending data for a 24-hour period, avoid mixing in data that’s weeks or months older.
* **Be aware of ingestion concurrency:** Avoid mixing brand-new events with extremely old events in the same ingest request.
Future improvements: Axiom’s roadmap includes an initiative which aims to mitigate the impact of poorly clustered time data by performing incremental time-based compaction. Until then, avoid mixing large historical ranges with live ingest whenever possible.
## Large number of fields in a dataset [#large-number-of-fields-in-a-dataset]
### Problem [#problem-2]
Slow query performance in datasets with very high dimensionality (with more than several thousand fields).
### Why it matters [#why-it-matters-2]
Axiom stores event data in a tuned format. As a result:
* The number of distinct values (cardinality) in your data impacts performance because low-cardinality fields compress better than high-cardinality fields.
* The number of fields in a dataset (dimensionality) impacts performance.
* The volume of data collected impacts performance.
### How to fix it [#how-to-fix-it-2]
Scoping the number of fields in a dataset below a few thousand can help you achieve the best performance in Axiom.
## Failing to use the `_time` field for event timestamps [#failing-to-use-the-_time-field-for-event-timestamps]
### Problem [#problem-3]
Axiom’s core optimizations rely on `_time` for indexing and time-based queries. If you store event timestamps in a different field (for example, `timestamp` or `created_at`) and use that field in time filters, you can’t leverage Axiom’s time-based optimizations.
### Why it matters [#why-it-matters-3]
* **No time-based indexing**: Every block must be scanned because your custom timestamp field is invisible to the time index.
### How to fix it [#how-to-fix-it-3]
* **Always use `_time`:** Configure your ingest pipelines so that Axiom sets `_time` to the actual event timestamp.
* If you have a custom field like `created_at`, rename it to `_time` at ingest.
* Verify that your ingestion library or agent is correctly populating `_time`.
* **Use Axiom’s native time filters:** Rely on `where _time >= ... and _time <= ...` or the built-in time range selectors in the query UI.
## Handling mixed types in the same field [#handling-mixed-types-in-the-same-field]
### Problem [#problem-4]
A single field sometimes stores different data types across events (for instance, strings in some events and integers in others). This is typically a side effect of using “kitchen-sink” ingestion or inconsistent parsing logic in your code.
### Why it matters [#why-it-matters-4]
* **Reduced compression**: Storing multiple types in the same field (variant field) is less efficient than storing a single type.
* **Complex queries**: You might need frequent casting or conditional logic in queries (`tostring()` calls, etc.).
### How to fix it [#how-to-fix-it-4]
* **Standardize your types at ingest:** If a field is semantically an integer, always send it as an integer.
* **Use consistent schemas across services:** If multiple apps write to the same dataset, agree on a schema and data types.
* **Perform corrections at the source:** If you discover your data has been mixed historically, stop ingesting mismatched types. Over time, new blocks reflect the corrected types even though historical blocks remain mixed.
## Query exceeds memory constraints [#query-exceeds-memory-constraints]
### Problem [#problem-5]
Some queries can exceed the available memory budget on query workers, causing them to fail with an HTTP 432 error (`StatusQueryMemoryExceeded`). This typically happens when queries use memory-intensive operations on large datasets or wide schemas. For example, when you use `parse_json()` on large strings or `pack(*)` on datasets with many fields.
### Why it matters [#why-it-matters-5]
* **Query failures**: Queries that exceed memory limits are terminated and return an error instead of results.
* **Resource constraints**: Query workers have fixed memory allocations. Memory-intensive operations can exhaust these allocations.
* **User experience**: Failed queries provide no results and require query optimization to succeed.
When a query exceeds memory limits, Axiom returns an HTTP 432 error with a message indicating memory constraints.
### How to fix it [#how-to-fix-it-5]
#### Optimize `parse_json()` usage [#optimize-parse_json-usage]
`parse_json()` can consume significant memory when parsing large JSON strings, especially when applied to many rows.
* **Use map fields at ingest time:** Instead of storing JSON as strings and parsing at query time, ingest JSON data as [map fields](/apl/data-types/map-fields#map-fields). Map fields are stored columnar and don’t require runtime parsing:
Instead of:
```kusto
['logs']
| extend parsed = parse_json(json_payload)
| where parsed.status == "error"
```
Ingest `json_payload` as a map field and query directly:
```kusto
['logs']
| where json_payload.status == "error"
```
* **Extract frequently used fields:** Extract only the fields you need rather than parsing entire objects:
```kusto
['logs']
| extend status = parse_json(json_payload).status
| where status == "error"
```
* **Filter before parsing:** Apply filters to reduce the dataset size before using `parse_json()`:
```kusto
['logs']
| where json_payload contains "error"
| extend parsed = parse_json(json_payload)
| where parsed.status == "error"
```
#### Optimize `pack(*)` usage [#optimize-pack-usage]
`pack(*)` creates a dictionary from all fields in each row, which can consume significant memory on wide datasets (datasets with many fields).
* **Use `pack` with specific fields:** Instead of packing all fields, pack only the fields you need:
Instead of:
```kusto
['logs']
| extend event = pack(*)
```
Use:
```kusto
['logs']
| extend event = pack('timestamp', _time, 'level', level, 'message', message)
```
Or use `pack_dictionary()` for explicit key-value pairs:
```kusto
['logs']
| extend event = pack_dictionary('timestamp', _time, 'level', level, 'message', message)
```
* **Use `project` to reduce fields first:** If you need to pack multiple fields, reduce the dataset width first:
```kusto
['logs']
| project _time, level, message, user_id
| extend event = pack(*)
```
* **Use map fields at ingest time** instead of using `pack(*)`. Instead of storing JSON as strings and parsing at query time, ingest JSON data as [map fields](/apl/data-types/map-fields#map-fields).
## Overly wide queries returning more fields than needed [#overly-wide-queries-returning-more-fields-than-needed]
### Problem [#problem-6]
By default, Axiom’s query engine projects all fields (`project *`) for each matching event. This can return large amounts of unneeded data, especially in wide datasets with many fields.
### Why it matters [#why-it-matters-6]
* **High I/O and memory usage**: Unnecessary data is scanned, read, and returned.
* **Slower queries**: Time is wasted processing fields you never use.
### How to fix it [#how-to-fix-it-6]
* **Use `project` or `project-keep`**
Specify exactly which fields you need. For example:
```kusto
dataset
| where status == 500
| project timestamp, error_code, user_id
```
* **Use `project-away` if you only need to exclude a few fields:** If you need 90% of the fields but want to exclude the largest ones, for instance:
```kusto
dataset
| project-away debug_payload, large_object_field
```
* **Limit your results**
If you only need a sample of events for debugging, use a lower `limit` value (such as 10) instead of the default 1000.
## Regular expressions when simple filters suffice [#regular-expressions-when-simple-filters-suffice]
### Problem [#problem-7]
Regular expressions (`matches`, `regex`) can be powerful, but they’re also expensive to evaluate, especially on large datasets.
### Why it matters [#why-it-matters-7]
* **High CPU usage**: Regex filters require complex per-row matching.
* **Slower queries**: Axiom scans large swaths of data with less efficient matching.
### How to fix it [#how-to-fix-it-7]
* **Use direct string filters**
Instead of:
```kusto
dataset
| where message matches "[Ff]ailed"
```
Use:
```kusto
dataset
| where message contains "failed"
```
* **Use `search` for substring search:**
To find `foobar` in all fields, use:
```kusto
dataset
| search "foobar"
```
`search` matches text in all fields. To find text in a specific field, a more efficient solution is to use the following:
```kusto
dataset
| where FIELD contains_cs "foobar"
```
In this example, `cs` stands for case-sensitive.
## Overusing runtime JSON parsing (`parse_json`) [#overusing-runtime-json-parsing-parse_json]
### Problem [#problem-8]
Some ingestion pipelines place large JSON payloads into a string field, deferring parsing until query time with `parse_json()`. This is both CPU-intensive and slower than columnar operations.
### Why it matters [#why-it-matters-8]
* **Repeated parsing overhead**: You pay a performance penalty on each query.
* **Limited indexing**: Axiom can’t index nested fields if they’re only known at query time.
### How to fix it [#how-to-fix-it-8]
* **Ingest as map fields:** Axiom’s new [map field type](/apl/data-types/map-fields#map-fields) can store object fields column by column, preserving structure and optimizing for nested queries. This allows indexing of specific nested keys.
* **Extract top-level fields where possible:** If a certain nested field is frequently used for filtering or grouping, consider promoting it to its own top-level field (for faster scanning and filtering). For more information, see [Extract top-level fields from log body](/send-data/kubernetes#extract-top-level-fields-from-log-body).
* **Avoid `parse_json()` in query:** If your JSON can’t be flattened entirely, ingest it into a map field. Then query subfields directly:
```kusto
dataset
| where data_map.someKey == "someValue"
```
## Virtual fields for simple transformations [#virtual-fields-for-simple-transformations]
### Problem [#problem-9]
You can create virtual fields (for example, `extend converted = toint(some_field)`) to transform data at query time. While sometimes necessary, every additional virtual field imposes overhead.
### Why it matters [#why-it-matters-9]
* **Increased CPU**: Each virtual field requires interpretation by Axiom’s expression engine.
* **Slower queries**: Overuse of `extend` for trivial or frequently repeated operations can add up.
### How to fix it [#how-to-fix-it-9]
* **Avoid unnecessary casting:** If a field must be an integer, handle it at ingest time.
**Example:** Instead of
```kusto
dataset
| extend str_user_id = tostring(mixed_user_id)
| where str_user_id contains "123"
```
Use:
```kusto
| where mixed_user_id contains "123"
```
The filter automatically matches string values in mixed fields.
* **Reserve virtual fields for truly dynamic or derived logic**
If you frequently need a computed value, store it at ingest or keep the transformations minimal.
## Poor filter order in queries [#poor-filter-order-in-queries]
### Problem [#problem-10]
Axiom’s query engine doesn’t currently reorder your `where` clauses optimally. This means the sequence of filters in your query can matter.
### Why it matters [#why-it-matters-10]
* **Unnecessary scans**: If you use selective filters last, the engine may process many rows before discarding them.
* **Longer execution times**: CPU usage and scan times increase.
### How to fix it [#how-to-fix-it-10]
* **Put the most selective filters first:**
Example:
```kusto
dataset
| where user_id == 1234
| where log_level == "ERROR"
```
If `user_id == 1234` discards most rows, apply it before `log_level == "ERROR"`.
* **Profile your filters:** Experiment with which filters discard the most rows to find the most selective conditions.
---
# Configure user profile
Source: https://axiom.co/docs/reference/profile
## Change name [#change-name]
1. Click **Settings > Profile**.
2. Enter your name in the **Name** section.
## View contact details and base role [#view-contact-details-and-base-role]
1. Click **Settings > Profile**.
2. Find your your contact details and base role in the **Email** and **Role** sections.
## Change timezone [#change-timezone]
1. Click **Settings > Profile**.
2. Select your timezone in the **Timezone** section.
## Change editor mode [#change-editor-mode]
The editor mode determines the style of the APL query editor. To change this:
1. Click **Settings > Profile**.
2. Select your preferred editor in the **Editor mode** section.
## Select default method for null values [#select-default-method-for-null-values]
When you visualize your data, you can select how Axiom treats missing or undefined values in the chart. For more information, see [Configure dashboard elements](/dashboard-elements/configure#values). When you select a default method to deal with null values, Axiom uses this method in every new chart you create.
To select the default method for null values:
1. Click **Settings > Profile**.
2. Select your preferred editor in the **default method for null values** section.
## Manage personal access tokens [#manage-personal-access-tokens]
Create and delete personal access tokens (PATs). For more information, see [Personal access tokens](/reference/tokens#personal-access-tokens-pat).
## View and manage active sessions [#view-and-manage-active-sessions]
1. Click **Settings > Profile**.
2. View active sessions in the **Sessions** section.
3. Optional: To log out of a session, find the session in the list, and then click **Delete session** on the right.
## Delete user account [#delete-user-account]
This is a destructive action. After you delete your user account, you can’t recover it.
To delete your user account:
1. Click **Settings > Profile**.
2. Click **Delete account**.
---
# Organize resources with labels
Source: https://axiom.co/docs/reference/resource-labels
Resource labels help you organize related resources in an Axiom organization. For example, you can use labels such as `production`, `payments`, or `team-platform` to group resources by environment, service, or owner.
You can assign labels to the following resources:
* Datasets
* Saved and integration dashboards
* Monitors
* Notifiers
Labels are organization-wide definitions. Renaming a label or changing its color updates it everywhere it's assigned. Deleting a label removes the label from every assigned resource without deleting the resources.
Label assignments are explicit. Assigning a label to a dataset doesn't assign it to dashboards, monitors, or notifiers that use the dataset.
## Create label [#create-label]
To create a label for your organization:
1. Click **Settings > Labels**.
2. Click **Create label**.
3. Enter a unique name of up to 128 characters.
4. Optional: Enter a description of up to 512 characters.
5. Select a color. The color helps distinguish labels visually and doesn't change how filtering works.
6. Click **Create label**.
You can also create a label while assigning labels to a resource. In the label panel, enter the new label name, choose a color, and click **Create new label**. A label created this way remains available to the organization even if you cancel the resource form.
## Edit label [#edit-label]
To change the name, description, or color of a label:
1. Click **Settings > Labels**.
2. Find the label, and then click **Edit label**.
3. Make your changes.
4. Click **Save changes**.
## Delete label [#delete-label]
Deleting a label removes it from all assigned resources. You can't undo this action.
To delete a label:
1. Click **Settings > Labels**.
2. Find the label, and then click **Delete label**.
3. Click **Delete label** to confirm.
## Assign labels to a resource [#assign-labels-to-a-resource]
To change the labels assigned to an existing resource:
1. Open **Datasets**, **Dashboards**, **Monitors**, or **Notifiers**.
2. Open the resource's context menu. For example, right-click the resource row.
3. Select **Labels**.
4. Select labels to assign them, or clear selected labels to remove them. Changes save immediately.
The label panel lists assigned labels first. Use its search field to find labels by name. Click **Manage labels** to open **Settings > Labels** in a new tab.
When you create or edit a dataset, dashboard, or monitor, you can also change its labels in the form. These changes take effect when you save the resource. If you duplicate, fork, or clone a supported resource, Axiom copies its label assignments to the new resource. Later changes to either resource's assignments are independent.
## Filter resources by label [#filter-resources-by-label]
The **Datasets**, **Dashboards**, **Monitors**, and **Notifiers** pages have a **Labels** section in the left sidebar.
Select a label to show resources assigned that label. If you select several labels, Axiom shows only resources assigned all of them. The number next to each label counts resources that also match the page's other active filters.
Selected labels move to the top of the section. Click **Clear** to remove all label filters. Your selection is stored in the page URL, so reloading or sharing the URL preserves the filter.
## Label permissions [#label-permissions]
Label definitions and label assignments use separate permissions:
* The **Labels** capability controls whether you can read, create, update, or delete organization-wide label definitions.
* The update capability for a resource controls whether you can change that resource's label assignments. For example, assigning labels to a monitor requires **Monitors: Update**.
You can't change label assignments on a reserved dataset, a dataset shared from another organization, or a dataset you can't write to. If you can view a resource but can't update it, its labels remain visible and the label assignment control isn't available.
For more information, see [Role-Based Access Control](/reference/settings#assign-capabilities-to-roles).
---
# Semantic conventions
Source: https://axiom.co/docs/reference/semantic-conventions
[OpenTelemetry semantic conventions](https://opentelemetry.io/docs/specs/semconv/) specify standard attribute names and values for different kinds of operations and data.
## Trace attributes in Axiom [#trace-attributes-in-axiom]
The OTel trace attributes you send to Axiom are available under the following fields:
* Attributes that follow semantic conventions are nested fields under the `attributes` field. For example, `attributes.http.method` or `attributes.http.url`.
* Resource attributes that follow semantic conventions are nested fields under the `resource` field. For example, `resource.host.name` or `resource.host.id`.
* Custom attributes that don’t match any semantic conventions are nested fields under the `attributes.custom` map field.
For more information on map fields and querying nested fields, see [Map fields](/apl/data-types/map-fields).
## Supported versions [#supported-versions]
For the versions of OTel semantic conventions that Axiom supports, see [System requirements](/reference/system-requirements#opentelemetry).
(Recommended) When you send OTel data to Axiom, include the version of the OTel semantic conventions that your data follows. This ensures that your data is properly shaped in Axiom.
If you don’t define the version and Axiom can’t detect it, Axiom defaults to the version specified in [System requirements](/reference/system-requirements#opentelemetry). In this case, Axiom nests attributes that don’t match the semantic conventions of the default version under the `attributes.custom` map field.
## Semantic conventions upgrades [#semantic-conventions-upgrades]
To guarantee the best logging experience with OTel, Axiom regularly updates the list of supported versions of semantic conventions and sometimes the default version. These updates can change the shape of your data. Axiom announces these changes in the [Changelog](https://axiom.co/changelog) and you might need to take action:
* If you send data to Axiom using an unsupported version of OTel semantic conventions, be aware that the shape of your data can change when Axiom adds support for new versions.
* When you send OTel data to Axiom, include the version of the OTel semantic conventions that your data follows. This ensures that your data is properly shaped in Axiom and it won’t be affected when Axiom changes the default version.
In addition, the shape of your data can change when you choose to migrate to a newer version of OTel semantic conventions.
See the sections below for more details on how your data can change and the actions you need to take when this happens.
### Changes to list of supported versions [#changes-to-list-of-supported-versions]
After Axiom adds support for new versions of OTel semantic conventions, the shape of your data can change when the following are all true:
* Before the update, you sent data to Axiom using an unsupported version of OTel semantic conventions.
* After the update, the version of OTel semantic conventions that you used becomes supported.
In this case, the shape of your data can change:
* Before the update, attributes that Axiom couldn’t match to the previously supported semantic conventions were nested under the `attributes.custom` map field.
* After the update, Axiom matches these attributes to the newly supported semantic conventions. The newly recognized attributes are nested under the `attributes` or `resource` fields, similarly to all other attributes that follow semantic conventions.
When the shape of your data changes, you need to [take action](#take-action-when-shape-of-data-changes).
### Changes to default version [#changes-to-default-version]
If you don’t specify the version of the OTel semantic conventions that your data follows when you send OTel data to Axiom, Axiom interprets the data using the default version.
After Axiom changes the default version of OTel semantic conventions, the shape of your data can change when you don’t specify the version of the OTel semantic conventions in the data you send to Axiom. For this reason, to prevent changes to your data, include the version of the OTel semantic conventions that your data follows when you send OTel data to Axiom. This ensures that your data is properly shaped in Axiom and it won’t be affected when Axiom changes the default version.
When Axiom updates the default version of OTel semantic conventions, the shape of your data can change:
* Before the update, attributes that become supported between the old and the new default versions are nested under the `attributes.custom` field. After the update, these attributes are nested under the `attributes` or `resource` fields.
* Before the update, attributes that became deprecated between the old and the new default versions are nested under the `attributes` or `resource` fields. After the update, these attributes are nested under the `attributes.custom` field.
When the shape of your data changes, you need to [take action](#take-action-when-shape-of-data-changes).
### Migrate to new version [#migrate-to-new-version]
When you choose to migrate to a newer version of OTel semantic conventions, the shape of your data can change. Some attributes can become supported, deprecated, renamed, or relocated.
When the shape of your data changes, you need to [take action](#take-action-when-shape-of-data-changes).
### Determine changes between versions [#determine-changes-between-versions]
To determine the changes between different versions of OTel semantic conventions, compare the [schema files](https://github.com/open-telemetry/semantic-conventions/tree/main/schemas) or the [changelog](https://github.com/open-telemetry/semantic-conventions/releases) in the OTel documentation. This informs you about how the shape of your data can change as a result of semantic conventions upgrades.
## Take action when shape of data changes [#take-action-when-shape-of-data-changes]
When some attributes are relocated or renamed, the shape of your data changes and you need to take action.
For example, assume that Axiom supports OTel semantic conventions up to version 1.25. You send data to Axiom that follows version 1.32 and you don’t specify the version. On June 12th 2025, Axiom adds support for versions up to 1.32 and makes version 1.32 the default. The following happens with the attribute `db.system.name`:
* You send the attribute `db.system.name` to Axiom because your data follows version 1.32. The shape of the data you send to Axiom doesn’t change during the update.
* Before the update, Axiom interpreted your data using the old default version 1.25. It didn’t recognize `db.system.name` and nested it under `attributes.custom`.
* After the update, Axiom interprets your data using the new default version 1.32. It recognizes `db.system.name` properly and nests it under `attributes`.
As a result, the attribute is relocated from `['attributes.custom']['db.system.name']` to `['attributes.db.system.name']`. You need to update all saved queries, dashboards, or monitors that reference the attribute. You have the following options:
* [Update queries to reference the new location](#reference-new-location)
* [Update queries to reference both locations](#reference-both-locations)
### Reference new location [#reference-new-location]
When you update affected queries to reference the new location, the query results only include data you send after the semantic conventions upgrade.
For example, a saved query references the old location before the update:
```kusto
['otel-demo-traces']
| where ['service.name'] == "frontend"
| project ['attributes.custom']['db.system.name']
```
After the update, change the query to the following:
```kusto
['otel-demo-traces']
| where ['service.name'] == "frontend"
| project ['attributes.db.system.name']
```
### Reference both locations [#reference-both-locations]
To ensure that affected queries include data from the attribute that you send before and after the semantic conventions upgrade, use [coalesce](/apl/scalar-functions/string-functions#coalesce) in your query. This function evaluates a list of expressions and returns the first non-null value. In this case, pass the old and the new locations of the attribute to the `coalesce` function.
For example, a saved query references the old location before the update:
```kusto
['otel-demo-traces']
| where ['service.name'] == "frontend"
| project ['attributes.custom']['db.system.name']
```
After the update, change the query to the following:
```kusto
['otel-demo-traces']
| where ['service.name'] == "frontend"
| project coalesce(['attributes.custom']['db.system.name'], ['attributes.db.system.name'])
```
---
# Role-Based Access Control
Source: https://axiom.co/docs/reference/settings
Role-Based Access Control (RBAC) allows you to manage and restrict access to your data and resources efficiently. You can control access to your data with the following:
* [Groups](#groups)
* [Roles](#roles)
* [Users](#users)
* [Directory Sync](#directory-sync)
* [Single Sign-On (SAML SSO)](#single-sign-on-saml-sso)
Role-Based Access Control (RBAC), Directory Sync, and Single Sign-On (SAML SSO) are available as add-ons on the Axiom Cloud plan. For more information, see [Manage add-ons](/reference/usage-billing#manage-add-ons).
## Groups [#groups]
Groups connect users with roles, making it easier to manage access control at scale. For example, you can create groups for areas of your business like Security, Infrastructure, or Business Analytics, with specific roles assigned to serve the unique needs of these domains.
A user’s complete set of capabilities is derived from the additive union of their base role, plus any roles assigned through group membership.
### Create new group [#create-new-group]
1. Click **Settings > Groups**
2. Click **New group**.
3. Enter the name and description of the group.
4. Click **Add users** to add users to the group.
5. Click **Add roles** to add roles to the group.
## Roles [#roles]
Roles are sets of capabilities that define which actions a user can perform at both the organization and dataset levels.
### Default roles [#default-roles]
The default roles are the following:
* **Owner:** Assigns all capabilities across the entire Axiom platform.
* **Admin:** Assigns administrative capabilities except for Billing capabilities, which are reserved for Owners.
* **User:** Assigns standard access for regular users.
* **Read-only:** Assigns read capabilities for datasets, plus read access on various resources like dashboards, monitors, notifiers, users, queries, saved queries, and virtual fields.
* **None:** Assigns zero capabilities, useful for adopting the principle of least privilege when inviting new users. You can build up specific capabilities for these users by assigning their role to a group.
### Create custom role [#create-custom-role]
1. Ensure you have create permission for the access control capability. By default, this capability is assigned to the Owner and Admin roles.
2. Click **Settings > Roles**.
3. Click **New role**.
4. Enter the name and description of the role.
5. Assign permissions (create, read, update, and delete) across capabilities (access control, API tokens, dashboards, datasets, etc.).
### Assign capabilities to roles [#assign-capabilities-to-roles]
You can assign organization-level and dataset-level capabilities to roles. You can assign create, read, update, or delete (CRUD) permissions to most capabilities.
Organization-level capabilities define access for various parts of your Axiom organization:
* **Access control:** Full CRUD.
* **Annotations:** Full CRUD.
* **API tokens:** Full CRUD.
* **Apps:** Full CRUD.
* **Audit log:** Read only.
* **Billing:** Read and update only.
* **Dashboards:** Full CRUD.
* **Datasets:** Full CRUD.
* **Labels:** Full CRUD.
* **Monitors:** Full CRUD.
* **Notifiers:** Full CRUD.
* **Shared access keys:** Read and update only.
* **Users:** Full CRUD.
* **Views:** Full CRUD.
The table below describes these organization-level capabilities:
| Capability | Create | Read | Update | Delete |
| ------------------ | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| Access control | User can create custom roles and groups. | User can view the list of existing roles and groups. | User can update the and description of roles and groups, and modify permissions. | User can delete custom roles or groups. |
| Annotations | User can create annotations. | User can view the list of existing annotations in an organization. | User can modify annotations. | User can delete annotations. |
| API tokens | User can create an API token with access to the datasets their user has access to. | User can access the list of tokens that have been in their organization. | User can regenerate a token from the list of tokens in an organization. | User can delete API tokens created in their organization. |
| Apps | User can create a new app. | Users can access the list of installed apps in their organization. | Users can modify the existing apps in their organization. | User can disconnect apps installed in their organization. |
| Audit log | — | Users can access the audit log in an organization. | — | — |
| Billing | — | User can access billing settings. | User can change the organization plan. | — |
| Dashboards | User can create new dashboards. | User can access their own dashboards and those created by other users in their organization. | User can modify dashboard titles and descriptions. User can add, resize, and delete charts from dashboards. | User can delete a dashboard from their organization. |
| Datasets | User can create a new dataset. | Users can access the list of datasets in an organization, and their associated fields. | User can trim a dataset, and modify dataset fields. | User can delete a dataset from their organization. |
| Labels | User can create organization-wide resource labels. | User can view the labels in an organization. | User can change a label's name, description, and color. | User can delete a label and remove it from all assigned resources. |
| Monitors | User can create a monitor. | User can access the list of monitors in their organization. User can also review the monitor status. | Users can modify a monitor configuration in their organization. | Users can delete monitors that have been created in their organization. |
| Notifiers | User can create a new notifier in their organization. | User can access the list of notifiers in their organization. | User can update existing notifiers in their organization. User can snooze a notifier. | User can delete notifiers that have been created in their organization. |
| Shared access keys | — | User can access shared access keys in their organization. | User can update shared access keys in their organization. | — |
| Users | Users can invite new users to an organization. | User can access the list of users that are part of their organization. | User can update user roles and information within the organization. | Users can remove other users from their organization and delete their own account. |
| Views | User can create new views. | User can access the list of views in an organization in their organization. | User can modify views. | User can delete views from their organization. |
Dataset-level capabilities provide fine-grained control over access to datasets. You can assign the following capabilities for all datasets or individual datasets:
* **Data:** Delete only.
* **Ingest:** Create only.
* **Query:** Read only.
* **Share:** Create, read, and update only.
* **Saved queries:** Full CRUD.
* **Trim:** Update only.
* **Vacuum:** Update only.
* **Virtual fields:** Full CRUD.
The table below describes these dataset-level capabilities:
| Datasets | Create | Read | Update | Delete |
| -------------- | ------------------------------------------- | ------------------------------------------------------------------ | ----------------------------------------------------------------- | --------------------------------------------- |
| Data | — | — | — | — |
| Ingest | User can ingest events to datasets. | — | — | User can delete data from datasets. |
| Query | — | User can query events from datasets. | — | — |
| Share | User can share datasets. | User can access the list of shared datasets in their organization. | User can modify an existing shared dataset in their organization. | — |
| Saved queries | User can create a saved query for datasets. | User can access the list of saved queries in their organization. | User can modify an existing saved query in their organization. | User can delete a saved query from a dataset. |
| Trim | — | — | User can trim datasets. | — |
| Vacuum | — | — | User can vacuum datasets and delete fields from datasets. | — |
| Virtual fields | User can create a new virtual field. | User can see the list of virtual fields. | User can modify the definition of a virtual field. | User can delete a virtual field. |
## Users [#users]
Users in Axiom are the individual accounts that have access to an Axiom organization. You assign a base role to users when you invite them to join your organization. For organizations with the role-based access control (RBAC) add-on, additional roles can be added through group membership.
### Assign roles to users [#assign-roles-to-users]
1. Click **Settings > Users**.
2. Find the user in the list, and then assign a role to them on the right.
Access for a user is the additive union of capabilities assigned through their default role, plus any capabilities included in roles assigned through group membership.
### Delete users [#delete-users]
This is a destructive action. After you delete a user, you can’t recover their account.
1. Click **Settings > Users**.
2. Find the user in the list, and then click **Delete user** on the right.
## Directory Sync [#directory-sync]
Directory Sync automatically mirrors user account data between a central directory, such as Active Directory, and connected applications. When the status of an employee changes, all systems are automatically updated.
For this feature, Axiom relies on WorkOS. For more information, see [Directory Sync](https://workos.com/directory-sync) and [Supported vendors](https://workos.com/docs/integrations) in the WorkOS documentation.
## Single Sign-On (SAML SSO) [#single-sign-on-saml-sso]
To simplify access management and enhance security, Security Assertion Markup Language-based Single Sign-On (SAML SSO) allows you to keep access grants up-to-date with support for the industry standard SCIM protocol.
Axiom supports secure, centralized user authentication through both types of flow for SAML-based SSO:
* IdP-initiated flow (identity-provider-initiated flow)
* SP-initiated flow (service-provider-initiated flow)
Two-factor authentication (2FA) is a security feature that requires users to provide two forms of identification before accessing their accounts. You can turn on 2FA for users logging in through SAML SSO and enforce it through your identity provider. Axiom doesn’t offer 2FA natively.
For this feature, Axiom relies on WorkOS:
1. Axiom provisions an organization for you in WorkOS, connects it to your Axiom organization, and turns on SSO.
2. Axiom provides you with a setup link to your WorkOS organization.
3. You follow the instructions using the setup link. The setup requires the following attributes for your users:
* `idp_id`
* `first_name`
* `last_name`
* `email`
For more information, see [Enterprise Single Sign-On](https://workos.com/single-sign-on) and [Supported vendors](https://workos.com/docs/integrations) in the WorkOS documentation.
---
# System requirements
Source: https://axiom.co/docs/reference/system-requirements
## Browsers and platforms [#browsers-and-platforms]
The Axiom web app supports the latest versions of the following browsers and platforms:
| | Android | iOS | macOS | Linux | Windows |
| :------ | :------ | :-- | :---- | :---- | :------ |
| Chrome | ✓ | ✓ | ✓ | ✓ | ✓ |
| Edge | ✓ | ✓ | ✓ | ✓ | ✓ |
| Firefox | ✓ | ✓ | ✓ | ✓ | ✓ |
| Safari | - | ✓ | ✓ | - | - |
Some actions in the Dashboards tab, such as moving dashboard elements, aren’t supported in mobile view.
## OpenTelemetry [#opentelemetry]
### Semantic conventions [#semantic-conventions]
Axiom supports the following versions of OTel semantic conventions:
| Version | Date when supported added | Schema in OTel docs |
| :--------------- | :------------------------ | :---------------------------------------------------------------------------------------- |
| 1.37.0 | 11-09-2025 | [1.37.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.37.0) |
| 1.36.0 | 11-09-2025 | [1.36.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.36.0) |
| 1.34.0 | 01-07-2025 | [1.34.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.34.0) |
| 1.33.0 (default) | 01-07-2025 | [1.33.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.33.0) |
| 1.32.0 | 12-06-2025 | [1.32.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.32.0) |
| 1.31.0 | 12-06-2025 | [1.31.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.31.0) |
| 1.30.0 | 12-06-2025 | [1.30.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.30.0) |
| 1.28.0 | 12-06-2025 | [1.28.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.28.0) |
| 1.27.0 | 12-06-2025 | [1.27.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.27.0) |
| 1.26.0 | 03-07-2024 | [1.26.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.26.0) |
| 1.25.0 | 26-04-2024 | [1.25.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.25.0) |
| 1.24.0 | 19-01-2024 | [1.24.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.24.0) |
| 1.23.1 | 26-03-2024 | [1.23.1](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.23.1) |
| 1.23.0 | 26-03-2024 | [1.23.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.23.0) |
| 1.22.0 | 26-03-2024 | [1.22.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.22.0) |
| 1.21.0 | 26-03-2024 | [1.21.0](https://github.com/open-telemetry/semantic-conventions/blob/main/schemas/1.21.0) |
Version 1.29.0 and version 1.35.0 of OTel semantic conventions aren’t supported.
For more information, see [Semantic conventions](/reference/semantic-conventions).
### Logs, traces, and metrics [#logs-traces-and-metrics]
| OpenTelemetry component | Support |
| ------------------------------------------------------------------ | ------- |
| [Logs](https://opentelemetry.io/docs/concepts/signals/logs/) | ✓ |
| [Traces](https://opentelemetry.io/docs/concepts/signals/traces/) | ✓ |
| [Metrics](https://opentelemetry.io/docs/concepts/signals/metrics/) | ✓ |
---
# Authenticate API requests with tokens
Source: https://axiom.co/docs/reference/tokens
This reference article explains how you can authenticate your requests to the Axiom API with tokens.
## Why authenticate with tokens [#why-authenticate-with-tokens]
You can use the Axiom API and CLI to programmatically ingest and query data, and manage settings and resources. For example, you can create new API tokens and change existing datasets with API requests. To prove that these requests come from you, you must include forms of authentication called tokens in your API requests. Axiom offers two types of tokens:
* [API tokens](#api-tokens) let you control the actions that can be performed with the token. For example, you can specify that requests authenticated with a certain API token can only query data from a particular dataset.
* [Personal access tokens (PATs)](#personal-access-tokens-pat) provide full control over your Axiom account. Requests authenticated with a PAT can perform every action you can perform in Axiom. When possible, use API tokens instead of PATs.
Keep tokens confidential. Anyone with these forms of authentication can perform actions on your behalf such as sending data to your Axiom dataset.
When working with tokens, use the principle of least privilege:
* Assign only those privileges to API tokens that are necessary to perform the actions that you want.
* When possible, use API tokens instead of PATs because PATs have full control over your Axiom account.
For more information on how to use tokens in API requests, see [Get started with Axiom API](/restapi/introduction).
## API tokens [#api-tokens]
You can use two types of API tokens in Axiom:
* Basic API tokens let you ingest data to Axiom. When you create a basic API token, you select the datasets that you allow the basic API token to access.
* Advanced API tokens let you perform a wide range of actions in Axiom beyond ingesting data. When you create an advanced API token, you select which actions you allow the advanced API token to perform. For example, you can create an advanced API token that can only query data from a particular dataset and another that has wider privileges such as creating datasets and changing existing monitors.
After creating an API token, you can’t change the privileges assigned to that API token.
### Create basic API token [#create-basic-api-token]
1. Click **Settings > API tokens**, and then click **New API token**.
2. Name your API token.
3. Optional: Give a description to the API token and set an expiration date.
4. In **Token permissions**, click **Basic**.
5. In **Dataset access**, select the datasets where this token can ingest data.
6. Click **Create**.
7. Copy the API token that appears and store it securely. It won’t be displayed again.
### Create advanced API token [#create-advanced-api-token]
1. Click **Settings > API tokens**, and then click **New API token**.
2. Name your API token.
3. Optional: Give a description to the API token and set an expiration date.
4. In **Token permissions**, click **Advanced**.
5. In **Advanced permissions**, choose one of the following options:
* Select **Custom** and define your own permission set. This allows you to select the datasets that this token can access and the actions it can perform. In **Org level permissions**, you can select the actions the token can perform that affect your whole Axiom organisation. For example, creating users and changing existing notifiers.
* Select one of the presets to auto-populate a predefined set of capabilities. For example, **Preset - Evaluations** allows an SDK to write evaluation traces and query comparison data.
6. Click **Create**.
7. Copy the API token that appears and store it securely. It won’t be displayed again.
### Limit query costs of an API token [#limit-query-costs-of-an-api-token]
You can cap the hourly and daily query costs of an API token, in dollars. When the token exceeds a limit, its query requests fail with HTTP status code `429` until the window resets. Ingest and other operations are unaffected. This is particularly useful for tokens you give to AI agents.
To set limits when you create a token, enter an hourly limit, a daily limit, or both in **Query cost limits**. To add or change limits on an existing token, click **Settings > API tokens**, select the token, and then edit **Query cost limits**. The token page shows the token’s current usage against each limit.
For more information, see [Set query cost limits for AI agents](/console/intelligence/query-cost-limits).
### Regenerate API token [#regenerate-api-token]
Similarly to passwords, it’s recommended to change API tokens regularly and to set an expiration date after which the token becomes invalid. When a token expires, you can regenerate it.
To regenerate an advanced API token, follow these steps:
1. Click **Settings > API tokens**.
2. In the list, select the API token you want to regenerate.
3. Click **Regenerate token**.
4. Copy the regenerated API token that appears and store it securely. It won’t be displayed again.
5. Update all the API requests where you use the API token with the regenerated token.
### Delete API token [#delete-api-token]
1. Click **Settings > API tokens**.
2. In the list, hold the pointer over the API token you want to delete.
3. To the right, click **Delete**.
## Personal access tokens (PAT) [#personal-access-tokens-pat]
Personal access tokens (PATs) provide full control over your Axiom account. Requests authenticated with a PAT can perform every action you can perform in Axiom. When possible, use API tokens instead of PATs.
### Create PAT [#create-pat]
1. Click **Settings > Profile**.
2. In the **Personal tokens** section, click **New token**.
3. Name the PAT.
4. Optional: Give a description to the PAT.
5. Copy the PAT that appears and store it securely. It wont be displayed again.
### Delete PAT [#delete-pat]
1. Click **Settings > Profile**.
2. In the list, find the PAT that you want to delete.
3. To the right of the PAT, click **Delete**.
## Determine organization ID [#determine-organization-id]
If you authenticate requests with a PAT, you must include the organization ID in the requests. For more information on including the organization ID in the request, see [Axiom API](/restapi/introduction) and [Axiom CLI](/reference/cli).
Determine the organization ID in one of the following ways:
* Click **Settings**, and then copy the organization ID in the top right corner.
* Click **Settings > General**, and then find the **ID** section.
* Go to the [Axiom app](https://app.axiom.co/) and check the URL. For example, in the URL `https://app.axiom.co/axiom-abcd/datasets`, the organization ID is `axiom-abcd`.
---
# Usage and billing
Source: https://axiom.co/docs/reference/usage-billing
## Billing [#billing]
To view details about your next and last bill, go to **Settings > Billing**.
The Current breakdown section explains what you paid for in your last bill and what you can expect to pay for in your next bill.
### View billing history [#view-billing-history]
To view details about your billing history:
1. Go to **Settings > Billing**.
2. In the Current breakdown section, click **Billing history**.
### Compute credits [#compute-credits]
You can save on compute spending by pre-purchasing compute credits. This means that you purchase credits in advance at a discount. The more credits you purchase, the higher the discount rate. For more information, see [Pricing](https://axiom.co/pricing).
Your compute credits can cover the following costs:
* Data loading
* Query compute
Your compute credits can’t cover the following costs:
* Your pricing plan
* Add-ons
* Storage
To purchase compute credits:
1. Ensure you have permissions to modify billing. For more information, see [Role-Based Access Control](/reference/settings).
2. Go to **Settings > Billing**.
3. In the Compute credits section, click **Add credits**.
4. Enter the amount of credits you want to purchase.
5. Review the total cost.
6. Click **Buy credits**.
7. Complete the purchase.
### Spending limit [#spending-limit]
Setting a monthly spending limit allows you to control costs.
Axiom continuously tracks your current billing cycle’s projected costs. To determine your accumulated charges, Axiom considers all costs, including the base cost of your plan, usage costs, and the costs of any add-ons you have purchased. When your accumulated charges reach your spending limit, Axiom automatically pauses actions that generate further costs. This can cause interruptions to your service.
For example, if you have used up the query compute allowance included in your pricing plan, you can’t run queries and your monitors can’t query your data. At the same time, if you haven’t yet used up the data loading allowance, you can still ingest data.
Even if you reach your spending limit, you can still initiate purchases manually such as buying add-ons and credits.
The spending limit applies to your whole organization. To cap the query costs of individual API tokens or members instead, for example for AI agents, set [query cost limits](/console/intelligence/query-cost-limits) on API tokens and roles.
To set a monthly spending limit:
1. Ensure you have permissions to modify billing. For more information, see [Role-Based Access Control](/reference/settings).
2. Go to **Settings > Billing**.
3. In the Limit section, click **Manage limit**.
4. Turn on **Set monthly spending limit**.
5. Enter the maximum monthly spending.
6. Click **Save changes**.
If your organization reaches the spend limit, Axiom sends an email to the owner of your organization. To avoid further interruptions to your service, increase the spend limit. Your service resumes until usage-related costs reach the amount by which you increased the limit. The spend limit resets in the next billable period as usual.
## Pricing plan [#pricing-plan]
### View plan details [#view-plan-details]
To view details about your current plan:
1. Go to **Settings > Plan**.
2. Click **License**.
This page gives you an overview of the allowances included in your plan and your current monthly usage.
### Upgrade or downgrade plan [#upgrade-or-downgrade-plan]
To upgrade or downgrade your plan:
1. Ensure you have permissions to modify billing. For more information, see [Role-Based Access Control](/reference/settings).
2. Go to **Settings > Plan**.
3. Click **More > Upgrade** or **More > Downgrade**.
### Manage add-ons [#manage-add-ons]
You can manage the following add-ons:
* Additional edge deployments
* [Audit log](/reference/audit-log)
* [Directory Sync](/reference/settings#directory-sync)
* [Role-Based Access Control (RBAC)](/reference/settings)
* [SAML Single Sign-On (SSO)](/reference/settings#single-sign-on-saml-sso)
To manage add-ons:
1. Ensure you have permissions to modify billing. For more information, see [Role-Based Access Control](/reference/settings).
2. Go to **Settings > Plan**.
3. Click the add-on area.
4. Select or deselect add-ons.
5. Review the updated base monthly cost.
6. Click **Update add-ons**.
## Usage [#usage]
To view details about your organization’s total usage of Axiom:
1. Click **Settings > Usage**.
2. To select the period for which you want to display usage, click **Time range**.
The Usage page displays:
* **Ingest**: The total amount of data ingested to Axiom.
* **Query**: The total amount of query compute resources used to run queries.
* **Storage**: The amount of data stored in each of your datasets, broken down by [access tier](/reference/optimize-usage#adaptive-tiering).
### Monitor usage in detail [#monitor-usage-in-detail]
For more granular usage monitoring, query the [audit log](/reference/audit-log). The audit log captures hourly usage data and allows you to:
* Track ingestion by dataset over time.
* Identify high-cost queries.
* Monitor which monitors consume the most query resources.
* Detect ingestion spikes.
---
# Axiom and Splunk
Source: https://axiom.co/docs/splunk/overview
Axiom connects to Splunk in two ways. Both let your team work with Axiom data from the Splunk interface they already know, without moving or duplicating data. The work of filtering and aggregating happens inside Axiom, and Splunk receives compact results it can shape, chart, and alert on.
* The **[Axiom for Splunk app](/splunk/app/setup)** adds a set of `ax` commands to SPL. You query Axiom datasets explicitly from any Splunk search, enrich existing Splunk events with Axiom context, and run raw APL when you need the full Axiom query language. Any Splunk user can install and configure it with an Axiom API token.
* The **[Axiom Portal for Splunk](/splunk/portal/overview)** registers with your Splunk deployment as a federated search provider and makes Axiom datasets appear as ordinary Splunk indexes, addressed as `index=federated:` or, in transparent mode, directly by name as `index=`. Your team searches them in plain SPL, and existing dashboards, saved searches, and alerts work unchanged. A Splunk admin sets it up once for the whole deployment.
## Choose between the app and the Portal [#choose-between-the-app-and-the-portal]
The two integrations solve different problems and work well together in the same deployment.
| | Axiom for Splunk app | Axiom Portal for Splunk |
| ---------------------------------------------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------- |
| Query syntax | New `ax` commands, plus raw APL | Plain SPL: `index=federated:`, or `index=` in transparent mode |
| Existing dashboards and saved searches | Adapt them to use `ax` commands | Work unchanged |
| Setup | Any user installs the app with an API token | Splunk admin configures a federated provider |
| Enrich existing Splunk events with Axiom data | Yes, with the purpose-built `axlookup` command | Yes, with standard SPL patterns like `join` and subsearches |
| Full APL access | Yes, with `axquery` | No |
| Splunk lookups and data models over Axiom data | No | Yes, in transparent mode |
| OCSF data as CIM data models and Enterprise Security | No | Yes, in transparent mode |
| Suited to | Analysts who mix Axiom and Splunk data in one pipeline | Teams who live in Splunk and want Axiom data to feel native |
Choose the **app** when:
* You want to get started without changing Splunk deployment settings. Installing the app doesn’t require federation configuration.
* You want to enrich events that are already in Splunk with context from Axiom. The `axlookup` command joins Axiom fields onto Splunk search results in one streaming command, with batching and field normalization handled for you.
* You want the full power of APL from inside Splunk. The `axquery` command runs any APL query and returns the results as Splunk events.
Choose the **Portal** when:
* Your team already has Splunk dashboards, saved searches, and alerts, and you want them to run against Axiom data without edits.
* End users shouldn’t have to learn anything new. Axiom datasets appear as indexes, and everyone keeps writing the SPL they know.
* You use Splunk knowledge objects like lookups and data models and want them to work against Axiom data. Transparent mode supports this.
* You store security data in Axiom in OCSF format and want CIM data models, `tstats`, and Enterprise Security detections to run against it. For more information, see [Search OCSF data as Splunk CIM](/splunk/portal/ocsf-cim).
A useful way to remember the difference: the app brings Axiom’s query language into your Splunk searches, and the Portal brings Axiom datasets into Splunk itself.
## What happens to your data [#what-happens-to-your-data]
Neither integration copies data into Splunk. Axiom stores and queries your event data, and Splunk receives results.
Both integrations push the expensive work down into Axiom. An aggregation like a count by service over billions of events runs inside Axiom and returns a handful of rows to Splunk. Results are exact, not sampled, at any dataset size. For more information on how work is divided between Axiom and the Splunk search head, see [How the Portal works](/splunk/portal/overview).
Access is controlled with Axiom API tokens. Each integration authenticates with a token that has query permissions on the datasets you choose to expose. Revoke the token, and access is gone. For more information, see [Tokens](/reference/tokens).
## What’s next [#whats-next]
* [Install and configure the Axiom for Splunk app](/splunk/app/setup)
* [Set up the Axiom Portal for Splunk](/splunk/portal/set-up-standard)
* [Search OCSF security data from Splunk](/splunk/portal/ocsf)
* [Translate SPL to APL](/apl/guides/splunk-cheat-sheet)
---
# Send data from Amazon Data Firehose to Axiom
Source: https://axiom.co/docs/send-data/aws-firehose
Amazon Data Firehose is a service for delivering real-time streaming data to different destinations. Send event data from Amazon Data Firehose to Axiom to analyse and monitor your data efficiently.
* [Create an account on AWS Cloud](https://signin.aws.amazon.com/signup?request_type=register).
## Setup [#setup]
1. In Axiom, determine the ID of the dataset you’ve created.
2. In Amazon Data Firehose, create an HTTP endpoint destination. For more information, see the [Amazon Data Firehose documentation](https://docs.aws.amazon.com/firehose/latest/dev/create-destination.html#create-destination-http).
3. Set HTTP endpoint URL to `https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME/firehose`.
4. Set the access key to the Axiom API token.
You have configured Amazon Data Firehose to send data to Axiom. Go to the Axiom UI and ensure your dataset receives events properly.
---
# Send data from AWS FireLens to Axiom
Source: https://axiom.co/docs/send-data/aws-firelens
AWS FireLens is a log routing feature for Amazon ECS. It lets you use popular open-source logging projects [Fluent Bit](https://fluentbit.io/) or [Fluentd](https://www.fluentd.org/) with Amazon ECS to route your logs to various AWS and partner monitoring solutions like Axiom without installing third-party agents on your tasks.
FireLens integrates with your Amazon ECS tasks and services seamlessly, so you can send logs from your containers to Axiom seamlessly.
## Use AWS FireLens with Fluent Bit and Axiom [#use-aws-firelens-with-fluent-bit-and-axiom]
Here’s a basic configuration for using FireLens with Fluent Bit to forward logs to Axiom:
## Fluent Bit configuration for Axiom [#fluent-bit-configuration-for-axiom]
You’ll typically define this in a file called `fluent-bit.conf`:
```ini
[SERVICE]
Log_Level info
[INPUT]
Name forward
Listen 0.0.0.0
Port 24224
[OUTPUT]
Name http
Match *
Host AXIOM_DOMAIN
Port 443
URI /v1/ingest/DATASET_NAME
Format json_lines
tls On
format json
json_date_key _time
json_date_format iso8601
Header Authorization Bearer API_TOKEN
```
Read more about [Fluent Bit configuration here](/send-data/fluent-bit)
## ECS task definition with FireLens [#ecs-task-definition-with-firelens]
You’ll want to include this within your ECS task definition, and reference the FireLens configuration type and options:
```json
{
"family": "myTaskDefinition",
"containerDefinitions": [
{
"name": "log_router",
"image": "amazon/aws-for-fluent-bit:latest",
"essential": true,
"firelensConfiguration": {
"type": "fluentbit",
"options": {
"config-file-type": "file",
"config-file-value": "/fluent-bit/etc/fluent-bit.conf"
}
}
},
{
"name": "myApp",
"image": "my-app-image",
"logConfiguration": {
"logDriver": "awsfirelens"
}
}
]
}
```
## Use AWS FireLens with Fluentd and Axiom [#use-aws-firelens-with-fluentd-and-axiom]
Create the `fluentd.conf` file and add your configuration:
```bash
@type forward
port 24224
bind 0.0.0.0
@type http
headers {"Authorization": "Bearer API_TOKEN"}
data_type json
endpoint https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME
sourcetype ecs
```
Read more about [Fluentd configuration here](/send-data/fluentd)
## ECS Task Definition for Fluentd [#ecs-task-definition-for-fluentd]
The task definition would be similar to the Fluent Bit example, but using Fluentd and its configuration:
```json
{
"family": "fluentdTaskDefinition",
"containerDefinitions": [
{
"name": "log_router",
"image": "YOUR_ECR_REPO_URI:latest",
"essential": true,
"memory": 512,
"cpu": 256,
"firelensConfiguration": {
"type": "fluentd",
"options": {
"config-file-type": "file",
"config-file-value": "/path/to/your/fluentd.conf"
}
}
},
{
"name": "myApp",
"image": "my-app-image",
"essential": true,
"memory": 512,
"cpu": 256,
"logConfiguration": {
"logDriver": "awsfirelens",
"options": {
"Name": "forward",
"Host": "log_router",
"Port": "24224"
}
}
}
]
}
```
By efficiently routing logs with FireLens and analyzing them with Axiom, businesses and development teams can save on operational overheads and reduce time spent on troubleshooting.
---
# Send data from AWS IoT to Axiom
Source: https://axiom.co/docs/send-data/aws-iot-rules
* Create an AWS account with permissions to create and manage IoT rules, Lambda functions, and IAM roles.
## Create AWS Lambda function [#create-aws-lambda-function]
Create a Lambda function with Python runtime and the following content. For more information, see the [AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html#getting-started-create-function). The Lambda function acts as an intermediary to process data from AWS IoT and send it to Axiom.
```python
import os # Import the os module to access environment variables
import json # Import the json module to handle JSON data
import requests # Import the requests module to make HTTP requests
def lambda_handler(event, context):
# Retrieve the dataset name and the Axiom domain from the environment variables
dataset_name = os.environ['DATASET_NAME']
axiom_domain = os.environ['AXIOM_DOMAIN']
# Construct the Axiom API URL using the dataset name
axiom_api_url = f"https://{axiom_domain}/v1/ingest/{dataset_name}"
# Retrieve the Axiom API token from the environment variable
api_token = os.environ['API_TOKEN']
# Define the headers for the HTTP request to Axiom
headers = {
"Authorization": f"Bearer {api_token}", # Set the Authorization header with the token
"Content-Type": "application/json", # Specify the content type as JSON
"X-Axiom-Dataset": dataset_name # Include the dataset name in the headers
}
# Create the payload for the HTTP request
payload = {
"tags": {"source": "aws-iot"}, # Add a tag to indicate the source of the data
"events": [{"timestamp": event['timestamp'], "attributes": event}] # Include the event data
}
# Send a POST request to the Axiom API with the headers and payload
response = requests.post(axiom_api_url, headers=headers, data=json.dumps(payload))
# Return the status code and a confirmation message
return {
'statusCode': response.status_code, # Return the HTTP status code from the Axiom API response
'body': json.dumps('Log sent to Axiom!') # Return a confirmation message as JSON
}
```
In the environment variables section of the Lambda function configuration, add the following environment variables:
This example uses Python for the Lambda function. To use another language, change the code above accordingly.
## Create AWS IoT rule [#create-aws-iot-rule]
Create an IoT rule with an SQL statement similar to the example below that matches the MQTT messages. For more information, see the [AWS documentation](https://docs.aws.amazon.com/iot/latest/developerguide/iot-create-rule.html).
```sql
SELECT * FROM 'iot/topic'
```
In **Rule actions**, select the action to send a message to a Lambda function, and then choose the Lambda function you created earlier.
## Check logs in Axiom [#check-logs-in-axiom]
Use the AWS IoT Console, AWS CLI, or an MQTT client to publish messages to the topic that matches your rule. For example, `iot/topic`.
In Axiom, go to the Stream tab and select the dataset you specified in the Lambda function. You now see your logs from your IoT devices in Axiom.
---
# Send data from AWS to Axiom using AWS Distro for OpenTelemetry
Source: https://axiom.co/docs/send-data/aws-lambda-dot
This page explains how to auto-instrument and monitor applications running on AWS Lambda using the AWS Distro for OpenTelemetry (ADOT). ADOT is an OpenTelemetry collector layer managed by and optimized for AWS.
Alternatively, you can use the Axiom Lambda Extension to send Lambda function logs and platform events to Axiom. For more information, see [AWS Lambda](/send-data/aws-lambda).
Axiom detects the extension and provides you with quick filters and a dashboard. For more information on how this enriches your Axiom organization, see [AWS Lambda app](/apps/lambda).
## ADOT Lambda collector layer [#adot-lambda-collector-layer]
[AWS Distro for OpenTelemetry Lambda](https://aws-otel.github.io/docs/getting-started/lambda) provides a plug-and-play user experience by automatically instrumenting a Lambda function. It packages OpenTelemetry together with an out-of-the-box configuration for AWS Lambda and OTLP in an easy-to-setup layer. You can turn on and off OpenTelemetry for your Lambda function without changing your code.
With the ADOT collector layer, you can send telemetry data to Axiom with a simple configuration.
## Set up ADOT Lambda layer [#set-up-adot-lambda-layer]
This example creates a new Lambda function and applies the ADOT Lambda layer to it with the proper configuration.
You can deploy your Lambda function with the choice of your runtime. This example uses the Python3.10 runtime.
Create a new Lambda function with the following content. For more information on creating Lambda functions, see the [AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html).
```python
import json
print('Loading function')
def lambda_handler(event, context):
#print("Received event: " + json.dumps(event, indent=2))
print("value1 = " + event['key1'])
print("value2 = " + event['key2'])
print("value3 = " + event['key3'])
return event['key1'] # Echo back the first key value
#raise Exception('Something went wrong')
```
Add a new ADOT Lambda layer to your function with the following ARN (Amazon Resource Name). For more information on adding layers to your function, see the [AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/adding-layers.html).
```bash
arn:aws:lambda:AWS_REGION:901920570463:layer:aws-otel-python-ARCH-VERSION
```
* Replace `AWS_REGION` with the AWS Region to send the request to. For example, `us-west-1`.
* Replace `ARCH` with the system architecture type. For example, `arm64`.
* Replace `VERSION` with the latest version number specified in the [AWS documentation](https://aws-otel.github.io/docs/getting-started/lambda/lambda-python). For example, `ver-1-25-0:1`.
The configuration file is a YAML file that contains the configuration for the OpenTelemetry collector. Create the configuration file `/var/task/collector.yaml` with the following content. This tells the collector to receive telemetry data from the OTLP receiver and export it to Axiom.
```yaml
receivers:
otlp:
protocols:
grpc:
http:
exporters:
otlphttp:
compression: zstd
endpoint: https://AXIOM_DOMAIN
headers:
authorization: Bearer API_TOKEN
x-axiom-dataset: DATASET_NAME
service:
pipelines:
logs:
receivers: [otlp]
exporters: [otlphttp]
traces:
receivers: [otlp]
exporters: [otlphttp]
```
Set the following environment variables. For more information on setting environment variables, see the [AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html).
```bash
AWS_LAMBDA_EXEC_WRAPPER: /opt/otel-instrument
OPENTELEMETRY_COLLECTOR_CONFIG_FILE: /var/task/collector.yaml
```
* `AWS_LAMBDA_EXEC_WRAPPER` wraps the function handler with the OpenTelemetry Lambda wrapper. This layer enables the auto-instrumentation for your Lambda function by initializing the OpenTelemetry agent and handling the lifecycle of spans.
* `OPENTELEMETRY_COLLECTOR_CONFIG_FILE` specified the location of the collector configuration file.
As the app runs, it sends traces to Axiom. To view the traces:
1. In Axiom, click the **Stream** tab.
2. Click your dataset.
---
# Send data from AWS Lambda to Axiom
Source: https://axiom.co/docs/send-data/aws-lambda
Use the Axiom Lambda Extension to send logs and platform events of your Lambda function to Axiom.
Alternatively, you can use the AWS Distro for OpenTelemetry to send Lambda function logs and platform events to Axiom. For more information, see [AWS Lambda Using OTel](/send-data/aws-lambda-dot).
Axiom detects the extension and provides you with quick filters and a dashboard. For more information on how this enriches your Axiom organization, see [AWS Lambda app](/apps/lambda).
The Axiom Lambda Extension is an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/axiom-lambda-extension).
* [Create an account on AWS Cloud](https://signin.aws.amazon.com/signup?request_type=register).
## Setup [#setup]
1. [Install the Axiom Lambda extension](#installation).
2. Ensure everything works properly in Axiom.
3. [Turn off the permissions for Amazon CloudWatch](#turn-off-cloudwatch-logging).
The last step is important because after you install the Axiom Lambda extension, the Lambda service still sends logs to Amazon CloudWatch Logs. You need to manually turn off Amazon CloudWatch logging.
## Installation [#installation]
To install the Axiom Lambda Extension, choose one of the following methods:
* [AWS CLI](#install-with-aws-cli)
* [Terraform](#install-with-terraform)
* [AWS Lambda function UI](#install-with-aws-lambda-function-ui)
The layer `VERSION` in the ARN isn’t the same as the extension release version on the [GitHub Releases](https://github.com/axiomhq/axiom-lambda-extension/releases) page. AWS assigns layer version numbers automatically, one per publish, so the two numbering schemes differ. For example, extension release v16 is published as layer version `17` in all supported regions. After you install or upgrade, [verify the extension version](#verify-the-extension-version) that your functions run.
### Install with AWS CLI [#install-with-aws-cli]
Add the extension as a layer with the AWS CLI:
```bash
aws lambda update-function-configuration --function-name my-function \
--layers arn:aws:lambda:AWS_REGION:694952825951:layer:axiom-extension-ARCH:VERSION
```
* Replace `AWS_REGION` with the AWS Region to send the request to. For example, `us-west-1`.
* Replace `ARCH` with the system architecture type. For example, `arm64`.
* Replace `VERSION` with the latest Lambda layer version. For example, `17`, which contains extension release v16. The layer version doesn’t match the release version on the [GitHub Releases](https://github.com/axiomhq/axiom-lambda-extension/releases) page because AWS assigns layer version numbers automatically.
Add the Axiom dataset name and API token to the list of environment variables. For more information on setting environment variables, see the [AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html).
```bash
AXIOM_TOKEN: API_TOKEN
AXIOM_DATASET: DATASET_NAME
AXIOM_URL: AXIOM_DOMAIN
```
You have installed the Axiom Lambda Extension. Go to the Axiom UI and ensure your dataset receives events properly.
### Install with Terraform [#install-with-terraform]
Choose one of the following to install the Axiom Lambda Extension with Terraform:
* Use plain Terraform code
```tf
resource "aws_lambda_function" "test_lambda" {
filename = "lambda_function_payload.zip"
function_name = "lambda_function_name"
role = aws_iam_role.iam_for_lambda.arn
handler = "index.test"
runtime = "nodejs14.x"
ephemeral_storage {
size = 10240 # Min 512 MB and the Max 10240 MB
}
environment {
variables = {
AXIOM_TOKEN = "API_TOKEN"
AXIOM_DATASET = "DATASET_NAME"
AXIOM_URL = "AXIOM_DOMAIN"
}
}
layers = [
"arn:aws:lambda:AWS_REGION:694952825951:layer:axiom-extension-ARCH:VERSION"
]
}
```
Replace `AWS_REGION` with the AWS Region to send the request to. For example, `us-west-1`.
Replace `ARCH` with the system architecture type. For example, `arm64`.
Replace `VERSION` with the latest Lambda layer version. For example, `17`, which contains extension release v16. The layer version doesn’t match the release version on the [GitHub Releases](https://github.com/axiomhq/axiom-lambda-extension/releases) page because AWS assigns layer version numbers automatically.
* Use the [AWS Lambda Terraform module](https://registry.terraform.io/modules/terraform-aws-modules/lambda/aws/latest)
```tf
module "lambda_function" {
source = "terraform-aws-modules/lambda/aws"
function_name = "my-lambda1"
description = "My awesome lambda function"
handler = "index.lambda_handler"
runtime = "python3.8"
source_path = "../src/lambda-function1"
layers = [
"arn:aws:lambda:AWS_REGION:694952825951:layer:axiom-extension-ARCH:VERSION"
]
environment_variables = {
AXIOM_TOKEN = "API_TOKEN"
AXIOM_DATASET = "DATASET_NAME"
AXIOM_URL = "AXIOM_DOMAIN"
}
}
```
Replace `AWS_REGION` with the AWS Region to send the request to. For example, `us-west-1`.
Replace `ARCH` with the system architecture type. For example, `arm64`.
Replace `VERSION` with the latest Lambda layer version. For example, `17`, which contains extension release v16. The layer version doesn’t match the release version on the [GitHub Releases](https://github.com/axiomhq/axiom-lambda-extension/releases) page because AWS assigns layer version numbers automatically.
You have installed the Axiom Lambda Extension. Go to the Axiom UI and ensure your dataset receives events properly.
### Install with AWS Lambda function UI [#install-with-aws-lambda-function-ui]
Add a new layer to your Lambda function with the following ARN (Amazon Resource Name). For more information on adding layers to your function, see the [AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/adding-layers.html).
```bash
arn:aws:lambda:AWS_REGION:694952825951:layer:axiom-extension-ARCH:VERSION
```
Replace `AWS_REGION` with the AWS Region to send the request to. For example, `us-west-1`.
Replace `ARCH` with the system architecture type. For example, `arm64`.
Replace `VERSION` with the latest Lambda layer version. For example, `17`, which contains extension release v16. The layer version doesn’t match the release version on the [GitHub Releases](https://github.com/axiomhq/axiom-lambda-extension/releases) page because AWS assigns layer version numbers automatically.
Add the Axiom dataset name and API token to the list of environment variables. For more information on setting environment variables, see the [AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html).
```bash
AXIOM_TOKEN: API_TOKEN
AXIOM_DATASET: DATASET_NAME
```
You have installed the Axiom Lambda Extension. Go to the Axiom UI and ensure your dataset receives events properly.
## Verify the extension version [#verify-the-extension-version]
The extension stamps its release version on every event it sends to Axiom. After you install or upgrade, check which release your functions actually run:
```kusto
['DATASET_NAME']
| where isnotnull(['axiom.awsLambdaExtensionVersion'])
| summarize count() by ['axiom.awsLambdaExtensionVersion']
```
The result is the extension release version, such as `v16`. If the result shows an older release than you expect, the layer version in your function configuration points to an older build. Update the layer ARN to the latest layer version, and then redeploy your function.
## Turn off Amazon CloudWatch logging [#turn-off-amazon-cloudwatch-logging]
After you install the Axiom Lambda extension, the Lambda service still sends logs to CloudWatch Logs. You need to manually turn off Amazon CloudWatch logging.
To turn off Amazon CloudWatch logging, deny the Lambda function access to Amazon CloudWatch by editing the permissions:
1. In the AWS Lambda function UI, go to **Configuration > Permissions**.
2. In the **Execution role** section, click the role related to Amazon CloudWatch Logs.
3. In the **Permissions** tab, select the role, and then click **Remove**.
### Requirements for log level fields [#requirements-for-log-level-fields]
Axiom supports [severity matching](/reference/limits#requirements-for-log-level-fields) for AWS Lambda logs.
## Best practices for production workloads [#best-practices-for-production-workloads]
The Axiom Lambda Extension runs inside your Lambda execution environment and shares its CPU, memory, and network with your function. It favors the performance of your function over guaranteed log delivery: it buffers events in memory and, when Axiom is unreachable for a sustained period, drops the oldest buffered events. The buffer only lives as long as the execution environment. For low-to-medium volume workloads that tolerate occasional loss, sending directly from the extension to Axiom works well.
For high-volume, high-concurrency, or delivery-critical workloads, don’t send directly to Axiom from your functions. Decouple your functions from Axiom with a durable collector that you run on separate infrastructure. Your functions hand logs to a nearby collector and return immediately, and the collector owns buffering, batching, backpressure, and retries before forwarding to Axiom. This keeps your function durations predictable and prevents log loss when Axiom is briefly unreachable.
### Forward to a collector you manage (recommended) [#forward-to-a-collector-you-manage-recommended]
Run a durable log pipeline such as Vector or the OpenTelemetry Collector on always-on infrastructure you manage, such as Amazon ECS or EC2. The collector forwards to Axiom: Vector through its native [Axiom sink](/send-data/vector), and the OpenTelemetry Collector over OTLP, which Axiom ingests [natively](/send-data/opentelemetry). The sizing and operation of the collector are up to you.
Get logs from your functions to this collector in one of the following ways:
* **Axiom Lambda Extension.** Set the `AXIOM_URL` environment variable to your collector’s endpoint. The extension sends gzip-compressed NDJSON to the `/v1/datasets/DATASET_NAME/ingest` path of that URL, so any intermediary that accepts the [Axiom ingest API](/restapi/ingest) and forwards to Axiom works.
* **OpenTelemetry Lambda layer.** Use the [OpenTelemetry Lambda layer](https://github.com/open-telemetry/opentelemetry-lambda/blob/main/collector/README.md) as a replacement for the Axiom Lambda Extension, and configure its exporter to forward to your collector. For more information, see [Send OpenTelemetry data to Axiom](/send-data/opentelemetry).
### Use Amazon CloudWatch as the buffer [#use-amazon-cloudwatch-as-the-buffer]
If you prefer not to run collector infrastructure, use AWS-native tooling to decouple delivery. Keep CloudWatch logging turned on (skip the [turn-off step](#turn-off-amazon-cloudwatch-logging) above) and ship logs with the [Axiom CloudWatch Forwarder](/send-data/cloudwatch). CloudWatch durably stores the logs, and the forwarder delivers them to Axiom fully decoupled from your functions, at the cost of CloudWatch pricing and some added latency.
## Troubleshooting [#troubleshooting]
* Ensure the Axiom API token has permission to ingest data into the dataset.
* Check the function logs on the AWS console. The Axiom Lambda Extension logs any errors with setup or ingest.
For testing purposes, set the `PANIC_ON_API_ERR` environment variable to `true`. This means that the Axiom Lambda Extension crashes if it can’t connect to Axiom.
---
# Send data from AWS to Axiom
Source: https://axiom.co/docs/send-data/aws-overview
For most AWS services, the fastest and easiest way to send logs to Axiom is the [Axiom CloudWatch Forwarder](/send-data/cloudwatch). It’s subscribed to one or more of your CloudWatch Log Groups and runs as a Lambda function. To determine which AWS service sends logs to Amazon CloudWatch and/or Amazon S3, see the [AWS Documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html).
## Choose the best method to send data [#choose-the-best-method-to-send-data]
To choose the best method to send data from AWS services to Axiom, consider that Amazon CloudWatch Logs captures three main types of logs:
* **Service logs**: More than 30 AWS services, including Amazon API Gateway, AWS Lambda, AWS CloudTrail, can send service logs to CloudWatch.
* **Vended logs**: Automatically published by certain AWS services like Amazon VPC and Amazon Route 53.
* **Custom logs**: Logs from your own applications, on-premise resources, and other clouds.
You can only send vended logs to Axiom through Amazon CloudWatch. Use the [Axiom CloudWatch Forwarder](/send-data/cloudwatch) to send vended logs from Amazon CloudWatch to Axiom for richer insights. After sending vended logs to Axiom, shorten the retention period for these logs in Amazon CloudWatch to cut costs even more.
For service logs and custom logs, you can skip Amazon CloudWatch altogether and send them to Axiom using open-source collectors like [Fluent Bit](/send-data/fluent-bit), [Fluentd](/send-data/fluentd) and [Vector](/send-data/vector). Completely bypassing Amazon CloudWatch results in significant cost savings.
## Amazon services exclusively supported by Axiom CloudWatch Forwarder [#amazon-services-exclusively-supported-by-axiom-cloudwatch-forwarder]
To send data from the following Amazon services to Axiom, use the [Axiom CloudWatch Forwarder](/send-data/cloudwatch).
* Amazon API Gateway
* Amazon Aurora MySQL
* Amazon Chime
* Amazon CloudWatch
* Amazon CodeWhisperer
* Amazon Cognito
* Amazon Connect
* AWS AppSync
* AWS Elastic Beanstalk
* AWS CloudHSM
* AWS CloudTrail
* AWS CodeBuild
* AWS DataSync
* AWS Elemental MediaTailor
* AWS Fargate
* AWS Glue
To send evaluation event logs from Amazon CloudWatch to Axiom, you can also use [Amazon Data Firehose](/send-data/aws-firehose).
## Amazon services supported by other methods [#amazon-services-supported-by-other-methods]
The table below summarizes the methods you can use to send data from the other supported Amazon services to Axiom.
| Supported Amazon service | Supported methods to send data to Axiom |
| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| Amazon Bedrock | [Axiom CloudWatch Forwarder](/send-data/cloudwatch) [AWS S3 Forwarder](/send-data/aws-s3) [Amazon Data Firehose](/send-data/aws-firehose) |
| Amazon CloudFront | [AWS S3 Forwarder](/send-data/aws-s3) |
| Amazon Data Firehose | [Amazon Data Firehose](/send-data/aws-firehose) |
| Amazon Elastic Container Service | [Fluentbit](/send-data/fluent-bit) |
| Amazon Elastic Load Balancing (ELB) | [Fluentbit](/send-data/fluent-bit) |
| Amazon ElastiCache (Redis OSS) | [Axiom CloudWatch Forwarder](/send-data/cloudwatch) [Amazon Data Firehose](/send-data/aws-firehose) |
| Amazon EventBridge Pipes | [Axiom CloudWatch Forwarder](/send-data/cloudwatch) [AWS S3 Forwarder](/send-data/aws-s3) [Amazon Data Firehose](/send-data/aws-firehose) |
| Amazon FinSpace | [Axiom CloudWatch Forwarder](/send-data/cloudwatch) [AWS S3 Forwarder](/send-data/aws-s3) [Amazon Data Firehose](/send-data/aws-firehose) |
| Amazon S3 | [AWS S3 Forwarder](/send-data/aws-s3) [Vector](/send-data/vector) |
| Amazon Virtual Private Cloud (VPC) | [AWS S3 Forwarder](/send-data/aws-s3) |
| AWS Fault Injection Service | [AWS S3 Forwarder](/send-data/aws-s3) |
| AWS FireLens | [AWS FireLens](/send-data/aws-firelens) |
| AWS Global Accelerator | [AWS S3 Forwarder](/send-data/aws-s3) |
| AWS IoT Core | [AWS IoT](/send-data/aws-iot-rules) |
| AWS Lambda | [AWS Lambda](/send-data/aws-lambda) |
To request support for AWS services not listed above, please [reach out to Axiom](https://axiom.co/contact).
---
# Send data from AWS S3 to Axiom
Source: https://axiom.co/docs/send-data/aws-s3
This page explains how to set up an AWS Lambda function to send logs from an S3 bucket to Axiom. The Lambda function triggers when a new log file is uploaded to an S3 bucket, processes the log data, and sends it to Axiom.
* Create an AWS account with permissions to create and manage S3 buckets, Lambda functions, and IAM roles. For more information, see the [AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html).
## Package the requests module [#package-the-requests-module]
Before creating the Lambda function, package the requests module so it can be used in the function:
1. Create a new directory.
2. Install the requests module into the current directory using pip.
3. Zip the contents of the directory.
4. Add your Lambda function file to the zip file.
## Create AWS Lambda function [#create-aws-lambda-function]
Create a Lambda function with Python runtime and upload the packaged zip file containing the requests module and your function code below:
```py
import os
import json
import boto3
import requests
import csv
import io
import ndjson
import re
def lambda_handler(event, context):
# Extract the bucket name and object key from the event
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
try:
# Fetch the log file from S3
s3 = boto3.client('s3')
obj = s3.get_object(Bucket=bucket, Key=key)
except Exception as e:
print(f"Error fetching from S3: {str(e)}")
raise e
# Read the log data from the S3 object
log_data = obj['Body'].read().decode('utf-8')
# Determine the file format and parse accordingly
file_extension = os.path.splitext(key)[1].lower()
if file_extension == '.csv':
csv_data = csv.DictReader(io.StringIO(log_data))
json_logs = list(csv_data)
elif file_extension == '.txt':
log_lines = log_data.strip().split("\n")
json_logs = [{'message': line} for line in log_lines]
elif file_extension == '.log':
# IMPORTANT: Log files can be in various formats (JSON, XML, syslog, etc.)
try:
# First, try to parse as JSON (either one JSON object per line or a JSON array)
if log_data.strip().startswith('[') and log_data.strip().endswith(']'):
# Appears to be a JSON array
json_logs = json.loads(log_data)
else:
# Try parsing as NDJSON (one JSON object per line)
try:
json_logs = ndjson.loads(log_data)
except:
# If not valid NDJSON, check if each line might be JSON
log_lines = log_data.strip().split("\n")
json_logs = []
for line in log_lines:
try:
# Try to parse each line as JSON
parsed_line = json.loads(line)
json_logs.append(parsed_line)
except:
# Create a dictionary and let json module handle the escaping
message_dict = {'message': line}
json_logs.append(message_dict)
except:
# If JSON parsing fails, default to treating as plain text
log_lines = log_data.strip().split("\n")
json_logs = [{'message': line} for line in log_lines]
print("Warning: Log file format could not be determined. Treating as plain text.")
elif file_extension == '.ndjson' or file_extension == '.jsonl':
json_logs = ndjson.loads(log_data)
else:
print(f"Unsupported file format: {file_extension}")
return
# Prepare Axiom API request
dataset_name = os.environ['DATASET_NAME']
axiom_edge_domain = os.environ['AXIOM_DOMAIN']
axiom_api_url = f"https://{axiom_edge_domain}/v1/ingest/{dataset_name}"
api_token = os.environ['API_TOKEN']
axiom_headers = {
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json"
}
try:
response = requests.post(axiom_api_url, headers=axiom_headers, json=json_logs)
if response.status_code != 200:
print(f"Failed to send logs to Axiom: {response.text}")
else:
print(f"Successfully sent logs to Axiom. Response: {response.text}")
except Exception as e:
print(f"Error sending to Axiom: {str(e)}")
print(f"Processed {len(json_logs)} log entries")
```
In the environment variables section of the Lambda function configuration, add the following environment variables:
This example uses Python for the Lambda function. To use another language, change the code above accordingly.
### Understanding log format [#understanding-log-format]
The `.log` extension doesn't guarantee any specific format. Log files might contain:
* JSON (single object or array)
* NDJSON/JSONL (one JSON object per line)
* Syslog format
* XML
* Application-specific formats (Apache, Nginx, ELB, etc.)
* Custom formats with quoted strings and special characters
The example code includes format detection for common formats, but you’ll need to customize this based on your specific log structure.
#### Example: Custom parser for structured logs [#example-custom-parser-for-structured-logs]
For logs with a specific structure (like AWS ELB logs), you have to implement a custom parser. Here’s a simplified example:
```py
import shlex
import re
class Parser:
def parse_line(self, line):
try:
line = re.sub(r"[\[\]]", "", line)
data = shlex.split(line)
result = {
"protocol": data[0],
"timestamp": data[1],
"client_ip_port": data[2],
# ...more fields...
}
return result
except Exception as e:
raise e
```
## Configure S3 to trigger Lambda [#configure-s3-to-trigger-lambda]
In the Amazon S3 console, select the bucket where your log files are stored. Go to the properties tab, find the event notifications section, and create an event notification. Select All object create events as the event type and choose the Lambda function you created earlier as the destination. For more information, see the [AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html).
## Upload a test log file [#upload-a-test-log-file]
Ensure the log file you upload to the S3 bucket is in the correct format, such as JSON or newline-delimited JSON (NDJSON) or CSV. Here’s an example:
```json
[
{
"_time":"2021-02-04T03:11:23.222Z",
"data":{"key1":"value1","key2":"value2"}
},
{
"data":{"key3":"value3"},
"attributes":{"key4":"value4"}
},
{
"tags": {
"server": "aws",
"source": "wordpress"
}
}
]
```
After uploading a test log file to your S3 bucket, the Lambda function automatically processes the log data and sends it to Axiom. In Axiom, go to the Stream tab and select the dataset you specified in the Lambda function. You now see the logs from your S3 bucket in Axiom.
---
# Send data from CloudFront to Axiom
Source: https://axiom.co/docs/send-data/cloudfront
Use the Axiom CloudFront Lambda to send CloudFront logs to Axiom using AWS S3 bucket and Lambda. After you set this up, you can observe your static and dynamic content and run deep queries on your CloudFront distribution logs efficiently and properly.
The Axiom CloudFront Lambda is an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/axiom-cloudfront-lambda).
* [Create an account on AWS Cloud](https://signin.aws.amazon.com/signup?request_type=register).
## Setup [#setup]
1. Select one of the following:
* If you already have an S3 bucket for your CloudFront data, [launch the base stack on AWS](https://us-east-2.console.aws.amazon.com/cloudformation/home?region=us-east-2#/stacks/create/template?stackName=CloudFront-Axiom\&templateURL=https://axiom-cloudformation-stacks.s3.amazonaws.com/axiom-cloudfront-lambda-base-cloudformation-stack.yaml).
* If you don’t have an S3 bucket for your CloudFront data, [launch the stack on AWS](https://us-east-2.console.aws.amazon.com/cloudformation/home?region=us-east-2#/stacks/create/template?stackName=CloudFront-Axiom\&templateURL=https://axiom-cloudformation-stacks.s3.amazonaws.com/axiom-cloudfront-lambda-cloudformation-stack.yaml) that creates an S3 bucket for you.
2. Add the name of the Axiom dataset where you want to send data.
3. Enter the Axiom API token you have previously created.
## Configuration [#configuration]
To configure your CloudFront distribution:
1. In AWS, select your origin domain.
2. In **Origin access**, select **Legacy access identities**, and then select your origin access identity in the list.
3. In **Bucket policy**, select **Yes, update the bucket policy**.
4. In **Standard logging**, select **On**. This means that your data is delivered to your S3 bucket.
5. Click **Create Distribution**, and then click **Run your Distribution**.
Go back to Axiom to see the CloudFront distribution logs.
---
# Send data from Amazon CloudWatch to Axiom
Source: https://axiom.co/docs/send-data/cloudwatch
Axiom CloudWatch Forwarder is a set of easy-to-use AWS CloudFormation stacks designed to forward logs from Amazon CloudWatch to Axiom. It includes a Lambda function to handle the forwarding and stacks to create Amazon CloudWatch log group subscription filters for both existing and future log groups.
Axiom CloudWatch Forwarder includes templates for the following CloudFormation stacks:
* **Forwarder** creates a Lambda function that forwards logs from Amazon CloudWatch to Axiom.
* **Subscriber** runs once to create subscription filters on Forwarder for Amazon CloudWatch log groups specified by a combination of names, prefix, and regular expression filters.
* **Listener** creates a Lambda function that listens for new log groups and creates subscription filters for them on Forwarder. This way, you don’t have to create subscription filters manually for new log groups.
* **Unsubscriber** runs once to remove subscription filters on Forwarder for Amazon CloudWatch log groups specified by a combination of names, prefix, and regular expression filters.
The Axiom CloudWatch Forwarder is an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/axiom-cloudwatch-forwarder).
* [Create an account on AWS Cloud](https://signin.aws.amazon.com/signup?request_type=register).
## Installation [#installation]
To install the Axiom CloudWatch Forwarder, choose one of the following:
* [Cloudformation stacks](#install-with-cloudformation-stacks)
* [Terraform module](#install-with-terraform-module)
### Install with Cloudformation stacks [#install-with-cloudformation-stacks]
1. [Launch the Forwarder stack template on AWS](https://console.aws.amazon.com/cloudformation/home?#/stacks/new?stackName=axiom-cloudwatch-forwarder\&templateURL=https://axiom-cloudformation.s3.amazonaws.com/stacks/axiom-cloudwatch-forwarder-v1.1.1-cloudformation-stack.yaml). Copy the Forwarder Lambda ARN because it’s referenced in the Subscriber stack.
2. [Launch the Subscriber stack template on AWS](https://console.aws.amazon.com/cloudformation/home?#/stacks/new?stackName=axiom-cloudwatch-subscriber\&templateURL=https://axiom-cloudformation.s3.amazonaws.com/stacks/axiom-cloudwatch-subscriber-v1.1.1-cloudformation-stack.yaml).
3. [Launch the Listener stack template on AWS](https://console.aws.amazon.com/cloudformation/home?#/stacks/new?stackName=axiom-cloudwatch-listener\&templateURL=https://axiom-cloudformation.s3.amazonaws.com/stacks/axiom-cloudwatch-listener-v1.1.1-cloudformation-stack.yaml).
### Install with Terraform module [#install-with-terraform-module]
Create a new Forwarder module in your Terraform file in the following way:
```hcl
module "forwarder" {
source = "axiomhq/axiom-cloudwatch-forwarder/aws//modules/forwarder"
axiom_dataset = "DATASET_NAME"
axiom_token = "API_TOKEN"
prefix = "axiom-cloudwatch-forwarder"
}
```
Alternatively, create a dataset with the [Axiom Terraform provider](/apps/terraform#create-dataset).
Create a new Subscriber module in your Terraform file in the following way:
```hcl
module "subscriber" {
source = "axiomhq/axiom-cloudwatch-forwarder/aws//modules/subscriber"
prefix = "axiom-cloudwatch-forwarder"
forwarder_lambda_arn = module.forwarder.lambda_arn
log_groups_prefix = "/aws/lambda/"
}
```
Create a new Listener module in your Terraform file in the following way:
```hcl
module "listener" {
source = "axiomhq/axiom-cloudwatch-forwarder/aws//modules/listener"
prefix = "axiom-cloudwatch-forwarder"
forwarder_lambda_arn = module.forwarder.lambda_arn
log_groups_prefix = "/aws/lambda/"
}
```
In your terminal, go to the folder of your main Terraform file, and then run `terraform init`.
Run `terraform plan` to check the changes, and then run `terraform apply`.
## Filter Amazon CloudWatch log groups [#filter-amazon-cloudwatch-log-groups]
The Subscriber and Unsubscriber stacks allow you to filter the log groups by a combination of names, prefix, and regular expression filters. If no filters are specified, the stacks subscribe to or unsubscribe from all log groups. You can also whitelist a specific set of log groups using filters in the CloudFormation stack parameters. The log group names, prefix, and regular expression filters included are additive, meaning the union of all provided inputs is matched.
### Example [#example]
For example, you have the following list of log groups:
```
/aws/lambda/function-foo
/aws/lambda/function-bar
/aws/eks/cluster/cluster-1
/aws/rds/instance-baz
```
* To subscribe to the Lambda log groups exclusively, use a prefix filter with the value of `/aws/lambda`.
* To subscribe to EKS and RDS log groups, use a list of names with the value of `/aws/eks/cluster/cluster-1,/aws/rds/instance-baz`.
* To subscribe to the EKS log group and all Lambda log groups, use a combination of prefix and names list.
* To use the regular expression filter, write a regular expression to match the log group names. For example, `\/aws\/lambda\/.*` matches all Lambda log groups.
* To subscribe to all log groups, leave the filters empty.
## Listener architecture [#listener-architecture]
The optional Listener stack does the following:
* Creates an Amazon S3 bucket for AWS CloudTrail.
* Creates a trail to capture the creation of new log groups.
* Creates an event rule to pass those creation events to an Amazon EventBridge event bus.
* Sends an event via EventBridge to a Lambda function when a new log group is created.
* Creates a subscription filter for each new log group.
## Remove subscription filters [#remove-subscription-filters]
To remove subscription filters for one or more log groups, [launch the Unsubscriber stack template on AWS](https://console.aws.amazon.com/cloudformation/home?#/stacks/new?stackName=axiom-cloudwatch-subscriber\&templateURL=https://axiom-cloudformation.s3.amazonaws.com/stacks/axiom-cloudwatch-unsubscriber-v1.1.1-cloudformation-stack.yaml).
The log group filtering works the same way as the Subscriber stack. You can filter the log groups by a combination of names, prefix, and regular expression filters.
Alternatively, to turn off log forwarding to Axiom, create a new Unsubscriber module in your Terraform file in the following way:
```hcl
module "unsubscriber" {
source = "axiomhq/axiom-cloudwatch-forwarder/aws//modules/unsubscriber"
prefix = "axiom-cloudwatch-forwarder"
forwarder_lambda_arn = module.forwarder.lambda_arn
log_groups_prefix = "/aws/lambda/"
}
```
---
# Send data from Convex to Axiom
Source: https://axiom.co/docs/send-data/convex
[Convex](https://convex.dev) lets you manage the backend of your app (database, server, and more) from a centralized cloud interface. Set up a log stream in Convex to send your app’s logs to Axiom and make it your single source of truth about events.
* [Create a Convex account](https://www.convex.dev/login) with a Professional plan.
* Set up your app with Convex. For example, follow one of the quickstart guides in the [Convex documentation](https://docs.convex.dev/quickstarts).
## Configure Convex log streams [#configure-convex-log-streams]
To send data from Convex to Axiom, set up a Convex log stream:
In your Convex dashboard, configure the Axiom integration. For more information, see the [Convex documentation about configuring an integration](https://docs.convex.dev/production/integrations/#configuring-an-integration).
During this process, you need the following:
* **Dataset name**: The name of the Axiom dataset where you want to send data.
* **API key**: Your Axiom API token.
* **Attributes** (optional): A list of key-value pairs to include in all events your app sends to Axiom. Attributes are useful for adding context like project name, environment, or team information to all your logs.
Convex verifies the connection to Axiom and displays a confirmation when the log stream is active.
For more information, see the [Convex documentation about log streams](https://docs.convex.dev/production/integrations/log-streams#axiom).
## Benefits of streaming Convex logs to Axiom [#benefits-of-streaming-convex-logs-to-axiom]
The Convex log streaming integration with Axiom provides several key benefits:
* **Complete observability**: Monitor all function executions, errors, and performance metrics in one place
* **Historical analysis**: Store and analyze logs beyond Convex’s recent logs view
* **Advanced querying**: Use APL to create complex queries and aggregations
* **Real-time monitoring**: Set up alerts and monitors for proactive issue detection
* **Custom dashboards**: Build tailored visualizations for your specific use cases
* **Team collaboration**: Share insights and dashboards with your development team
For more information, see [Connect Axiom with Convex](/apps/convex).
---
# Send data from Cribl to Axiom
Source: https://axiom.co/docs/send-data/cribl
Cribl is a data processing framework often used with machine data. It allows you to parse, reduce, transform, and route data to and from various systems in your infrastructure.
You can send data from Cribl Stream to Axiom using the Webhook destination.
To send OCSF security events, use the OCSF for Axiom pack together with the Webhook destination. The pack conforms OCSF events to the Axiom OCSF schema before they leave Cribl. For more information, see [Send OCSF data from Cribl Stream](/use-cases/ocsf/send-data#send-ocsf-data-from-cribl-stream).
## Send data using the Webhook destination [#send-data-using-the-webhook-destination]
Cribl Stream has no dedicated Axiom destination. The stock Webhook destination sends batched, compressed NDJSON events straight to Axiom’s [ingest API](/restapi/ingest).
1. In Cribl Stream, add a **Webhook** destination and enter an **Output ID** for it.
2. Configure the destination with the following settings.
3. Optional: In **Processing Settings > Post-Processing**, select a pipeline to shape events before they leave Cribl, and adjust **System fields**. By default, Cribl adds the `cribl_pipe` field to every event.
4. Save the destination, and then commit and deploy the change.
---
# Send data from Docker to Axiom
Source: https://axiom.co/docs/send-data/docker
Docker captures everything your containers write to `stdout` and `stderr` and hands it to a logging driver. By default, the `json-file` driver stores this output on the host. To send container logs to Axiom, run a collector on the host that reads those logs, or point one of Docker’s built-in logging drivers at a forwarder that sends the logs to Axiom.
This page covers the methods that work with Axiom and explains when to use each. For containers that run on Kubernetes, see [Send data from Kubernetes](/send-data/kubernetes). For Amazon ECS and AWS Fargate, see [Send data from AWS FireLens](/send-data/aws-firelens).
* Docker Engine on a Linux host. Depending on the method, the collector needs access to the Docker socket (`/var/run/docker.sock`) or to the container log directory (`/var/lib/docker/containers`).
## Choose a method [#choose-a-method]
| Method | How it collects logs | Container metadata |
| :---------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------- | :------------------------------------------------- |
| [Vector](#send-docker-logs-with-vector) | The `docker_logs` source reads container output through the Docker socket. | Container name and ID, image, labels, stream |
| [OpenTelemetry Collector](#send-docker-logs-with-the-opentelemetry-collector) | The `filelog` receiver tails the `json-file` log files. The `docker_stats` receiver adds container metrics. | Container ID, stream, and the path of the log file |
| [Fluent Bit](#send-docker-logs-with-fluent-bit) | Docker’s `fluentd` logging driver pushes logs to the Fluent Bit `forward` input. | Container name and ID, stream |
| [Fluentd](#send-docker-logs-with-fluentd) | Docker’s `fluentd` logging driver pushes logs to the Fluentd `forward` input. | Container name and ID, stream |
| [Filebeat](#send-docker-logs-with-filebeat) | The `filestream` input with the `container` parser tails the `json-file` log files. | Container ID, name, image, and labels |
Vector, the OpenTelemetry Collector, and Filebeat work with Docker’s default logging configuration. The Fluent Bit and Fluentd methods change the logging driver of your containers. In that case, `docker logs` still works because Docker keeps a local cache of the latest logs, unless you set the `cache-disabled` option to `true`.
## Send Docker logs with Vector [#send-docker-logs-with-vector]
Vector’s `docker_logs` source collects the output of all containers through the Docker socket and adds the container name, ID, image, and labels to each event. The `axiom` sink sends the events to Axiom. This is the recommended method if you don’t already run another collector.
### Run Vector on the host [#run-vector-on-the-host]
1. [Install Vector](https://vector.dev/docs/setup/quickstart/) on the Docker host. The user that runs Vector must have access to the Docker socket, for example as a member of the `docker` group.
2. Create a configuration file `vector.toml` with the following content:
```toml
[sources.docker_logs]
type = "docker_logs"
docker_host = "unix:///var/run/docker.sock"
# Keep the Docker log timestamp as the Axiom event time
[transforms.docker_time]
type = "remap"
inputs = ["docker_logs"]
source = '''
._time = del(.timestamp)
'''
[sinks.axiom]
type = "axiom"
inputs = ["docker_time"]
dataset = "DATASET_NAME"
token = "API_TOKEN"
region = "AXIOM_DOMAIN"
```
3. Run Vector with the configuration file:
```bash
vector --config /path/to/vector.toml
```
The `docker_time` transform moves Vector’s `timestamp` field to `_time`. Without it, Axiom assigns the ingest time to each event and stores the Docker timestamp in the `timestamp` field.
To collect logs from a subset of containers, add `include_containers`, `exclude_containers`, `include_images`, or `include_labels` to the `docker_logs` source. Container names and IDs match by prefix. Exclusions take precedence over inclusions.
### Run Vector as a container [#run-vector-as-a-container]
To run Vector as a container on the same host, mount the Docker socket and the configuration file into the container.
1. Create a configuration file `vector.yaml` with the following content:
```yaml
sources:
docker_logs:
type: docker_logs
# Optional: collect only from some containers (prefix match on name or ID)
# include_containers:
# - api
# - worker
transforms:
# Keep the Docker log timestamp as the Axiom event time
docker_time:
type: remap
inputs:
- docker_logs
source: |
._time = del(.timestamp)
sinks:
axiom:
type: axiom
inputs:
- docker_time
dataset: DATASET_NAME
token: API_TOKEN
region: AXIOM_DOMAIN
```
2. Start Vector:
```bash
docker run -d --name vector \
-v /var/run/docker.sock:/var/run/docker.sock:ro \
-v $(pwd)/vector.yaml:/etc/vector/vector.yaml:ro \
timberio/vector:0.59.0-alpine
```
Alternatively, add Vector to your Docker Compose file:
```yaml
services:
vector:
image: timberio/vector:0.59.0-alpine
restart: unless-stopped
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- ./vector.yaml:/etc/vector/vector.yaml:ro
```
Replace `0.59.0` with the Vector version you want to run.
When Vector runs as a container, it automatically excludes its own logs.
### Query Docker logs sent by Vector [#query-docker-logs-sent-by-vector]
Each event contains the log line in `message`, the output stream in `stream`, and the container metadata in `container_name`, `container_id`, `image`, `container_created_at`, and `label`. For example, to see the latest output of the `api` container:
```kusto
['DATASET_NAME']
| where container_name == "api"
| project _time, stream, message
| sort by _time desc
```
## Send Docker logs with the OpenTelemetry Collector [#send-docker-logs-with-the-opentelemetry-collector]
The `filelog` receiver of the OpenTelemetry Collector tails the `json-file` log files that Docker writes. The `container` operator parses the Docker log format, and the `otlphttp` exporter sends the logs to Axiom. The `filelog` receiver is part of the Contrib distribution of the Collector.
1. Create a configuration file `otel-collector.yaml` with the following content:
```yaml
receivers:
filelog:
include:
- /var/lib/docker/containers/*/*-json.log
start_at: end
include_file_path: true
operators:
# Parse the json-file format: the log text becomes the body, the stream
# becomes the log.iostream attribute, and the time becomes the timestamp
- type: container
format: docker
add_metadata_from_filepath: false
# Add the container ID from the log file path
- type: regex_parser
regex: '/containers/(?P[^/]+)/'
parse_from: attributes["log.file.path"]
# Optional: parse JSON log lines into fields
- type: json_parser
if: body matches '^{.*}\\s*$'
processors:
batch:
exporters:
otlphttp:
compression: zstd
endpoint: https://AXIOM_DOMAIN
headers:
authorization: Bearer API_TOKEN
x-axiom-dataset: DATASET_NAME
service:
pipelines:
logs:
receivers:
- filelog
processors:
- batch
exporters:
- otlphttp
```
2. Start the Collector. The Collector needs read access to `/var/lib/docker/containers`, which is only readable by root, so run the container as root:
```bash
docker run -d --name otel-collector \
--user 0 \
-v /var/lib/docker/containers:/var/lib/docker/containers:ro \
-v $(pwd)/otel-collector.yaml:/etc/otelcol-contrib/config.yaml:ro \
otel/opentelemetry-collector-contrib:0.162.0
```
Alternatively, add the Collector to your Docker Compose file:
```yaml
services:
otel-collector:
image: otel/opentelemetry-collector-contrib:0.162.0
restart: unless-stopped
user: "0"
volumes:
- /var/lib/docker/containers:/var/lib/docker/containers:ro
- ./otel-collector.yaml:/etc/otelcol-contrib/config.yaml:ro
```
Replace `0.162.0` with the Collector version you want to run.
Each event contains the log line as the body, the output stream in `log.iostream`, the log file in `log.file.path`, and the container ID in `container_id`. When a log line is a JSON object, the `json_parser` operator turns its keys into fields. Docker keeps the trailing newline of each line, so the condition of the operator allows whitespace after the closing brace. Docker doesn’t record container names in the log files. To query by container name, use Vector or the `fluentd` logging driver instead.
### Send container metrics with the OpenTelemetry Collector [#send-container-metrics-with-the-opentelemetry-collector]
The `docker_stats` receiver collects CPU, memory, network, and block I/O metrics for every running container through the Docker socket. Send these metrics to a dataset of type **Metrics**, separate from the dataset that holds your logs. The receiver runs on Linux only.
Add the receiver, an exporter for the metrics dataset, and a metrics pipeline to the Collector configuration:
```yaml
receivers:
docker_stats:
endpoint: unix:///var/run/docker.sock
collection_interval: 30s
processors:
batch:
exporters:
otlphttp/metrics:
compression: zstd
endpoint: https://AXIOM_DOMAIN
headers:
authorization: Bearer API_TOKEN
x-axiom-metrics-dataset: METRICS_DATASET_NAME
service:
pipelines:
metrics:
receivers:
- docker_stats
processors:
- batch
exporters:
- otlphttp/metrics
```
Mount the Docker socket into the Collector container with `-v /var/run/docker.sock:/var/run/docker.sock:ro`.
Replace `API_TOKEN` with the Axiom API token you have generated. For added security, store the API token in an environment variable.
Replace `METRICS_DATASET_NAME` with the name of the Axiom dataset of type **Metrics** where you send the container metrics.
## Send Docker logs with Fluent Bit [#send-docker-logs-with-fluent-bit]
Docker’s built-in `fluentd` logging driver sends container logs to a Fluentd-compatible `forward` input. Fluent Bit implements this protocol, so you can run Fluent Bit as a small forwarder and point the logging driver at it. Fluent Bit then sends the logs to Axiom with its `http` output. Each record contains the log line in `log`, the output stream in `source`, and the container metadata in `container_id` and `container_name`.
1. Create a configuration file `fluent-bit.conf` with the following content:
```ini
[SERVICE]
Flush 1
Log_Level info
Parsers_File /fluent-bit/etc/parsers.conf
[INPUT]
Name forward
Listen 0.0.0.0
Port 24224
[OUTPUT]
Name http
Match *
Host AXIOM_DOMAIN
Port 443
URI /v1/ingest/DATASET_NAME
Header Authorization Bearer API_TOKEN
Compress gzip
Format json
JSON_Date_Key _time
JSON_Date_Format iso8601
TLS On
```
The `JSON_Date_Key` option writes the timestamp of each record to the `_time` field, so Axiom uses the time that Docker recorded.
2. Start Fluent Bit and publish port `24224` on the host. The Docker daemon, not the container, connects to this port:
```bash
docker run -d --name fluent-bit \
-p 24224:24224 \
-v $(pwd)/fluent-bit.conf:/fluent-bit/etc/fluent-bit.conf:ro \
cr.fluentbit.io/fluent/fluent-bit:5.1.3
```
3. Start your containers with the `fluentd` logging driver:
```bash
docker run -d \
--log-driver=fluentd \
--log-opt fluentd-address=localhost:24224 \
--log-opt fluentd-async=true \
--log-opt tag="{{.Name}}" \
nginx
```
The `fluentd-async` option lets the container start even when Fluent Bit isn’t reachable yet. Docker buffers the logs until the connection is established.
To use the driver for all new containers, set it as the default in `/etc/docker/daemon.json` and restart Docker:
```json
{
"log-driver": "fluentd",
"log-opts": {
"fluentd-address": "localhost:24224",
"fluentd-async": "true",
"tag": "{{.Name}}"
}
}
```
In Docker Compose, run Fluent Bit as a service and configure the `logging` key of each service that sends logs:
```yaml
services:
fluent-bit:
image: cr.fluentbit.io/fluent/fluent-bit:5.1.3
restart: unless-stopped
ports:
- "24224:24224"
volumes:
- ./fluent-bit.conf:/fluent-bit/etc/fluent-bit.conf:ro
api:
image: nginx
depends_on:
- fluent-bit
logging:
driver: fluentd
options:
fluentd-address: localhost:24224
fluentd-async: "true"
tag: "{{.Name}}"
```
Replace `5.1.3` with the Fluent Bit version you want to run.
If your containers write JSON log lines, add a `parser` filter between the input and the output to turn the keys of the `log` field into fields of the record:
```ini
[FILTER]
Name parser
Match *
Key_Name log
Parser json
Reserve_Data On
```
## Send Docker logs with Fluentd [#send-docker-logs-with-fluentd]
If you already run Fluentd, point Docker’s `fluentd` logging driver at its `forward` input and send the logs to Axiom with the `http` output plugin. The records contain the same `log`, `source`, `container_id`, and `container_name` fields as with Fluent Bit.
1. Create a configuration file `fluent.conf` with the following content:
```xml
@type forward
port 24224
# Keep the Docker log timestamp as the Axiom event time
@type record_transformer
enable_ruby true
_time ${time.utc.strftime('%Y-%m-%dT%H:%M:%S.%NZ')}
@type http
endpoint https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME
headers {"Authorization": "Bearer API_TOKEN"}
json_array false
open_timeout 3
@type json
flush_interval 5s
```
The `record_transformer` filter adds the event time as the `_time` field. The `http` output doesn’t include the event time in the record on its own.
2. Start Fluentd and publish port `24224` on the host:
```bash
docker run -d --name fluentd \
-p 24224:24224 \
-v $(pwd)/fluent.conf:/fluentd/etc/fluent.conf:ro \
fluent/fluentd:v1.19-2 \
-c /fluentd/etc/fluent.conf
```
3. Start your containers with the `fluentd` logging driver, as described in [Send Docker logs with Fluent Bit](#send-docker-logs-with-fluent-bit).
Replace `v1.19-2` with the Fluentd version you want to run.
If your containers write JSON log lines, add a `parser` filter before the `match` section to turn the keys of the `log` field into fields of the record:
```xml
@type parser
key_name log
reserve_data true
@type json
```
## Send Docker logs with Filebeat [#send-docker-logs-with-filebeat]
Filebeat’s `filestream` input tails the `json-file` log files, and the `container` parser extracts the log line and stream from the Docker log format. The `add_docker_metadata` processor looks up the container ID from the path of the log file and adds the container name, image, and labels to each event. Filebeat sends the events to Axiom’s Elasticsearch-compatible bulk API.
Use the open-source software (OSS) version 8.12.1 or lower of Filebeat. Other versions don’t work with Axiom. For more information, see [Send data from Elastic Beats](/send-data/elastic-beats).
1. [Install Filebeat OSS](https://www.elastic.co/downloads/beats/filebeat-oss) on the Docker host.
2. Create a configuration file `filebeat.yml` with the following content:
```yaml
setup.ilm.enabled: false
filebeat.inputs:
- type: filestream
id: docker-containers
paths:
- /var/lib/docker/containers/*/*-json.log
parsers:
- container:
stream: all
format: docker
processors:
- add_docker_metadata:
host: "unix:///var/run/docker.sock"
output.elasticsearch:
hosts: ['https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic']
api_key: 'axiom:API_TOKEN'
allow_older_versions: true
```
3. Run Filebeat as root so it can read the container log files and the Docker socket.
Filebeat stores the log line in the `message` field, the output stream in `stream`, and the Docker log timestamp in `@timestamp`. Axiom’s Elasticsearch-compatible API uses `@timestamp` as the event time.
---
# Send data from Elastic Beats to Axiom
Source: https://axiom.co/docs/send-data/elastic-beats
[Elastic Beats](https://www.elastic.co/beats/) serves as a lightweight platform for data shippers that transfer information from the source to Axiom and other tools based on the configuration. Before shipping data, it collects metrics and logs from different sources, which later are deployed to your Axiom deployments.
There are different [Elastic Beats](https://www.elastic.co/beats/) you could use to ship logs. Axiom’s documentation provides a detailed step by step procedure on how to use each Beats.
To ensure compatibility with Axiom, use the following versions:
* For Elastic Beats log shippers such as Filebeat, Metricbeat, Heartbeat, Auditbeat, and Packetbeat, use their open-source software (OSS) version 8.12.1 or lower.
* For Winlogbeat, use the OSS version 7.17.22 or lower.
* For Journalbeat, use the OSS version 7.15.2 or lower.
If you get a 400 error when you use the field name `_time` or when you override the [`timestamp` field](/reference/limits), use the query parameter `?timestamp-field` to set a field as the time field.
## Filebeat [#filebeat]
[Filebeat](https://www.elastic.co/beats/filebeat) is a lightweight shipper for logs. It helps you centralize logs and files, and can read files from your system.
Filebeats is useful for workloads, system, app log files, and data logs you would like to ingest to Axiom in some way.
In the logging case, it helps centralize logs and files in a structured pattern by reading from your various apps, services, workloads, and VMs, then shipping to your Axiom deployments.
### Installation [#installation]
Visit the [Filebeat OSS download page](https://www.elastic.co/downloads/beats/filebeat-oss) to install Filebeat. For more information, check out Filebeat’s [official documentation](https://www.elastic.co/guide/en/beats/filebeat/current/index.html)
When downloading Filebeats, install the OSS version being that the non-oss version doesn’t work with Axiom.
### Configuration [#configuration]
Axiom lets you ingest data with the ElasticSearch bulk ingest API.
In order for Filebeat to work, disable index lifecycle management (ILM). To do so, `add setup.ilm.enabled: false` to the `filebeat.yml` configuration file.
```yaml
setup.ilm.enabled: false
filebeat.inputs:
- type: log
# Specify the path of the system log files to be sent to Axiom deployment.
paths:
- $PATH_TO_LOG_FILE
output.elasticsearch:
hosts: ['https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic']
api_key: 'axiom:API_TOKEN'
allow_older_versions: true
```
## Metricbeat [#metricbeat]
[Metricbeat](https://www.elastic.co/beats/metricbeat) is a lightweight shipper for metrics.
Metricbeat is installed on your systems and services and used for monitoring their performance, as well as different remote packages/utilities running on them.
### Installation [#installation-1]
Visit the [MetricBeat OSS download page](https://www.elastic.co/downloads/beats/metricbeat-oss) to install Metricbeat. For more information, check out Metricbeat’s [official documentation](https://www.elastic.co/guide/en/beats/metricbeat/current/index.html)
### Configuration [#configuration-1]
```yaml
setup.ilm.enabled: false
metricbeat.config.modules:
path:
-$PATH_TO_LOG_FILE
metricbeat.modules:
- module: system
metricsets:
- filesystem
- cpu
- load
- fsstat
- memory
- network
output.elasticsearch:
hosts: ["https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic"]
# Specify Axiom API token
api_key: 'axiom:API_TOKEN'
allow_older_versions: true
```
### Send AWS RDS metric set to Axiom [#send-aws-rds-metric-set-to-axiom]
The RDS metric set enables you to monitor your AWS RDS service. [RDS metric set](https://www.elastic.co/guide/en/beats/metricbeat/current/metricbeat-metricset-aws-rds.html) fetches a set of metrics from Amazon RDS and Amazon Aurora DB. With Amazon RDS, users can monitor network throughput, I/O for read, write, and/or metadata operations, client connections, and burst credit balances for their DB instances and send the data to Axiom.
```yaml
setup.ilm.enabled: false
metricbeat.config.modules:
path:
-$PATH_TO_LOG_FILE
metricbeat.modules:
- module: aws
period: 60s
metricsets:
- rds
access_key_id: ''
secret_access_key: ''
session_token: ''
# Add other AWS configurations if needed
output.elasticsearch:
hosts: ["https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic"]
api_key: 'axiom:API_TOKEN'
allow_older_versions: true
```
## Winlogbeat [#winlogbeat]
[Winlogbeat](https://www.elastic.co/guide/en/beats/winlogbeat/current/index.html) is an open-source Windows specific event-log shipper that’s installed as a Windows service. It can be used to collect and send event logs to Axiom.
Winlogbeat reads from one or more event logs using Windows APIs, filters the events based on user-configured criteria, then sends the event data to the configured outputs.
You can Capture:
* app events
* hardware events
* security events
* system events
### Installation [#installation-2]
Visit the [Winlogbeat download page](https://www.elastic.co/downloads/beats/winlogbeat) to install Winlogbeat. For more information, check out Winlogbeat’s [official documentation](https://www.elastic.co/guide/en/beats/winlogbeat/current/winlogbeat-installation-configuration.html)
* Extract the contents of the zip file into `C:\Program Files`.
* Rename the `winlogbeat-$version` directory to Winlogbeat
* Open a PowerShell prompt as an Administrator and run
```bash
PS C:\Users\Administrator> cd C:\Program Files\Winlogbeat
PS C:\Program Files\Winlogbeat> .\install-service-winlogbeat.ps1
```
### Configuration [#configuration-2]
Configuration for Winlogbeat Service is found in the `winlogbeat.yml` file in `C:\Program Files\Winlogbeat.`
Edit the `winlogbeat.yml` configuration file found in `C:\Program Files\Winlogbeat` to send data to Axiom.
The `winlogbeat.yml` file contains the configuration on which windows events and service it should monitor and the time required.
```yaml
winlogbeat.event_logs:
- name: Application
- name: System
- name: Security
logging.to_files: true
logging.files:
path: C:\ProgramData\Winlogbeat\Logs
logging.level: info
output.elasticsearch:
hosts: ['https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic']
# token should be an API token
api_key: 'axiom:API_TOKEN'
allow_older_versions: true
```
#### Validate configuration [#validate-configuration]
```bash
# Check if your configuration is correct
PS C:\Program Files\Winlogbeat> .\winlogbeat.exe test config -c .\winlogbeat.yml -e
```
#### Start Winlogbeat [#start-winlogbeat]
```bash
PS C:\Program Files\Winlogbeat> Start-Service winlogbeat
```
You can view the status of your service and control it from the Services management console in Windows.
To launch the management console, run this command:
```bash
PS C:\Program Files\Winlogbeat> services.msc
```
#### Stop Winlogbeat [#stop-winlogbeat]
```bash
PS C:\Program Files\Winlogbeat> Stop-Service winlogbeat
```
### Ignore older Winlogbeat configuration [#ignore-older-winlogbeat-configuration]
The `ignore_older` option in the Winlogbeat configuration is used to ignore older events.
Winlogbeat reads from the Windows event log system. When it starts up, it starts reading from a specific point in the event log. By default, Winlogbeat starts reading new events created after Winlogbeat started.
However, you might want Winlogbeat to read some older events as well. For instance, if you restart Winlogbeat, you might want it to continue where it left off, rather than skipping all the events that were created while it wasn’t running. In this case, you can use the `ignore_older` option to specify how old events Winlogbeat should read. The `ignore_older` option takes a duration as a value. Any events that are older than this duration are ignored. The duration is a string of a number followed by a unit. Units can be one of `ms` (milliseconds), `s` (seconds), `m` (minutes), `h` (hours) or `d` (days).
```yaml
winlogbeat.event_logs:
- name: Application
ignore_older: 72h
output.elasticsearch:
hosts: ['https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic']
protocol: "https"
ssl.verification_mode: "full"
# token should be an API token
api_key: 'axiom:API_TOKEN'
allow_older_versions: true
```
You can start Winlogbeat from the command line by running `.\winlogbeat.exe -c winlogbeat.yml` in the Winlogbeat installation directory.
### Add verification modes and processors [#add-verification-modes-and-processors]
Verification mode refers to the SSL/TLS verification performed when Winlogbeat connects to your output destination, for instance, a Logstash instance, ElasticSearch instance or an Axiom instance. You can add your verification modes, additional processors data, and multiple windows event logs to you configurations and send the logs to Axiom. The configuration is specified in the`winlogbeat.event_logs` configuration option.
```yaml
winlogbeat.event_logs:
- name: Application
ignore_older: 72h
- name: Security
- name: System
output.elasticsearch:
hosts: ['https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic']
# token should be an API token
api_key: 'axiom:API_TOKEN'
allow_older_versions: true
ssl.verification_mode: "certificate"
processors:
- add_host_metadata: ~
- add_cloud_metadata: ~
logging.level: info
logging.to_files: true
logging.files:
path: C:/ProgramData/winlogbeat/Logs
name: winlogbeat
keepfiles: 7
permissions: 0600
```
You can start Winlogbeat from the command line by running `.\winlogbeat.exe -c winlogbeat.yml` in the Winlogbeat installation directory.
For more information on Winlogbeat event logs, visit the Winlogbeat [documentation](https://www.elastic.co/guide/en/beats/winlogbeat/current/index.html).
## Heartbeat [#heartbeat]
[Heartbeat](https://www.elastic.co/guide/en/beats/heartbeat/current/heartbeat-overview.html) is a lightweight shipper for uptime monitoring.
It monitors your services and sends response time to Axiom. It lets you periodically check the status of your services and determine whether they’re available.
Heartbeat is useful when you need to verify that you’re meeting your service level agreements for service uptime.
Heartbeat currently supports monitors for checking hosts via:
* ICMP (v4 and v6) echo requests: Use the `icmp monitor` when you simply want to check whether a service is available. This monitor requires root access.
* TCP: Use the TCP monitor to connect `via TCP.` You can optionally configure this monitor to verify the endpoint by sending and/or receiving a custom payload.
* HTTP: Use the HTTP monitor to connect `via HTTP.` You can optionally configure this monitor to verify that the service returns the expected response, such as a specific status code, response header, or content.
### Installation [#installation-3]
Visit the [Heartbeat download page](https://www.elastic.co/guide/en/beats/heartbeat/current/heartbeat-installation-configuration.html#installation) to install Heartbeat on your system.
### Configuration [#configuration-3]
Heartbeat provides monitors to check the status of hosts at set intervals. Heartbeat currently provides monitors for ICMP, TCP, and HTTP.
You configure each monitor individually. In `heartbeat.yml`, specify the list of monitors that you want to enable. Each item in the list begins with a dash (-).
The example below configures Heartbeat to use three monitors: an ICMP monitor, a TCP monitor, and an HTTP monitor deployed instantly to Axiom.
```yaml
# Disable index lifecycle management (ILM)
setup.ilm.enabled: false
heartbeat.monitors:
- type: icmp
schedule: '*/5 * * * * * *'
hosts: ['myhost']
id: my-icmp-service
name: My ICMP Service
- type: tcp
schedule: '@every 5s'
hosts: ['myhost:12345']
mode: any
id: my-tcp-service
- type: http
schedule: '@every 5s'
urls: ['http://example.net']
service.name: apm-service-name
id: my-http-service
name: My HTTP Service
output.elasticsearch:
hosts: ['https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic']
# token should be an API token
api_key: 'axiom:API_TOKEN'
allow_older_versions: true
```
## Auditbeat [#auditbeat]
Auditbeat is a lightweight shipper that ships events in real time to Axiom for further analysis. It Collects your Linux audit framework data and monitor the integrity of your files. It’s also used to evaluate the activities of users and processes on your system.
You can also use Auditbeat to detect changes to critical files, like binaries and configuration files, and identify potential security policy violations.
### Installation [#installation-4]
Visit the [Auditbeat download page](https://www.elastic.co/downloads/beats/auditbeat) to install Auditbeat on your system.
### Configuration [#configuration-4]
Auditbeat uses modules to collect audit information:
* Auditd
* File integrity
* System
By default, Auditbeat uses a configuration that’s tailored to the operating system where Auditbeat is running.
To use a different configuration, change the module settings in `auditbeat.yml.`
The example below configures Auditbeat to use the `file_integrity` module configured to generate events whenever a file in one of the specified paths changes on disk. The events contains the file metadata and hashes, and it’s deployed instantly to Axiom.
```yaml
# Disable index lifecycle management (ILM)
setup.ilm.enabled: false
auditbeat.modules:
- module: file_integrity
paths:
- /usr/bin
- /sbin
- /usr/sbin
- /etc
- /bin
- /usr/local/sbin
output.elasticsearch:
hosts: ['https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic']
# token should be an API token
api_key: 'axiom:API_TOKEN'
allow_older_versions: true
```
## Packetbeat [#packetbeat]
Packetbeat is a real-time network packet analyzer that you can integrate with Axiom to provide an app monitoring and performance analytics system between the servers of your network.
With Axiom you can use Packetbeat to capture the network traffic between your app servers, decode the app layer protocols (HTTP, MySQL, Redis, PGSQL, Thrift, MongoDB, and so on), and correlate the requests with the responses.
Packetbeat sniffs the traffic between your servers, and parses the app-level protocols on the fly directly into Axiom.
Currently, Packetbeat supports the following protocols:
* ICMP (v4 and v6)
* DHCP (v4)
* DNS
* HTTP
* AMQP 0.9.1
* Cassandra
* MySQL
* PostgreSQL
* Redis
* Thrift-RPC
* MongoDB
* MemCache
* NFS
* TLS
* SIP/SDP (beta)
### Installation [#installation-5]
Visit the [Packetbeat download page](https://www.elastic.co/downloads/beats/packetbeat) to install Packetbeat on your system.
### Configuration [#configuration-5]
In `packetbeat.yml`, configure the network devices and protocols to capture traffic from.
To see a list of available devices for `packetbeat.yml` configuration , run:
| OS type | Command |
| ------- | -------------------------------------------------------------- |
| DEB | Run `packetbeat devices` |
| RPM | Run `packetbeat devices` |
| MacOS | Run `./packetbeat devices` |
| Brew | Run `packetbeat devices` |
| Linux | Run `./packetbeat devices` |
| Windows | Run `PS C:\Program Files\Packetbeat> .\packetbeat.exe devices` |
Packetbeat supports these sniffer types:
* `pcap`
* `af_packet`
In the protocols section, configure the ports where Packetbeat can find each protocol. If you use any non-standard ports, add them here. Otherwise, use the default values:
```yaml
# Disable index lifecycle management (ILM)
setup.ilm.enabled: false
packetbeat.interfaces.auto_promisc_mode: true
packetbeat.flows:
timeout: 30s
period: 10s
protocols:
dns:
ports: [53]
include_authorities: true
include_additionals: true
http:
ports: [80, 8080, 8081, 5000, 8002]
memcache:
ports: [11211]
mysql:
ports: [3306]
pgsql:
ports: [5432]
redis:
ports: [6379]
thrift:
ports: [9090]
mongodb:
ports: [27017]
output.elasticsearch:
hosts: ['https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic']
# api_key should be your API token
api_key: 'axiom:API_TOKEN'
allow_older_versions: true
```
For more information on configuring Packetbeats, visit the [documentation](https://www.elastic.co/guide/en/beats/packetbeat/current/configuring-howto-packetbeat.html).
## Journalbeat [#journalbeat]
Journalbeat is a lightweight shipper for forwarding and centralizing log data from [systemd journals](https://www.freedesktop.org/software/systemd/man/systemd-journald.service.html) to a log management tool like Axiom.
Journalbeat monitors the journal locations that you specify, collects log events, and eventually forwards the logs to Axiom.
### Installation [#installation-6]
Visit the [Journalbeat download page](https://www.elastic.co/guide/en/beats/journalbeat/current/journalbeat-installation-configuration.html) to install Journalbeat on your system.
### Configuration [#configuration-6]
Before running Journalbeat, specify the location of the systemd journal files and configure how you want the files to be read.
The example below configures Journalbeat to use the `path` of your systemd journal files. Each path can be a directory path (to collect events from all journals in a directory), or a path configured to deploy logs instantly to Axiom.
```yaml
# Disable index lifecycle management (ILM)
setup.ilm.enabled: false
journalbeat.inputs:
- paths:
- "/dev/log"
- "/var/log/messages/my-journal-file.journal"
seek: head
journalbeat.inputs:
- paths: []
include_matches:
- "CONTAINER_TAG=redis"
- "_COMM=redis"
- "container.image.tag=redis"
- "process.name=redis"
output.elasticsearch:
hosts: ['https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic']
# token should be an API token
api_key: 'axiom:API_TOKEN'
allow_older_versions: true
```
For more information on configuring Journalbeat, visit the [documentation](https://www.elastic.co/guide/en/beats/journalbeat/current/configuration-journalbeat-options.html).
---
# Send data from Elastic Bulk API to Axiom
Source: https://axiom.co/docs/send-data/elasticsearch-bulk-api
Axiom is a log management platform that offers an Elasticsearch Bulk API emulation to facilitate migration from Elasticsearch or integration with tools that support the Elasticsearch Bulk API.
Using the Elastic Bulk API and Axiom in your app provides a robust way to store and manage logs.
The Elasticsearch Bulk API expects the timestamp to be formatted as `@timestamp`, not `_time`. For example:
```json
{"index": {"_index": "myindex", "_id": "1"}}
{"@timestamp": "2024-01-07T12:00:00Z", "message": "axiom elastic bulk", "severity": "INFO"}
```
## Send logs to Axiom using the Elasticsearch Bulk API and Go [#send-logs-to-axiom-using-the-elasticsearch-bulk-api-and-go]
To send logs to Axiom using the Elasticsearch Bulk API and Go, use the `net/http` package to create and send the HTTP request.
### Prepare your data [#prepare-your-data]
The data needs to be formatted as per the Bulk API’s requirements. Here’s a simple example of how to prepare your data:
```json
data :=
{"index": {"_index": "myindex", "_id": "1"}}
{"@timestamp": "2023-06-06T12:00:00Z", "message": "axiom elastic bulk", "severity": "INFO"}
{"index": {"_index": "myindex", "_id": "2"}}
{"@timestamp": "2023-06-06T12:00:01Z", "message": "axiom elastic bulk api", "severity": "ERROR"}
```
### Send data to Axiom [#send-data-to-axiom]
Get an Axiom [API token](/reference/tokens) for the Authorization header, and create a [dataset](/reference/datasets).
```go
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
data := []byte(`{"index": {"_index": "myindex", "_id": "1"}}
{"@timestamp": "2023-06-06T12:00:00Z", "message": "axiom elastic bulk", "severity": "INFO"}
{"index": {"_index": "myindex", "_id": "2"}}
{"@timestamp": "2023-06-06T12:00:01Z", "message": "axiom elastic bulk api", "severity": "ERROR"}
`)
// Create a new request using http
req, err := http.NewRequest("POST", "https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic/_bulk", bytes.NewBuffer(data))
if err != nil {
log.Fatalf("Error creating request: %v", err)
}
// Add authorization header to the request
req.Header.Add("Authorization", "Bearer API_TOKEN")
req.Header.Add("Content-Type", "application/x-ndjson")
// Send request using http.Client
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Error on response: %v", err)
}
defer resp.Body.Close()
// Read and print the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error reading response body: %v", err)
}
fmt.Printf("Response status: %s\nResponse body: %s\n", resp.Status, string(body))
}
```
## Send logs to Axiom using the Elasticsearch Bulk API and Python [#send-logs-to-axiom-using-the-elasticsearch-bulk-api-and-python]
To send logs to Axiom using the Elasticsearch Bulk API and Python, use the built-in `requests` library.
### Prepare your data [#prepare-your-data-1]
The data sent needs to be formatted as per the Bulk API’s requirements. Here’s a simple example of how to prepare the data:
```json
data = """
{"index": {"_index": "myindex", "_id": "1"}}
{"@timestamp": "2023-06-06T12:00:00Z", "message": "Log message 1", "severity": "INFO"}
{"index": {"_index": "myindex", "_id": "2"}}
{"@timestamp": "2023-06-06T12:00:01Z", "message": "Log message 2", "severity": "ERROR"}
"""
```
### Send data to Axiom [#send-data-to-axiom-1]
Obtain an Axiom [API token](/reference/tokens) for the Authorization header, and [dataset](/reference/datasets).
```py
import requests
import json
data = """
{"index": {"_index": "myindex", "_id": "1"}}
{"@timestamp": "2024-01-07T12:00:00Z", "message": "axiom elastic bulk", "severity": "INFO"}
{"index": {"_index": "myindex", "_id": "2"}}
{"@timestamp": "2024-01-07T12:00:01Z", "message": "Log message 2", "severity": "ERROR"}
"""
# Replace these with your actual dataset name and API token
dataset = "DATASET_NAME"
api_token = "API_TOKEN"
# The URL for the bulk API
url = f'https://AXIOM_DOMAIN:443/v1/ingest/{dataset}/elastic/_bulk'
try:
response = requests.post(
url,
data=data,
headers={
'Content-Type': 'application/x-ndjson',
'Authorization': f'Bearer {api_token}'
}
)
response.raise_for_status()
except requests.HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
print('Response:', response.text)
except Exception as err:
print(f'Other error occurred: {err}')
else:
print('Success!')
try:
print(response.json())
except json.JSONDecodeError:
print(response.text)
```
## Send logs to Axiom using the Elasticsearch Bulk API and JavaScript [#send-logs-to-axiom-using-the-elasticsearch-bulk-api-and-javascript]
Use the axios library in JavaScript to send logs to Axiom using the Elasticsearch Bulk API.
### Prepare your data [#prepare-your-data-2]
The data sent needs to be formatted as per the Bulk API’s requirements. Here’s a simple example of how to prepare the data:
```json
let data = `
{"index": {"_index": "myindex", "_id": "1"}}
{"@timestamp": "2023-06-06T12:00:00Z", "message": "Log message 1", "severity": "INFO"}
{"index": {"_index": "myindex", "_id": "2"}}
{"@timestamp": "2023-06-06T12:00:01Z", "message": "Log message 2", "severity": "ERROR"}
`;
```
### Send data to Axiom [#send-data-to-axiom-2]
Obtain an Axiom [API token](/reference/tokens) for the Authorization header, and [dataset](/reference/datasets).
```js
const axios = require('axios');
// Axiom elastic API URL
const AxiomApiUrl = 'https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic/_bulk';
// Your Axiom API token
const AxiomToken = 'API_TOKEN';
// The logs data retrieved from Elasticsearch
const logs = [
{"index": {"_index": "myindex", "_id": "1"}},
{"@timestamp": "2023-06-06T12:00:00Z", "message": "axiom logging", "severity": "INFO"},
{"index": {"_index": "myindex", "_id": "2"}},
{"@timestamp": "2023-06-06T12:00:01Z", "message": "axiom log data", "severity": "ERROR"}
];
// Convert the logs to a single string with newline separators
const data = logs.map(log => JSON.stringify(log)).join('\n') + '\n';
axios.post(AxiomApiUrl, data, {
headers: {
'Content-Type': 'application/x-ndjson',
'Authorization': `Bearer ${AxiomToken}`
}
})
.then((response) => {
console.log('Response Status:', response.status);
console.log('Response Data:', response.data);
})
.catch((error) => {
console.error('Error:', error.response ? error.response.data : error.message);
});
```
## Send logs to Axiom using the Elasticsearch Bulk API and PHP [#send-logs-to-axiom-using-the-elasticsearch-bulk-api-and-php]
To send logs from PHP to Axiom using the Elasticsearch Bulk API, make sure you have installed the necessary PHP libraries: [Guzzle](https://docs.guzzlephp.org/en/stable/overview.html) for making HTTP requests and [JsonMachine](https://packagist.org/packages/halaxa/json-machine) for handling newline-delimited JSON data.
### Prepare your data [#prepare-your-data-3]
The data sent needs to be formatted as per the Bulk API’s requirements. Here’s a simple example of how to prepare the data:
```json
$data = << 'https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic/_bulk', // Update with your Axiom host
'timeout' => 2.0,
]);
// Your Axiom API token
$AxiomToken = 'API_TOKEN';
// The logs data retrieved from Elasticsearch
// Note: Replace this with your actual code to retrieve logs from Elasticsearch
$logs = [
["@timestamp" => "2023-06-06T12:00:00Z", "message" => "axiom logger", "severity" => "INFO"],
["@timestamp" => "2023-06-06T12:00:01Z", "message" => "axiom logging elasticsearch", "severity" => "ERROR"]
];
$events = array_map(function ($log) {
return [
'@timestamp' => $log['@timestamp'],
'attributes' => $log
];
}, $logs);
// Create the payload for Axiom
$payload = [
'tags' => [
'source' => 'myapplication',
'host' => 'myhost'
],
'events' => $events
];
try {
$response = $client->post('', [
'headers' => [
'Authorization' => 'Bearer ' . $AxiomToken,
'Content-Type' => 'application/x-ndjson',
],
'json' => $payload,
]);
// handle response here
$statusCode = $response->getStatusCode();
$content = $response->getBody();
echo "Status code: $statusCode \nContent: $content";
} catch (\Exception $e) {
// handle exception here
echo "Error: " . $e->getMessage();
}
```
---
# Send data from Fluent Bit to Axiom
Source: https://axiom.co/docs/send-data/fluent-bit
Fluent Bit is an open-source log processor and forwarder that allows you to collect any data like metrics and logs from different sources, enrich them with filters, and send them to multiple destinations like Axiom.
* [Install Fluent Bit](https://docs.fluentbit.io/manual/installation/getting-started-with-fluent-bit).
## Configure Fluent Bit [#configure-fluent-bit]
1. Set up the Fluent Bit configuration file based on the [Fluent Bit documentation](https://docs.fluentbit.io/manual/administration/configuring-fluent-bit/classic-mode/configuration-file).
2. In the Fluent Bit configuration file, use the HTTP output plugin with the following configuration. For more information on the plugin, see the [Fluent Bit documentation](https://docs.fluentbit.io/manual/pipeline/outputs/http).
```ini
[OUTPUT]
Name http
Match *
Host AXIOM_DOMAIN
Port 443
URI /v1/ingest/DATASET_NAME
Header Authorization Bearer API_TOKEN
Compress gzip
Format json
JSON_Date_Key _time
JSON_Date_Format iso8601
TLS On
```
---
# Send data from Fluentd to Axiom
Source: https://axiom.co/docs/send-data/fluentd
Fluentd is an open-source log collector that allows you to collect, aggregate, process, analyze, and route log files.
With Fluentd, you can collect logs from multiple sources and ship it instantly into Axiom
## Installation [#installation]
Visit the [Fluentd download page](https://www.fluentd.org/download) to install Fluentd on your system.
## Configuration [#configuration]
Fluentd lifecycle consist of five different components which are:
* Setup: Configure your `fluent.conf` file.
* Inputs: Define your input listeners.
* Filters: Create a rule to allow or disallow an event.
* Matches: Send output to Axiom when input data match and pair specific data from your data input within your configuration.
* Labels: Groups filters and simplifies tag handling.
When setting up Fluentd, the configuration file `.conf` is used to connect its components.
## Configuring Fluentd using the HTTP output plugin [#configuring-fluentd-using-the-http-output-plugin]
The example below shows a Fluentd configuration that sends data to Axiom using the [HTTP output plugin](https://docs.fluentd.org/output/http):
```xml
@type forward
port 24224
@type http
endpoint https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME
# Authorization Bearer should be an ingest token
headers {"Authorization": "Bearer API_TOKEN"}
json_array false
open_timeout 3
@type json
flush_interval 5s
```
## Configuring Fluentd using the OpenSearch output plugin [#configuring-fluentd-using-the-opensearch-output-plugin]
The example below shows a Fluentd configuration that sends data to Axiom using the [OpenSearch plugin](https://docs.fluentd.org/output/opensearch):
```xml
@type tail
@id input_tail
@type apache2
path /var/log/*.log
tag td.logs
@type opensearch
@id out_os
@log_level info
include_tag_key true
include_timestamp true
host "#{ENV['FLUENT_OPENSEARCH_HOST'] || 'AXIOM_DOMAIN'}"
port "#{ENV['FLUENT_OPENSEARCH_PORT'] || '443'}"
path "#{ENV['FLUENT_OPENSEARCH_PATH']|| '/v1/ingest/DATASET_NAME/elastic'}"
scheme "#{ENV['FLUENT_OPENSEARCH_SCHEME'] || 'https'}"
ssl_verify "#{ENV['FLUENT_OPENSEARCH_SSL_VERIFY'] || 'true'}"
ssl_version "#{ENV['FLUENT_OPENSEARCH_SSL_VERSION'] || 'TLSv1_2'}"
user "#{ENV['FLUENT_OPENSEARCH_USER'] || 'axiom'}"
password "#{ENV['FLUENT_OPENSEARCH_PASSWORD'] || 'xaat-xxxxxxxxxx-xxxxxxxxx-xxxxxxx'}"
index_name "#{ENV['FLUENT_OPENSEARCH_INDEX_NAME'] || 'fluentd'}"
```
## Configure buffer interval with filter patterns [#configure-buffer-interval-with-filter-patterns]
The example below shows a Fluentd configuration to hold logs in memory with specific flush intervals, size limits, and how to exclude specific logs based on patterns.
```xml
# Collect common system logs
@type tail
@id system_logs
@type none
path /var/log/*.log
pos_file /var/log/fluentd/system.log.pos
read_from_head true
tag system.logs
# Collect Apache2 logs (if they’re located in /var/log/apache2/)
@type tail
@id apache_logs
@type apache2
path /var/log/apache2/*.log
pos_file /var/log/fluentd/apache2.log.pos
read_from_head true
tag apache.logs
# Filter to exclude certain patterns (optional)
@type grep
key message
pattern /exclude_this_pattern/
# Send logs to Axiom
@type opensearch
@id out_os
@log_level info
include_tag_key true
include_timestamp true
host "#{ENV['FLUENT_OPENSEARCH_HOST'] || 'AXIOM_DOMAIN'}"
port "#{ENV['FLUENT_OPENSEARCH_PORT'] || '443'}"
path "#{ENV['FLUENT_OPENSEARCH_PATH']|| '/v1/ingest/DATASET_NAME/elastic'}"
scheme "#{ENV['FLUENT_OPENSEARCH_SCHEME'] || 'https'}"
ssl_verify "#{ENV['FLUENT_OPENSEARCH_SSL_VERIFY'] || 'true'}"
ssl_version "#{ENV['FLUENT_OPENSEARCH_SSL_VERSION'] || 'TLSv1_2'}"
user "#{ENV['FLUENT_OPENSEARCH_USER'] || 'axiom'}"
password "#{ENV['FLUENT_OPENSEARCH_PASSWORD'] || 'xaat-xxxxxxxxxx-xxxxxxxxx-xxxxxxx'}"
index_name "#{ENV['FLUENT_OPENSEARCH_INDEX_NAME'] || 'fluentd'}"
@type memory
flush_mode interval
flush_interval 10s
chunk_limit_size 5M
retry_max_interval 30
retry_forever true
```
## Collect and send PHP logs to Axiom [#collect-and-send-php-logs-to-axiom]
The example below shows a Fluentd configuration that sends PHP data to Axiom.
```xml
# Collect PHP logs
@type tail
@id php_logs
@type multiline
format_firstline /^\[\d+-\w+-\d+ \d+:\d+:\d+\]/
format1 /^\[(?\d+-\w+-\d+ \d+:\d+:\d+)\] (?.*)/
path /var/log/php*.log
pos_file /var/log/fluentd/php.log.pos
read_from_head true
tag php.logs
# Send PHP logs to Axiom
@type opensearch
@id out_os
@log_level info
include_tag_key true
include_timestamp true
host "#{ENV['FLUENT_OPENSEARCH_HOST'] || 'AXIOM_DOMAIN'}"
port "#{ENV['FLUENT_OPENSEARCH_PORT'] || '443'}"
path "#{ENV['FLUENT_OPENSEARCH_PATH']|| '/v1/ingest/DATASET_NAME/elastic'}"
scheme "#{ENV['FLUENT_OPENSEARCH_SCHEME'] || 'https'}"
ssl_verify "#{ENV['FLUENT_OPENSEARCH_SSL_VERIFY'] || 'true'}"
ssl_version "#{ENV['FLUENT_OPENSEARCH_SSL_VERSION'] || 'TLSv1_2'}"
user "#{ENV['FLUENT_OPENSEARCH_USER'] || 'axiom'}"
password "#{ENV['FLUENT_OPENSEARCH_PASSWORD'] || 'xaat-xxxxxxxxxx-xxxxxxxxx-xxxxxxx'}"
index_name "#{ENV['FLUENT_OPENSEARCH_INDEX_NAME'] || 'php-logs'}"
@type memory
flush_mode interval
flush_interval 10s
chunk_limit_size 5M
retry_max_interval 30
retry_forever true
```
## Collect and send Scala logs to Axiom [#collect-and-send-scala-logs-to-axiom]
The example below shows a Fluentd configuration that sends Scala data to Axiom
```xml
# Collect Scala logs
@type tail
@id scala_logs
@type multiline
format_firstline /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}/
format1 /^(?\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}) \[(?.*)\] (?\w+) (?[\w\.$]+) - (?.*)/
path /var/log/scala-app.log
pos_file /var/log/fluentd/scala.log.pos
read_from_head true
tag scala.logs
# Send Scala logs using HTTP plugin to Axiom
@type http
endpoint "#{ENV['FLUENT_HTTP_ENDPOINT'] || 'https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME'}"
headers {"Authorization": "Bearer #{ENV['FLUENT_HTTP_TOKEN'] || ''}"}
@type json
@type memory
flush_mode interval
flush_interval 10s
chunk_limit_size 5M
retry_max_interval 30
retry_forever true
```
## Send virtual machine logs to Axiom using the HTTP output plugin [#send-virtual-machine-logs-to-axiom-using-the-http-output-plugin]
The example below shows a Fluentd configuration that sends data from your virtual machine to Axiom using the `apache` source type.
```xml
@type tail
@id input_tail
@type apache2
path /var/log/**/*.log
pos_file /var/log/fluentd/fluentd.log.pos
tag vm.logs
read_from_head true
@type record_transformer
hostname "#{Socket.gethostname}"
service "vm_service"
@type http
@id out_http_axiom
@log_level info
endpoint "#{ENV['AXIOM_URL'] || 'https://AXIOM_DOMAIN'}"
path "/v1/ingest/DATASET_NAME"
ssl_verify "#{ENV['AXIOM_SSL_VERIFY'] || 'true'}"
Authorization "Bearer API_TOKEN"
Content-Type "application/json"
@type json
@type memory
flush_mode interval
flush_interval 5s
chunk_limit_size 5MB
retry_forever true
```
The example below shows a Fluentd configuration that sends data from your virtual machine to Axiom using the `nginx` source type.
```xml
@type tail
@id input_tail
@type nginx
path /var/log/nginx/access.log, /var/log/nginx/error.log
pos_file /var/log/fluentd/nginx.log.pos
tag nginx.logs
read_from_head true
@type record_transformer
hostname "#{Socket.gethostname}"
service "nginx"
@type http
@id out_http_axiom
@log_level info
endpoint "#{ENV['AXIOM_URL'] || 'https://AXIOM_DOMAIN'}"
path "/v1/ingest/DATASET_NAME"
ssl_verify "#{ENV['AXIOM_SSL_VERIFY'] || 'true'}"
Authorization "Bearer API_TOKEN"
Content-Type "application/json"
@type json
@type memory
flush_mode interval
flush_interval 5s
chunk_limit_size 5MB
retry_forever true
```
---
# Send data from Heroku Log Drains to Axiom
Source: https://axiom.co/docs/send-data/heroku-log-drains
Use [Heroku Log Drains](https://devcenter.heroku.com/articles/log-drains) to send data from your Heroku apps and deployments to Axiom.
With Heroku Log Drains, you can only send data to the US East 1 (AWS) edge deployment. For more information, see [Edge deployments](/reference/edge-deployments).
* [Create an account on Heroku](https://heroku.com/).
* [Download and install the Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli).
* [Create a Heroku app](https://devcenter.heroku.com/articles/creating-apps).
## Setup [#setup]
Configure Heroku Log Drains:
```bash
heroku drains:add "https://axiom:API_TOKEN@api.axiom.co/v1/datasets/DATASET_NAME/ingest" -a HEROKU_APPLICATION_NAME
```
Replace `HEROKU_APPLICATION_NAME` with the name of the Heroku app.
---
# Send data from Honeycomb to Axiom
Source: https://axiom.co/docs/send-data/honeycomb
This page explains how to send data from Honeycomb-instrumented apps to Axiom. Choose the option that matches your instrumentation:
* If your apps use OpenTelemetry-based Honeycomb SDKs or distributions, point the OTLP exporter at Axiom. This is the recommended option.
* If your apps use Libhoney or Beelines, run the Axiom Honeycomb Proxy and point the SDK at the proxy.
## Send data with OpenTelemetry [#send-data-with-opentelemetry]
Honeycomb recommends OpenTelemetry for instrumenting apps, and its language distributions are OpenTelemetry-based. Configure the OTLP exporter to send data to Axiom instead of Honeycomb:
* Set the endpoint to `https://AXIOM_DOMAIN`.
* Set the `Authorization` header to `Bearer API_TOKEN`.
* Set the `X-Axiom-Dataset` header to the name of the Axiom dataset where you want to send data.
For configuration details and language-specific guides, see [Send OpenTelemetry data to Axiom](/send-data/opentelemetry).
## Send data with the Axiom Honeycomb Proxy [#send-data-with-the-axiom-honeycomb-proxy]
The [Axiom Honeycomb Proxy](https://github.com/axiomhq/axiom-honeycomb-proxy) is an open-source server that accepts Honeycomb event and batch requests and forwards them to Axiom. Use it with Libhoney and Beelines, or with any other tool that speaks the Honeycomb events API.
### Install and run the proxy [#install-and-run-the-proxy]
1. Download a [release from GitHub](https://github.com/axiomhq/axiom-honeycomb-proxy/releases/latest), install it with Homebrew (`brew install axiomhq/tap/axiom-honeycomb-proxy`), or use the [Docker image](https://hub.docker.com/r/axiomhq/axiom-honeycomb-proxy).
2. Create the Axiom datasets you want to send data to. Honeycomb creates datasets when you send data to them, but Axiom doesn’t. The proxy sends data to the Axiom dataset with the same name as the Honeycomb dataset in the request.
3. Set the `AXIOM_TOKEN` environment variable to an Axiom API token with ingest permission for the datasets. The proxy sends data to Axiom through `https://api.axiom.co`.
4. Run the proxy. By default, it listens on port `8080` and forwards each request to both Axiom and Honeycomb. Pass `-bypass` to send data to Axiom only.
For example, with Docker:
```shell
docker run -p8080:8080/tcp \
-e=AXIOM_TOKEN=API_TOKEN \
axiomhq/axiom-honeycomb-proxy -bypass
```
### Configure the Honeycomb SDK [#configure-the-honeycomb-sdk]
In your app, set `APIHost` to the address of the proxy, for example `http://localhost:8080`. Keep the Honeycomb API key and dataset name as they are: the proxy passes the API key through to Honeycomb when it’s not in bypass mode, and uses the dataset name to select the Axiom dataset.
## Examples [#examples]
### Send events from Libhoney for JavaScript [#send-events-from-libhoney-for-javascript]
```js
const Libhoney = require('libhoney');
const hny = new Libhoney({
writeKey: 'HONEYCOMB_API_KEY',
dataset: 'DATASET_NAME',
apiHost: 'http://localhost:8080',
});
hny.sendNow({ message: 'Welcome to Axiom!' });
```
### Send events from Libhoney for Python [#send-events-from-libhoney-for-python]
```py
import libhoney
libhoney.init(writekey="HONEYCOMB_API_KEY", dataset="DATASET_NAME", api_host="http://localhost:8080")
event = libhoney.new_event()
event.add_field("foo", "bar")
event.add({"message": "Welcome to Axiom!"})
event.send()
```
### Send events from Libhoney for Go [#send-events-from-libhoney-for-go]
```go
package main
import (
"github.com/honeycombio/libhoney-go"
)
func main() {
libhoney.Init(libhoney.Config{
WriteKey: "HONEYCOMB_API_KEY",
Dataset: "DATASET_NAME",
APIHost: "http://localhost:8080",
})
defer libhoney.Close() // Flush any pending events
var ev = libhoney.NewEvent()
ev.Add(map[string]interface{}{
"duration_ms": 155.67,
"method": "post",
"hostname": "web-1",
"payload_length": 43,
})
ev.Send()
}
```
---
# Send data from Kubernetes Cluster to Axiom
Source: https://axiom.co/docs/send-data/kubernetes
Axiom makes it easy to collect, analyze, and monitor logs from your Kubernetes clusters. Integrate popular tools like Filebeat, Vector, or Fluent Bit with Axiom to send your cluster logs.
## Send Kubernetes Cluster logs to Axiom using Filebeat [#send-kubernetes-cluster-logs-to-axiom-using-filebeat]
Ingest logs from your Kubernetes cluster into Axiom using Filebeat.
The following is an example of a DaemonSet configuration to ingest your data logs into Axiom.
### Configuration [#configuration]
```yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: filebeat
namespace: kube-system
labels:
k8s-app: filebeat
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: filebeat
labels:
k8s-app: filebeat
rules:
- apiGroups: [''] # "" indicates the core API group
resources:
- namespaces
- pods
- nodes
verbs:
- get
- watch
- list
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: filebeat
subjects:
- kind: ServiceAccount
name: filebeat
namespace: kube-system
roleRef:
kind: ClusterRole
name: filebeat
apiGroup: rbac.authorization.k8s.io
---
apiVersion: v1
data:
filebeat.yml: |-
filebeat.autodiscover:
providers:
- type: kubernetes
node: ${NODE_NAME}
hints.enabled: true
hints.default_config:
type: container
paths:
- /var/log/containers/*${data.kubernetes.container.id}.log
allow_older_versions: true
processors:
- add_cloud_metadata:
output.elasticsearch:
hosts: ['${AXIOM_HOST}/v1/ingest/${AXIOM_DATASET}/elastic']
api_key: 'axiom:${AXIOM_TOKEN}'
setup.ilm.enabled: false
kind: ConfigMap
metadata:
annotations: {}
labels:
k8s-app: filebeat
name: filebeat-config
namespace: kube-system
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
labels:
k8s-app: filebeat
name: filebeat
namespace: kube-system
spec:
selector:
matchLabels:
k8s-app: filebeat
template:
metadata:
annotations: {}
labels:
k8s-app: filebeat
spec:
containers:
- args:
- -c
- /etc/filebeat.yml
- -e
env:
- name: AXIOM_HOST
value: AXIOM_DOMAIN
- name: AXIOM_DATASET
value: DATASET_NAME
- name: AXIOM_TOKEN
value: API_TOKEN
- name: NODE_NAME
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: spec.nodeName
image: docker.elastic.co/beats/filebeat-oss:8.11.1
imagePullPolicy: IfNotPresent
name: filebeat
resources:
limits:
memory: 200Mi
requests:
cpu: 100m
memory: 100Mi
securityContext:
runAsUser: 0
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /etc/filebeat.yml
name: config
readOnly: true
subPath: filebeat.yml
- mountPath: /usr/share/filebeat/data
name: data
- mountPath: /var/lib/docker/containers
name: varlibdockercontainers
readOnly: true
- mountPath: /var/log
name: varlog
readOnly: true
dnsPolicy: ClusterFirst
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
serviceAccount: filebeat
serviceAccountName: filebeat
terminationGracePeriodSeconds: 30
volumes:
- configMap:
defaultMode: 416
name: filebeat-config
name: config
- hostPath:
path: /var/lib/docker/containers
type: ''
name: varlibdockercontainers
- hostPath:
path: /var/log
type: ''
name: varlog
- hostPath:
path: /var/lib/filebeat-data
type: ''
name: data
updateStrategy:
rollingUpdate:
maxUnavailable: 1
type: RollingUpdate
```
After editing your values, apply the changes to your cluster using `kubectl apply -f daemonset.yaml`
## Send Kubernetes Cluster logs to Axiom using Vector [#send-kubernetes-cluster-logs-to-axiom-using-vector]
Collect logs from your Kubernetes cluster and send them directly to Axiom using the Vector daemonset.
### Configuration [#configuration-1]
```yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: vector
namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: vector
rules:
- apiGroups: [""]
resources:
- pods
- nodes
- namespaces
verbs:
- get
- list
- watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: vector
subjects:
- kind: ServiceAccount
name: vector
namespace: kube-system
roleRef:
kind: ClusterRole
name: vector
apiGroup: rbac.authorization.k8s.io
---
apiVersion: v1
kind: ConfigMap
metadata:
name: vector-config
namespace: kube-system
data:
vector.yml: |-
sources:
kubernetes_logs:
type: kubernetes_logs
self_node_name: ${VECTOR_SELF_NODE_NAME}
sinks:
axiom:
type: axiom
inputs:
- kubernetes_logs
compression: zstd
dataset: ${AXIOM_DATASET}
token: ${AXIOM_TOKEN}
healthcheck:
enabled: true
log_level: debug
logging:
level: debug
log_level: debug
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: vector
namespace: kube-system
spec:
selector:
matchLabels:
name: vector
template:
metadata:
labels:
name: vector
spec:
serviceAccountName: vector
containers:
- name: vector
image: timberio/vector:0.37.0-debian
args:
- --config-dir
- /etc/vector/
env:
- name: AXIOM_HOST
value: AXIOM_DOMAIN
- name: AXIOM_DATASET
value: DATASET_NAME
- name: AXIOM_TOKEN
value: API_TOKEN
- name: VECTOR_SELF_NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
volumeMounts:
- name: config
mountPath: /etc/vector/vector.yml
subPath: vector-config.yml
- name: data-dir
mountPath: /var/lib/vector
- name: var-log
mountPath: /var/log
readOnly: true
- name: var-lib
mountPath: /var/lib
readOnly: true
resources:
limits:
memory: 500Mi
requests:
cpu: 200m
memory: 100Mi
securityContext:
runAsUser: 0
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumes:
- name: config
configMap:
name: vector-config
items:
- key: vector.yml
path: vector-config.yml
- name: data-dir
hostPath:
path: /var/lib/vector
type: DirectoryOrCreate
- name: var-log
hostPath:
path: /var/log
- name: var-lib
hostPath:
path: /var/lib
dnsPolicy: ClusterFirst
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
terminationGracePeriodSeconds: 30
updateStrategy:
rollingUpdate:
maxUnavailable: 1
type: RollingUpdate
```
After editing your values, apply the changes to your cluster using `kubectl apply -f daemonset.yaml`
## Send Kubernetes Cluster logs to Axiom using Fluent Bit [#send-kubernetes-cluster-logs-to-axiom-using-fluent-bit]
Collect logs from your Kubernetes cluster and send them directly to Axiom using Fluent Bit.
### Configuration [#configuration-2]
```yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: fluent-bit
namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: fluent-bit
rules:
- apiGroups: [""]
resources:
- pods
- nodes
- namespaces
verbs:
- get
- list
- watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: fluent-bit
subjects:
- kind: ServiceAccount
name: fluent-bit
namespace: kube-system
roleRef:
kind: ClusterRole
name: fluent-bit
apiGroup: rbac.authorization.k8s.io
---
apiVersion: v1
kind: ConfigMap
metadata:
name: fluent-bit-config
namespace: kube-system
data:
fluent-bit.conf: |-
[SERVICE]
Flush 1
Log_Level debug
Daemon off
Parsers_File parsers.conf
HTTP_Server On
HTTP_Listen 0.0.0.0
HTTP_Port 2020
[INPUT]
Name tail
Tag kube.*
Path /var/log/containers/*.log
Parser docker
DB /var/log/flb_kube.db
Mem_Buf_Limit 7MB
Skip_Long_Lines On
Refresh_Interval 10
[FILTER]
Name kubernetes
Match kube.*
Kube_URL https://kubernetes.default.svc:443
Kube_CA_File /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
Kube_Token_File /var/run/secrets/kubernetes.io/serviceaccount/token
Kube_Tag_Prefix kube.var.log.containers.
Merge_Log On
Merge_Log_Key log_processed
K8S-Logging.Parser On
K8S-Logging.Exclude Off
[OUTPUT]
Name http
Match *
Host ${AXIOM_HOST}
Port 443
URI /v1/ingest/${AXIOM_DATASET}
Header Authorization Bearer ${AXIOM_TOKEN}
Format json
Json_date_key time
Json_date_format iso8601
Retry_Limit False
Compress gzip
tls On
tls.verify Off
parsers.conf: |-
[PARSER]
Name docker
Format json
Time_Key time
Time_Format %Y-%m-%dT%H:%M:%S.%L
Time_Keep On
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: fluent-bit
namespace: kube-system
spec:
selector:
matchLabels:
name: fluent-bit
template:
metadata:
labels:
name: fluent-bit
spec:
serviceAccountName: fluent-bit
containers:
- name: fluent-bit
image: fluent/fluent-bit:1.9.9
env:
- name: AXIOM_HOST
value: AXIOM_DOMAIN
- name: AXIOM_DATASET
value: DATASET_NAME
- name: AXIOM_TOKEN
value: API_TOKEN
volumeMounts:
- name: config
mountPath: /fluent-bit/etc/fluent-bit.conf
subPath: fluent-bit.conf
- name: config
mountPath: /fluent-bit/etc/parsers.conf
subPath: parsers.conf
- name: varlog
mountPath: /var/log
- name: varlibdockercontainers
mountPath: /var/lib/docker/containers
readOnly: true
volumes:
- name: config
configMap:
name: fluent-bit-config
- name: varlog
hostPath:
path: /var/log
- name: varlibdockercontainers
hostPath:
path: /var/lib/docker/containers
terminationGracePeriodSeconds: 10
```
After editing your values, apply the changes to your cluster using `kubectl apply -f daemonset.yaml`
## Extract top-level fields from log body [#extract-top-level-fields-from-log-body]
To extract top-level fields from the log body, configure the `filelog` receiver with operators to parse container log formats and JSON-structured log bodies.
Configure the following settings in your OpenTelemetry Collector configuration:
| Setting | Description |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| **Receiver** | Use `filelog` receiver targeting `/var/log/pods/*/*/*.log` |
| **Container operator** | Add the `container` operator to parse container log formats (Docker, CRI-O, Containerd) and extract the inner log message as the body |
| **JSON parser operator** | Add the `json_parser` operator to parse JSON-structured log bodies into structured fields |
| **Transform processor** | Optional: Use the `transform` processor to promote parsed JSON fields to top-level attributes instead of keeping them in the body |
Example configuration:
```yaml
receivers:
filelog/k8s-logs:
include: [/var/log/pods/*/*/*.log]
start_at: end
operators:
- type: container
- type: json_parser
if: body matches '^{.*}$'
```
For complete configuration details, including optional timestamp and severity extraction, see the [OpenTelemetry Collector documentation](https://opentelemetry.io/docs/collector/).
---
# Send data from Logstash to Axiom
Source: https://axiom.co/docs/send-data/logstash
Logstash is an open-source log aggregation, transformation tool, and server-side data processing pipeline that simultaneously ingests data from many sources. With Logstash, you can collect, parse, send, and store logs for future use on Axiom.
Logstash works as a data pipeline tool with Axiom, where, from one end, the data is input from your servers and system and, from the other end, Axiom takes out the data and converts it into useful information.
It can read data from various `input` sources, filter data for the specified configuration, and eventually store it.
Logstash sits between your data and where you want to keep it.
* Visit the [Logstash download page](https://www.elastic.co/downloads/logstash) to install Logstash on your system.
## Configuration [#configuration]
To configure the `logstash.conf` file, define the source, set the rules to format your data, and set Axiom as the destination where the data is sent.
The Logstash configuration works with OpenSearch, so you can use the OpenSearch syntax to define the source and destination.
The Logstash Pipeline has three stages:
* [Input stage](https://www.elastic.co/guide/en/logstash/8.0/pipeline.html#_inputs) generates the event & Ingest Data of all volumes, Sizes, forms, and Sources
* [Filter stage](https://www.elastic.co/guide/en/logstash/8.0/pipeline.html#_filters) modifies the event as you specify in the filter component
* [Output stage](https://www.elastic.co/guide/en/logstash/8.0/pipeline.html#_outputs) shifts and sends the event into Axiom.
## OpenSearch output [#opensearch-output]
For installation instructions for the plugin, check out the [OpenSearch documentation](https://opensearch.org/docs/latest/tools/logstash/index/#install-logstash)
In `logstash.conf`, configure your Logstash pipeline to collect and send data logs to Axiom.
The example below shows Logstash configuration that sends data to Axiom:
```js
input{
exec{
command => "date"
interval => "1"
}
}
output{
opensearch{
hosts => ["https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic"]
user => "axiom"
password => "API_TOKEN"
}
}
```
## Combining filters with conditionals on Logstash events [#combining-filters-with-conditionals-on-logstash-events]
Logstash provides an extensive array of filters that allow you to enhance, manipulate, and transform your data. These filters can be used to perform tasks such as extracting, removing, and adding new fields and changing the content of fields.
Some valuable filters include the following.
## Grok filter plugin [#grok-filter-plugin]
The Grok filter plugin allows you to parse the unstructured log data into something structured and queryable, and eventually send the structured logs to Axiom. It matches the unstructured data to patterns and maps the data to specified fields.
Here’s an example of how to use the Grok plugin:
```js
input{
exec{
command => "axiom"
interval => "1"
}
}
filter {
grok {
match => { "message" => "%{COMBINEDAPACHELOG}" }
}
date {
match => [ "timestamp" , "dd/MMM/yyyy:HH:mm:ss Z" ]
}
mutate {
add_field => { "foo" => "Hello Axiom, from Logstash" }
remove_field => [ "axiom", "logging" ]
}
}
output{
opensearch{
hosts => ["https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic"]
user => "axiom"
password => "API_TOKEN"
}
}
```
This configuration parses Apache log data by matching the pattern of `COMBINEDAPACHELOG`.
## Mutate filter plugin [#mutate-filter-plugin]
The Mutate filter plugin allows you to perform general transformations on fields. For example, rename, convert, strip, and modify fields in event data.
Here’s an example of using the Mutate plugin:
```js
input{
exec{
command => "axiom"
interval => "1"
}
}
filter {
mutate {
rename => { "hostname" => "host" }
convert => { "response" => "integer" }
uppercase => [ "method" ]
remove_field => [ "request", "httpversion" ]
}
}
output{
opensearch{
hosts => ["https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic"]
user => "axiom"
password => "API_TOKEN"
}
}
```
This configuration renames the field `hostname` to `host`, converts the `response` field value to an integer, changes the `method` field to uppercase, and removes the `request` and `httpversion` fields.
## Drop filter plugin [#drop-filter-plugin]
The Drop filter plugin allows you to drop certain events based on specified conditions. This helps you to filter out unnecessary data.
Here’s an example of using the Drop plugin:
```js
input {
syslog {
port => 5140
type => syslog
}
}
filter {
if [type] == "syslog" and [severity] == "debug" {
drop { }
}
}
output{
opensearch{
hosts => ["https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic"]
user => "axiom"
password => "API_TOKEN"
}
}
```
This configuration drops all events of type `syslog` with severity `debug`.
## Clone filter plugin [#clone-filter-plugin]
The Clone filter plugin creates a copy of an event and stores it in a new event. The event continues along the pipeline until it ends or is dropped.
Here’s an example of using the Clone plugin:
```js
input {
syslog {
port => 5140
type => syslog
}
}
filter {
clone {
clones => ["cloned_event"]
}
}
output{
opensearch{
hosts => ["https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic"]
user => "axiom"
password => "API_TOKEN"
}
}
```
This configuration creates a new event named `cloned_event` that’s a clone of the original event.
## GeoIP filter plugin [#geoip-filter-plugin]
The GeoIP filter plugin adds information about the geographical location of IP addresses. This data includes the latitude, longitude, continent, country, and so on.
Here’s an example of using the GeoIP plugin:
```js
input{
exec{
command => "axiom"
interval => "6"
}
}
filter {
geoip {
source => "ip"
}
}
output{
opensearch{
hosts => ["https://AXIOM_DOMAIN:443/v1/ingest/DATASET_NAME/elastic"]
user => "axiom"
password => "API_TOKEN"
}
}
```
This configuration adds geographical location data for the IP address in the `ip` field. Note that you may need to specify the path to the GeoIP database file in the plugin configuration, depending on your setup.
---
# Send data from Loki Multiplexer to Axiom
Source: https://axiom.co/docs/send-data/loki-multiplexer
Loki by Prometheus is a multi-tenant log aggregation system that’s highly scalable and capable of indexing metadata about your logs.
Loki exposes an HTTP API for pushing, querying, and tailing Axiom log data.
Axiom Loki Proxy provides a gateway for you to connect a direct link interface to Axiom via Loki endpoint.
Using the Axiom Loki Proxy, you can ship logs to Axiom via the [Loki HTTP API](https://grafana.com/docs/loki/latest/reference/loki-http-api/#ingest-logs).
## Installation [#installation]
### Install and update using Homebrew [#install-and-update-using-homebrew]
```bash
brew tap axiomhq/tap
brew install axiom-loki-proxy
brew update
brew upgrade axiom-loki-proxy
```
### Install using `go get` [#install-using-go-get]
```bash
go get -u github.com/axiomhq/axiom-loki-proxy/cmd/axiom-loki-proxy
```
### Install from source [#install-from-source]
```bash
git clone https://github.com/axiomhq/axiom-loki-proxy.git
cd axiom-loki-proxy
make build
```
### Run the Loki-Proxy Docker [#run-the-loki-proxy-docker]
```bash
docker pull axiomhq/axiom-loki-proxy:latest
```
## Configuration [#configuration]
Specify the environmental variables for your Axiom deployment:
```bash
AXIOM_URL = AXIOM_DOMAIN
AXIOM_TOKEN = API_TOKEN
```
## Run and test [#run-and-test]
```bash
./axiom-loki-proxy
```
### Using Docker [#using-docker]
```bash
docker run -p8080:8080/tcp \
-e=AXIOM_TOKEN= \
axiomhq/axiom-loki-proxy
```
For more information on Axiom Loki Proxy and how you can propose bug fix, report issues and submit PRs, see the [GitHub repository](https://github.com/axiomhq/axiom-loki-proxy).
---
# Send data from Loki to Axiom
Source: https://axiom.co/docs/send-data/loki
This page explains how to send data from a Loki-based logging setup to Axiom.
Axiom doesn’t accept the Loki push API directly. Instead, replace the component that pushes to Loki with one that sends to Axiom natively. In most setups, this is a one-line change in a log shipper’s configuration.
## Replace the Loki output in your log shipper [#replace-the-loki-output-in-your-log-shipper]
Most Loki pipelines run a shipper that also has native support for Axiom. Replace the Loki output in the shipper configuration with the Axiom output, and keep the sources and transforms as they are:
* [Vector](/send-data/vector)
* [Fluent Bit](/send-data/fluent-bit)
* [Fluentd](/send-data/fluentd)
* [OpenTelemetry Collector](/send-data/opentelemetry)
If you use Promtail or Grafana Alloy only to ship logs to Loki, replace it with one of the shippers above.
## Replace the Loki transport in your app [#replace-the-loki-transport-in-your-app]
If your app logs through a Loki transport such as `winston-loki` or `logging_loki`, switch to the Axiom integration for your logging library:
* Node.js: [Winston](/guides/winston) or [Pino](/guides/pino)
* Python: [Python logging](/guides/python)
For other languages and frameworks, see [Methods for sending data](/send-data/methods).
---
# Methods for sending data
Source: https://axiom.co/docs/send-data/methods
The easiest way to send your first event data to Axiom is with a direct HTTP request using a tool like `cURL`.
```shell wrap
curl -X 'POST' 'https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME' \
-H 'Authorization: Bearer API_TOKEN' \
-H 'Content-Type: application/x-ndjson' \
-d '{ "http": { "request": { "method": "GET", "duration_ms": 231 }, "response": { "body": { "size": 3012 } } }, "url": { "path": "/download" } }'
```
To send events continuously, Axiom supports a wide range of standard tools, libraries, and platform integrations.
## Popular methods [#popular-methods]
| Method | Description |
| :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------ |
| [Rest API](/restapi/introduction) | Direct HTTP API for sending logs and events |
| [OpenTelemetry](/send-data/opentelemetry) | Industry-standard observability framework |
| [Vector](/send-data/vector) | High-performance observability data pipeline |
| [Cribl](/send-data/cribl) | Route and transform data with Cribl Stream. For OCSF security data, see [Send OCSF data](/use-cases/ocsf/send-data) |
| [Fluent Bit](/send-data/fluent-bit) | Fast and lightweight log processor |
| [Fluentd](/send-data/fluentd) | Open source data collector with plugin ecosystem |
| [JavaScript](/guides/javascript) | Browser and Node.js logging |
## Other methods [#other-methods]
| Method | Description |
| :------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------- |
| [.NET](/guides/send-logs-from-dotnet) | Send logs from .NET applications |
| [Apache Log4j](/guides/send-logs-from-apache-log4j) | Java logging with Log4j integration |
| [Apex](/guides/apex) | Structured logging for Go |
| [Cloudflare Workers](/guides/opentelemetry-cloudflare-workers) | Edge computing with Workers and OpenTelemetry |
| [Convex](/send-data/convex) | Stream data from Convex applications |
| [Docker](/send-data/docker) | Container logs and metrics with Vector, the OpenTelemetry Collector, Fluent Bit, Fluentd, or Filebeat |
| [Elastic Beats](/send-data/elastic-beats) | Lightweight data shippers from Elastic |
| [Elasticsearch Bulk API](/send-data/elasticsearch-bulk-api) | Compatible endpoint for Elasticsearch clients |
| [Elixir](/guides/send-logs-from-elixir) | Send logs from Elixir apps with a custom Logger handler |
| [Erlang](/guides/send-logs-from-erlang) | Send logs from Erlang/OTP apps with a custom logger handler |
| [Flutter](/guides/flutter) | Send structured logs from Flutter apps |
| [Go](/guides/go) | Native Go logging integration |
| [Heroku Log Drains](/send-data/heroku-log-drains) | Stream logs directly from Heroku apps |
| [Honeycomb](/send-data/honeycomb) | Send data from Honeycomb SDKs with OpenTelemetry or the Axiom Honeycomb Proxy |
| [Kubernetes](/send-data/kubernetes) | Collect logs and metrics from K8s clusters |
| [Laravel](/guides/send-logs-from-laravel) | PHP Laravel framework integration |
| [Logrus](/guides/logrus) | Structured logging for Go with Logrus |
| [Logstash](/send-data/logstash) | Server-side data processing pipeline |
| [Loki](/send-data/loki) | Send data from Loki pipelines and clients |
| [Loki Multiplexer](/send-data/loki-multiplexer) | Forward Loki data to multiple destinations |
| [Next.js](/send-data/nextjs) | Full-stack React framework logging |
| [PgBouncer](/send-data/pgbouncer) | PgBouncer metrics via pgbouncer\_exporter and the OpenTelemetry Collector |
| [Pino](/guides/pino) | Fast Node.js logger integration |
| [Python](/guides/python) | Python logging with standard library |
| [React](/send-data/react) | Client-side React app logging |
| [Render](/send-data/render) | Stream logs from Render.com services |
| [Ruby on Rails](/guides/send-logs-from-ruby-on-rails) | Rails app logging |
| [Rust](/guides/rust) | High-performance Rust logging |
| [Secure Syslog](/send-data/secure-syslog) | Receive syslog over TLS with Vector and forward to Axiom |
| [Serverless](/send-data/serverless) | Best practices for serverless environments |
| [Splunk](/send-data/splunk) | Send data from Splunk forwarders and logging libraries |
| [Splunk HEC](/send-data/splunk-hec) | HTTP Event Collector compatible API on your edge deployment |
| [StatsD](/send-data/statsd) | Send StatsD metrics through the OpenTelemetry Collector |
| [Syslog Proxy](/send-data/syslog-proxy) | Forward syslog data with transformation |
| [Traefik](/send-data/traefik) | Scrape Traefik metrics with the OpenTelemetry Collector |
| [Tremor](/send-data/tremor) | Event processing system for complex workflows |
| [Winston](/guides/winston) | Popular Node.js logging library |
| [Zap](/guides/zap) | Uber’s fast, structured Go logger |
## Amazon Web Services (AWS) [#amazon-web-services-aws]
Axiom offers deep integration with the AWS ecosystem.
| Method | Description |
| :------------------------------------------------------ | :------------------------------------ |
| [Amazon CloudFront](/send-data/cloudfront) | CDN access logs and real-time logs |
| [Amazon CloudWatch](/send-data/cloudwatch) | Stream logs from CloudWatch Logs |
| [Amazon Kinesis Data Firehose](/send-data/aws-firehose) | Real-time streaming with Firehose |
| [Amazon S3](/send-data/aws-s3) | Process logs stored in S3 buckets |
| [AWS FireLens](/send-data/aws-firelens) | Container log routing for ECS/Fargate |
| [AWS IoT Rules](/send-data/aws-iot-rules) | Route IoT device data and telemetry |
| [AWS Lambda](/send-data/aws-lambda) | Serverless function logs and traces |
| [AWS Lambda .NET](/send-data/aws-lambda-dot) | .NET-specific Lambda integration |
## Example configurations [#example-configurations]
The following examples show how to send data using OpenTelemetry from various languages and frameworks.
| Application | Description |
| :------------------------------------------------------------- | :---------------------------------------------- |
| [OpenTelemetry .NET](/guides/opentelemetry-dotnet) | Complete .NET app example |
| [OpenTelemetry Claude Code](/guides/opentelemetry-claude-code) | Monitor Claude Code usage with metrics and logs |
| [OpenTelemetry Django](/guides/opentelemetry-django) | Python Django with OpenTelemetry |
| [OpenTelemetry Go](/guides/opentelemetry-go) | Go app with full observability |
| [OpenTelemetry Java](/guides/opentelemetry-java) | Java Spring Boot example |
| [OpenTelemetry Next.js](/guides/opentelemetry-nextjs) | Full-stack Next.js with tracing |
| [OpenTelemetry Node.js](/guides/opentelemetry-nodejs) | Node.js Express example |
| [OpenTelemetry Nuxt.js](/guides/opentelemetry-nuxtjs) | Nuxt.js with server-side tracing |
| [OpenTelemetry Python](/guides/opentelemetry-python) | Python Flask/FastAPI example |
| [OpenTelemetry Ruby](/guides/opentelemetry-ruby) | Ruby on Rails with OpenTelemetry |
If you need an ingestion method that isn’t in the list above, [contact Axiom](https://www.axiom.co/contact).
## Limits on ingested data [#limits-on-ingested-data]
For more information on limits and requirements imposed by Axiom, see [Limits](/reference/limits).
---
# Send data from Next.js app to Axiom
Source: https://axiom.co/docs/send-data/nextjs
Next.js is a popular open-source JavaScript framework built on top of React, developed by Vercel. It’s used by a wide range of companies and organizations, from startups to large enterprises, due to its performance benefits and developer-friendly features.
To send data from your Next.js app to Axiom, choose one of the following options:
* [Axiom Vercel app](/apps/vercel)
* [@axiomhq/nextjs library](#use-axiomhq-nextjs-library)
* [next-axiom library](#use-next-axiom-library)
The choice between these options depends on your individual requirements:
* The two options can collect different event types.
| Event type | Axiom Vercel app | @axiomhq/nextjs library | next-axiom library |
| ---------------- | :--------------: | :---------------------: | :----------------: |
| Application logs | Yes | Yes | Yes |
| Web Vitals | No | Yes | Yes |
| HTTP logs | Yes | Yes | No |
| Build logs | Yes | No | No |
| Tracing | Yes | Yes | No |
* If you already use Vercel for deployments, the Axiom Vercel app can be easier to integrate into your existing experience.
* The cost of these options can differ widely depending on the volume of data you transfer. The Axiom Vercel app depends on Vercel Drains, a feature that’s only available on paid plans. For more information, see [the blog post on the changes to Vercel Drains](https://axiom.co/blog/changes-to-vercel-log-drains).
* The @axiomhq/nextjs library is the recommended choice if you want to send data from your Next.js app to Axiom without using Vercel Drains.
* The next-axiom library is no longer under active development. It’s supported with bug fixes, but it won’t receive new features.
For information on the Axiom Vercel app and migrating from the Vercel app to the next-axiom library, see [Axiom Vercel app](/apps/vercel).
The rest of this page explains how to send data from your Next.js app to Axiom using the next-axiom or the @axiomhq/nextjs library.
* [A new or existing Next.js app](https://nextjs.org/).
## Use @axiomhq/nextjs library [#use-axiomhqnextjs-library]
The @axiomhq/nextjs library is part of the Axiom JavaScript SDK, an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/axiom-js).
### Install @axiomhq/nextjs [#install-axiomhqnextjs]
1. In your terminal, go to the root folder of your Next.js app and run the following command:
```sh
npm install --save @axiomhq/js @axiomhq/logging @axiomhq/nextjs @axiomhq/react
```
2. Create the folder `lib/axiom` to store configurations for Axiom.
3. Create a `axiom.ts` file in the `lib/axiom` folder with the following content:
```ts lib/axiom/axiom.ts [expandable]
import { Axiom } from '@axiomhq/js';
const axiomClient = new Axiom({
token: process.env.NEXT_PUBLIC_AXIOM_TOKEN!,
});
export default axiomClient;
```
4. In the `lib/axiom` folder, create a `server.ts` file with the following content:
```ts lib/axiom/server.ts [expandable]
import axiomClient from '@/lib/axiom/axiom';
import { Logger, AxiomJSTransport } from '@axiomhq/logging';
import { createAxiomRouteHandler, nextJsFormatters } from '@axiomhq/nextjs';
export const logger = new Logger({
transports: [
new AxiomJSTransport({ axiom: axiomClient, dataset: process.env.NEXT_PUBLIC_AXIOM_DATASET! }),
],
formatters: nextJsFormatters,
});
export const withAxiom = createAxiomRouteHandler(logger);
```
The `createAxiomRouteHandler` is a builder function that returns a wrapper for your route handlers. The wrapper handles successful responses and errors thrown within the route handler. For more information on the logger, see [the @axiomhq/logging library](/guides/javascript#use-axiomhqlogging).
5. In the `lib/axiom` folder, create a `client.ts` file with the following content:
Ensure the API token you use on the client side has the appropriate permissions. Axiom recommends you create a client-side token with the only permission to ingest data into a specific dataset.
If you don’t want to expose the token to the client, use the [proxy transport](#proxy-for-client-side-usage) to send logs to Axiom.
```ts lib/axiom/client.ts [expandable]
'use client';
import axiomClient from '@/lib/axiom/axiom';
import { Logger, AxiomJSTransport } from '@axiomhq/logging';
import { createUseLogger, createWebVitalsComponent } from '@axiomhq/react';
import { nextJsFormatters } from '@axiomhq/nextjs/client';
export const logger = new Logger({
transports: [
new AxiomJSTransport({ axiom: axiomClient, dataset: process.env.NEXT_PUBLIC_AXIOM_DATASET! }),
],
formatters: nextJsFormatters,
});
const useLogger = createUseLogger(logger);
const WebVitals = createWebVitalsComponent(logger);
export { useLogger, WebVitals };
```
For more information on React client side helpers, see [React](/send-data/react).
### Capture traffic requests [#capture-traffic-requests]
To capture traffic requests, create a `proxy.ts` file in the root folder of your Next.js app with the following content:
```ts proxy.ts [expandable]
import { logger } from "@/lib/axiom/server";
import { transformMiddlewareRequest } from "@axiomhq/nextjs";
import { NextResponse } from "next/server";
import type { NextFetchEvent, NextRequest } from "next/server";
export async function proxy(request: NextRequest, event: NextFetchEvent) {
logger.info(...transformMiddlewareRequest(request));
event.waitUntil(logger.flush());
return NextResponse.next();
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
*/
"/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
],
};
```
Next.js 16 renamed middleware to proxy. If your app uses Next.js 15 or earlier, name the file `middleware.ts` and the exported function `middleware` instead. The file contents are otherwise identical. `middleware.ts` still works in Next.js 16, but it's deprecated and will be removed in a future version.
### Web Vitals [#web-vitals]
To capture Web Vitals, add the `WebVitals` component to the `app/layout.tsx` file:
```tsx /app/layout.tsx [expandable]
import { WebVitals } from "@/lib/axiom/client";
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
{children}
);
}
```
### Logs [#logs]
Send logs to Axiom from different parts of your app. Each log function call takes a message and an optional `fields` object.
```ts [expandable]
import { logger } from "@/lib/axiom/server";
logger.debug("Login attempt", { user: "j_doe", status: "success" }); // Results in {"message": "Login attempt", "fields": {"user": "j_doe", "status": "success"}}
logger.info("Payment completed", { userID: "123", amount: "25USD" });
logger.warn("API rate limit exceeded", {
endpoint: "/users/1",
rateLimitRemaining: 0,
});
logger.error("System Error", { code: "500", message: "Internal server error" });
```
#### Route handlers [#route-handlers]
You can use the `withAxiom` function exported from the setup file in `lib/axiom/server.ts` to wrap your route handlers.
```ts
import { logger } from "@/lib/axiom/server";
import { withAxiom } from "@/lib/axiom/server";
export const GET = withAxiom(async () => {
return new Response("Hello World!");
});
```
For more information on customizing the data sent to Axiom, see [Advanced route handlers](#advanced-route-handlers).
#### Client components [#client-components]
To send logs from client components, add `useLogger` to your component:
```tsx [expandable]
"use client";
import { useLogger } from "@/lib/axiom/client";
export default function ClientComponent() {
const log = useLogger();
log.debug("User logged in", { userId: 42 });
const handleClick = () => log.info("User logged out");
return (
Logged in
Log out
);
}
```
#### Server components [#server-components]
To send logs from server components, use the following:
```tsx [expandable]
import { logger } from "@/lib/axiom/server";
import { after } from "next/server";
export default async function ServerComponent() {
logger.info("User logged in", { userId: 42 });
after(() => {
logger.flush();
});
return Logged in ;
}
```
### Capture errors [#capture-errors]
#### Capture errors on Next 15 or later [#capture-errors-on-next-15-or-later]
To capture errors on Next 15 or later, use the `onRequestError` option. Create an `instrumentation.ts` file in the `src` or root folder of your Next.js app (depending on your configuration) with the following content:
```ts instrumentation.ts [expandable]
import { logger } from "@/lib/axiom/server";
import { createOnRequestError } from "@axiomhq/nextjs";
export const onRequestError = createOnRequestError(logger);
```
Alternatively, customize the error logging by creating a custom `onRequestError` function:
```ts [expandable]
import { logger } from "@/lib/axiom/server";
import { transformOnRequestError } from "@axiomhq/nextjs";
import { Instrumentation } from "next";
export const onRequestError: Instrumentation.onRequestError = async (
error,
request,
ctx
) => {
logger.error(...transformOnRequestError(error, request, ctx));
await logger.flush();
};
```
#### Capture errors on Next 14 or earlier [#capture-errors-on-next-14-or-earlier]
To capture routing errors on Next 14 or earlier, use the [error handling mechanism of Next.js](https://nextjs.org/docs/app/building-your-application/routing/error-handling):
1. Create an `error.tsx` file in the `app` folder.
2. Inside your component function, add `useLogger` to send the error to Axiom. For example:
```tsx [expandable]
"use client";
import NavTable from "@/components/NavTable";
import { LogLevel } from "@axiomhq/logging";
import { useLogger } from "@/lib/axiom/client";
import { usePathname } from "next/navigation";
export default function ErrorPage({
error,
}: {
error: Error & { digest?: string };
}) {
const pathname = usePathname();
const log = useLogger();
let status = error.message == "Invalid URL" ? 404 : 500;
log.log(LogLevel.error, error.message, {
error: error.name,
cause: error.cause,
stack: error.stack,
digest: error.digest,
request: {
host: window.location.href,
path: pathname,
statusCode: status,
},
});
return (
Ops! An Error has occurred:{" "}
`{error.message}`
);
}
```
### Advanced customizations [#advanced-customizations]
This section describes some advanced customizations.
#### Proxy for client-side usage [#proxy-for-client-side-usage]
Instead of sending logs directly to Axiom, you can send them to a proxy endpoint in your Next.js app. This is useful if you don’t want to expose the Axiom API token to the client or if you want to send the logs from the client to transports on your server.
1. Create a `client.ts` file in the `lib/axiom` folder with the following content:
```ts lib/axiom/client.ts [expandable]
'use client';
import { Logger, ProxyTransport } from '@axiomhq/logging';
import { createUseLogger, createWebVitalsComponent } from '@axiomhq/react';
export const logger = new Logger({
transports: [
new ProxyTransport({ url: '/api/axiom', autoFlush: true }),
],
});
const useLogger = createUseLogger(logger);
const WebVitals = createWebVitalsComponent(logger);
export { useLogger, WebVitals };
```
2. In the `/app/api/axiom` folder, create a `route.ts` file with the following content. This example uses `/api/axiom` as the Axiom proxy path.
```ts /app/api/axiom/route.ts
import { logger } from "@/lib/axiom/server";
import { createProxyRouteHandler } from "@axiomhq/nextjs";
export const POST = createProxyRouteHandler(logger);
```
For more information on React client side helpers, see [React](/send-data/react).
#### Customize data reports sent to Axiom [#customize-data-reports-sent-to-axiom]
To customize the reports sent to Axiom, use the `onError` and `onSuccess` functions that the `createAxiomRouteHandler` function accepts in the configuration object.
In the `lib/axiom/server.ts` file, use the `transformRouteHandlerErrorResult` and `transformRouteHandlerSuccessResult` functions to customize the data sent to Axiom by adding fields to the report object:
```ts [expandable]
import { Logger, AxiomJSTransport } from '@axiomhq/logging';
import {
createAxiomRouteHandler,
getLogLevelFromStatusCode,
nextJsFormatters,
transformRouteHandlerErrorResult,
transformRouteHandlerSuccessResult
} from '@axiomhq/nextjs';
/* ... your logger setup ... */
export const withAxiom = createAxiomRouteHandler(logger, {
onError: (error) => {
if (error.error instanceof Error) {
logger.error(error.error.message, error.error);
}
const [message, report] = transformRouteHandlerErrorResult(error);
report.customField = "customValue";
report.request.searchParams = new URL(error.req.url).searchParams;
logger.log(getLogLevelFromStatusCode(report.statusCode), message, report);
logger.flush();
},
onSuccess: (data) => {
const [message, report] = transformRouteHandlerSuccessResult(data);
report.customField = "customValue";
report.request.searchParams = new URL(data.req.url).searchParams;
logger.info(message, report);
logger.flush();
},
});
```
Changing the `transformSuccessResult()` or `transformErrorResult()` functions can change the shape of your data. This can affect dashboards (especially auto-generated dashboards) and other integrations.
Axiom recommends you add fields on top of the ones returned by the default `transformSuccessResult()` or `transformErrorResult()` functions, without replacing the default fields.
Alternatively, create your own `transformSuccessResult()` or `transformErrorResult()` functions:
```ts [expandable]
import { Logger, AxiomJSTransport } from '@axiomhq/logging';
import {
createAxiomRouteHandler,
getLogLevelFromStatusCode,
nextJsFormatters,
transformRouteHandlerErrorResult,
transformRouteHandlerSuccessResult
} from '@axiomhq/nextjs';
/* ... your logger setup ... */
export const transformSuccessResult = (
data: SuccessData
): [message: string, report: Record] => {
const report = {
request: {
type: "request",
method: data.req.method,
url: data.req.url,
statusCode: data.res.status,
durationMs: data.end - data.start,
path: new URL(data.req.url).pathname,
endTime: data.end,
startTime: data.start,
},
};
return [
`${data.req.method} ${report.request.path} ${
report.request.statusCode
} in ${report.request.endTime - report.request.startTime}ms`,
report,
];
};
export const transformRouteHandlerErrorResult = (data: ErrorData): [message: string, report: Record] => {
const statusCode = data.error instanceof Error ? getNextErrorStatusCode(data.error) : 500;
const report = {
request: {
startTime: new Date().getTime(),
endTime: new Date().getTime(),
path: data.req.nextUrl.pathname ?? new URL(data.req.url).pathname,
method: data.req.method,
host: data.req.headers.get('host'),
userAgent: data.req.headers.get('user-agent'),
scheme: data.req.url.split('://')[0],
ip: data.req.headers.get('x-forwarded-for'),
region: getRegion(data.req),
statusCode: statusCode,
},
};
return [
`${data.req.method} ${report.request.path} ${report.request.statusCode} in ${report.request.endTime - report.request.startTime}ms`,
report,
];
};
export const withAxiom = createAxiomRouteHandler(logger, {
onError: (error) => {
if (error.error instanceof Error) {
logger.error(error.error.message, error.error);
}
const [message, report] = transformRouteHandlerErrorResult(error);
report.customField = "customValue";
report.request.searchParams = new URL(error.req.url).searchParams;
logger.log(getLogLevelFromStatusCode(report.statusCode), message, report);
logger.flush();
},
onSuccess: (data) => {
const [message, report] = transformRouteHandlerSuccessResult(data);
report.customField = "customValue";
report.request.searchParams = new URL(data.req.url).searchParams;
logger.info(message, report);
logger.flush();
},
});
```
#### Change the log level from Next.js built-in function errors [#change-the-log-level-from-nextjs-built-in-function-errors]
By default, Axiom uses the following log levels:
* Errors thrown by the `redirect()` function are logged as `info`.
* Errors thrown by the `forbidden()`, `notFound()` and `unauthorized()` functions are logged as `warn`.
To customize this behavior, provide a custom `logLevelByStatusCode()` function when logging errors from your route handler:
```ts [expandable]
import { Logger, AxiomJSTransport, LogLevel } from '@axiomhq/logging';
import {
createAxiomRouteHandler,
nextJsFormatters,
transformRouteHandlerErrorResult,
} from '@axiomhq/nextjs';
/* ... your logger setup ... */
const getLogLevelFromStatusCode = (statusCode: number) => {
if (statusCode >= 300 && statusCode < 400) {
return LogLevel.info;
} else if (statusCode >= 400 && statusCode < 500) {
return LogLevel.warn;
}
return LogLevel.error;
};
export const withAxiom = createAxiomRouteHandler(logger, {
onError: (error) => {
if (error.error instanceof Error) {
logger.error(error.error.message, error.error);
}
const [message, report] = transformRouteHandlerErrorResult(error);
report.customField = 'customValue';
report.request.searchParams = new URL(error.req.url).searchParams;
logger.log(getLogLevelFromStatusCode(report.statusCode), message, report);
logger.flush();
}
});
```
Internally, the status code gets captured in the `transformErrorResult()` function using a `getNextErrorStatusCode()` function. To compose these functions yourself, create your own `getNextErrorStatusCode()` function and inject the result into the `transformErrorResult()` report.
```ts [expandable]
import { Logger, AxiomJSTransport, LogLevel } from '@axiomhq/logging';
import {
createAxiomRouteHandler,
nextJsFormatters,
transformRouteHandlerErrorResult,
} from '@axiomhq/nextjs';
import { isRedirectError } from 'next/dist/client/components/redirect-error';
import { isHTTPAccessFallbackError } from 'next/dist/client/components/http-access-fallback/http-access-fallback';
import axiomClient from '@/lib/axiom/axiom';
export const logger = new Logger({
transports: [
new AxiomJSTransport({ axiom: axiomClient, dataset: process.env.NEXT_PUBLIC_AXIOM_DATASET! }),
],
formatters: nextJsFormatters,
});
export const getNextErrorStatusCode = (error: Error & { digest?: string }) => {
if (!error.digest) {
return 500;
}
if (isRedirectError(error)) {
return parseInt(error.digest.split(';')[3]);
} else if (isHTTPAccessFallbackError(error)) {
return parseInt(error.digest.split(';')[1]);
}
};
const getLogLevelFromStatusCode = (statusCode: number) => {
if (statusCode >= 300 && statusCode < 400) {
return LogLevel.info;
} else if (statusCode >= 400 && statusCode < 500) {
return LogLevel.warn;
}
return LogLevel.error;
};
export const withAxiom = createAxiomRouteHandler(logger, {
onError: (error) => {
if (error.error instanceof Error) {
logger.error(error.error.message, error.error);
}
const [message, report] = transformRouteHandlerErrorResult(error);
const statusCode = error.error instanceof Error ? getNextErrorStatusCode(error.error) : 500;
report.request.statusCode = statusCode;
report.customField = 'customValue';
report.request.searchParams = new URL(error.req.url).searchParams;
logger.log(getLogLevelFromStatusCode(report.statusCode), message, report);
logger.flush();
},
});
```
### Server execution context [#server-execution-context]
The `serverContextFieldsFormatter` function included in the `nextJsFormatters` adds the server execution context to the logs, this is useful to have information about the scope where the logs were generated.
By default, the `createAxiomRouteHandler` function adds a `request_id` field to the logs using this server context and the server context fields formatter.
#### Route handlers server context [#route-handlers-server-context]
The `createAxiomRouteHandler` accepts a `store` field in the configuration object. The store can be a map, an object, or a function that accepts a request and context. It returns a map or an object.
The fields in the store are added to the `fields` object of the log report. For example, you can use this to add a `trace_id` field to every log report within the same function execution in the route handler.
```ts [expandable]
import { Logger, AxiomJSTransport } from '@axiomhq/logging';
import { createAxiomRouteHandler, nextJsFormatters } from '@axiomhq/nextjs';
import { NextRequest } from 'next/server';
import axiomClient from '@/lib/axiom/axiom';
export const logger = new Logger({
transports: [
new AxiomJSTransport({ axiom: axiomClient, dataset: process.env.NEXT_PUBLIC_AXIOM_DATASET! }),
],
formatters: nextJsFormatters,
});
export const withAxiom = createAxiomRouteHandler(logger, {
store: (req: NextRequest) => {
return {
request_id: crypto.randomUUID(),
trace_id: req.headers.get('x-trace-id'),
};
},
});
```
#### Server context on arbitrary functions [#server-context-on-arbitrary-functions]
You can also add the server context to any function that runs in the server. For example, server actions, proxy (formerly middleware), and server components.
```ts [expandable]
"use server";
import { runWithServerContext } from "@axiomhq/nextjs";
export const serverAction = () =>
runWithServerContext(() => {
return "Hello World";
}, { request_id: crypto.randomUUID() });
```
```ts proxy.ts [expandable]
import { logger } from "@/lib/axiom/server";
import { runWithServerContext, transformMiddlewareRequest } from "@axiomhq/nextjs";
import { NextResponse } from "next/server";
import type { NextFetchEvent, NextRequest } from "next/server";
export const proxy = (request: NextRequest, event: NextFetchEvent) =>
runWithServerContext(() => {
// trace_id will be added to the log fields
logger.info(...transformMiddlewareRequest(request));
// trace_id will also be added to the log fields
logger.info("Hello from proxy");
event.waitUntil(logger.flush());
return NextResponse.next();
}, { trace_id: request.headers.get("x-trace-id") });
```
## Use next-axiom library [#use-next-axiom-library]
The next-axiom library is an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/next-axiom).
### Install next-axiom [#install-next-axiom]
1. In your terminal, go to the root folder of your Next.js app and run the following command:
```sh
npm install --save next-axiom
```
2. Add the following environment variables to your Next.js app:
* `NEXT_PUBLIC_AXIOM_DATASET` is the name of the Axiom dataset where you want to send data.
* `NEXT_PUBLIC_AXIOM_TOKEN` is the Axiom API token you have generated.
3. In the `next.config.ts` file, wrap your Next.js configuration in `withAxiom`:
```js
const { withAxiom } = require("next-axiom");
module.exports = withAxiom({
// Your existing configuration.
});
```
### Capture traffic requests [#capture-traffic-requests-1]
To capture traffic requests, create a `middleware.ts` file in the root folder of your Next.js app:
```ts [expandable]
import { Logger } from 'next-axiom'
import { NextResponse } from 'next/server'
import type { NextFetchEvent, NextRequest } from 'next/server'
export async function middleware(request: NextRequest, event: NextFetchEvent) {
const logger = new Logger({ source: 'middleware' }); // traffic, request
logger.middleware(request)
event.waitUntil(logger.flush())
return NextResponse.next()
}
// For more information, see Matching Paths below
export const config = {
}
```
Next.js 16 renamed middleware to proxy. If your app uses Next.js 16 or later, name the file `proxy.ts` and the exported function `proxy` instead. `middleware.ts` still works in Next.js 16, but it's deprecated.
### Web Vitals [#web-vitals-1]
To send Web Vitals to Axiom, add the `AxiomWebVitals` component from next-axiom to the `app/layout.tsx` file:
```ts [expandable]
import { AxiomWebVitals } from "next-axiom";
export default function RootLayout() {
return (
...
...
);
}
```
Web Vitals are only sent from production deployments.
### Logs [#logs-1]
Send logs to Axiom from different parts of your app. Each log function call takes a message and an optional `fields` object.
```ts [expandable]
log.debug("Login attempt", { user: "j_doe", status: "success" }); // Results in {"message": "Login attempt", "fields": {"user": "j_doe", "status": "success"}}
log.info("Payment completed", { userID: "123", amount: "25USD" });
log.warn("API rate limit exceeded", {
endpoint: "/users/1",
rateLimitRemaining: 0,
});
log.error("System Error", { code: "500", message: "Internal server error" });
```
#### Route handlers [#route-handlers-1]
Wrap your route handlers in `withAxiom` to add a logger to your request and log exceptions automatically:
```ts [expandable]
import { withAxiom, AxiomRequest } from "next-axiom";
export const GET = withAxiom((req: AxiomRequest) => {
req.log.info("Login function called");
// You can create intermediate loggers
const log = req.log.with({ scope: "user" });
log.info("User logged in", { userId: 42 });
return NextResponse.json({ hello: "world" });
});
```
#### Client components [#client-components-1]
To send logs from client components, add `useLogger` from next-axiom to your component:
```ts [expandable]
"use client";
import { useLogger } from "next-axiom";
export default function ClientComponent() {
const log = useLogger();
log.debug("User logged in", { userId: 42 });
return Logged in ;
}
```
#### Server components [#server-components-1]
To send logs from server components, add `Logger` from next-axiom to your component, and call flush before returning:
```ts [expandable]
import { Logger } from "next-axiom";
export default async function ServerComponent() {
const log = new Logger();
log.info("User logged in", { userId: 42 });
// ...
await log.flush();
return Logged in ;
}
```
#### Log levels [#log-levels]
The log level defines the lowest level of logs sent to Axiom. Choose one of the following levels (from lowest to highest):
* `debug` is the default setting. It means that you send all logs to Axiom.
* `info`
* `warn`
* `error` means that you only send the highest-level logs to Axiom.
* `off` means that you don’t send any logs to Axiom.
For example, to send all logs except for debug logs to Axiom:
```sh
export NEXT_PUBLIC_AXIOM_LOG_LEVEL=info
```
### Capture errors [#capture-errors-1]
To capture routing errors, use the [error handling mechanism of Next.js](https://nextjs.org/docs/app/building-your-application/routing/error-handling):
1. Go to the `app` folder.
2. Create an `error.tsx` file.
3. Inside your component function, add `useLogger` from next-axiom to send the error to Axiom. For example:
```ts [expandable]
"use client";
import NavTable from "@/components/NavTable";
import { LogLevel } from "@/next-axiom/logger";
import { useLogger } from "next-axiom";
import { usePathname } from "next/navigation";
export default function ErrorPage({
error,
}: {
error: Error & { digest?: string };
}) {
const pathname = usePathname();
const log = useLogger({ source: "error.tsx" });
let status = error.message == "Invalid URL" ? 404 : 500;
log.logHttpRequest(
LogLevel.error,
error.message,
{
host: window.location.href,
path: pathname,
statusCode: status,
},
{
error: error.name,
cause: error.cause,
stack: error.stack,
digest: error.digest,
}
);
return (
Ops! An Error has occurred:{" "}
`{error.message}`
);
}
```
### Extend logger [#extend-logger]
To extend the logger, use `log.with` to create an intermediate logger. For example:
```ts [expandable]
const logger = useLogger().with({ userId: 42 });
logger.info("Hi"); // will ingest { ..., "message": "Hi", "fields" { "userId": 42 }}
```
---
# Send OpenTelemetry data to Axiom
Source: https://axiom.co/docs/send-data/opentelemetry
OpenTelemetry (OTel) is a set of APIs, libraries, and agents to capture distributed traces and metrics from your app. It’s a Cloud Native Computing Foundation (CNCF) project that was started to create a unified solution for service and app performance monitoring.
The OpenTelemetry project has published strong specifications for the three main pillars of observability: logs, traces, and metrics. These schemas are supported by all tools and services that support interacting with OpenTelemetry. Axiom supports OpenTelemetry natively on an API level, allowing you to connect any existing OpenTelemetry shipper, library, or tool to Axiom for sending data.
OpenTelemetry-compatible events flow into Axiom, where they’re organized into datasets for easy segmentation. Users can create a dataset to receive OpenTelemetry data and obtain an API token for ingestion. Axiom provides comprehensive observability through browsing, querying, dashboards, and alerting of OpenTelemetry data.
| OpenTelemetry component | Support |
| ------------------------------------------------------------------ | ------- |
| [Logs](https://opentelemetry.io/docs/concepts/signals/logs/) | ✓ |
| [Traces](https://opentelemetry.io/docs/concepts/signals/traces/) | ✓ |
| [Metrics](https://opentelemetry.io/docs/concepts/signals/metrics/) | ✓ |
You must use a different, dedicated dataset for each OTel component. When you create a dataset, select **Events** for logs or traces data, and select **Metrics** for metrics data. For more information, see [Create dataset](/reference/datasets#create-dataset).
## OpenTelemetry Collector [#opentelemetry-collector]
Configuring the OpenTelemetry collector is as simple as creating an HTTP exporter that sends data to the Axiom API together with headers to set the dataset and API token.
```yaml
exporters:
otlphttp:
compression: zstd
endpoint: https://AXIOM_DOMAIN
headers:
authorization: Bearer API_TOKEN
x-axiom-dataset: DATASET_NAME
service:
pipelines:
logs:
receivers:
- otlp
processors:
- memory_limiter
- batch
exporters:
- otlphttp
```
```yaml
exporters:
otlphttp:
compression: zstd
endpoint: https://AXIOM_DOMAIN
headers:
authorization: Bearer API_TOKEN
x-axiom-dataset: DATASET_NAME
service:
pipelines:
traces:
receivers:
- otlp
processors:
- memory_limiter
- batch
exporters:
- otlphttp
```
```yaml
processors:
batch:
send_batch_max_size: 8192
exporters:
otlphttp:
compression: zstd
endpoint: https://AXIOM_DOMAIN
headers:
authorization: Bearer API_TOKEN
x-axiom-metrics-dataset: DATASET_NAME
service:
pipelines:
metrics:
receivers:
- otlp
processors:
- memory_limiter
- batch
exporters:
- otlphttp
```
When configuring metrics, use the `x-axiom-metrics-dataset` header instead of `x-axiom-dataset`.
When using the OTLP/HTTP endpoint, the following endpoint URLs should be used in your SDK exporter OTel configuration.
* Traces: `https://AXIOM_DOMAIN/v1/traces`
* Logs: `https://AXIOM_DOMAIN/v1/logs`
* Metrics: `https://AXIOM_DOMAIN/v1/metrics`
The `/v1/metrics` endpoint accepts OTLP data encoded as Protobuf (`application/x-protobuf`) or JSON (`application/json`). Protobuf payloads are smaller, so prefer Protobuf when you send large volumes of metrics.
## OpenTelemetry for Go [#opentelemetry-for-go]
The example below configures a Go app using the [OpenTelemetry SDK for Go](https://github.com/open-telemetry/opentelemetry-go) to send OpenTelemetry data to Axiom.
```go
package main
import (
"context" // For managing request-scoped values, cancellation signals, and deadlines.
"crypto/tls" // For configuring TLS options, like certificates.
// OpenTelemetry imports for setting up tracing and exporting telemetry data.
"go.opentelemetry.io/otel" // Core OpenTelemetry APIs for managing tracers.
"go.opentelemetry.io/otel/attribute" // For creating and managing trace attributes.
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" // HTTP trace exporter for OpenTelemetry Protocol (OTLP).
"go.opentelemetry.io/otel/propagation" // For managing context propagation formats.
"go.opentelemetry.io/otel/sdk/resource" // For defining resources that describe an entity producing telemetry.
"go.opentelemetry.io/otel/sdk/trace" // For configuring tracing, like sampling and processors.
semconv "go.opentelemetry.io/otel/semconv/v1.24.0" // Semantic conventions for resource attributes.
)
const (
serviceName = "axiom-go-otel" // Name of the service for tracing.
serviceVersion = "0.1.0" // Version of the service.
otlpEndpoint = "AXIOM_DOMAIN" // OTLP collector endpoint.
bearerToken = "Bearer API_TOKEN" // Authorization token.
deploymentEnvironment = "production" // Deployment environment.
)
func SetupTracer() (func(context.Context) error, error) {
ctx := context.Background()
return InstallExportPipeline(ctx) // Setup and return the export pipeline for telemetry data.
}
func Resource() *resource.Resource {
// Defines resource with service name, version, and environment.
return resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceNameKey.String(serviceName),
semconv.ServiceVersionKey.String(serviceVersion),
attribute.String("environment", deploymentEnvironment),
)
}
func InstallExportPipeline(ctx context.Context) (func(context.Context) error, error) {
// Sets up OTLP HTTP exporter with endpoint, headers, and TLS config.
exporter, err := otlptracehttp.New(ctx,
otlptracehttp.WithEndpoint(otlpEndpoint),
otlptracehttp.WithHeaders(map[string]string{
"Authorization": bearerToken,
"X-AXIOM-DATASET": "DATASET_NAME",
}),
otlptracehttp.WithTLSClientConfig(&tls.Config{}),
)
if err != nil {
return nil, err
}
// Configures the tracer provider with the exporter and resource.
tracerProvider := trace.NewTracerProvider(
trace.WithBatcher(exporter),
trace.WithResource(Resource()),
)
otel.SetTracerProvider(tracerProvider)
// Sets global propagator to W3C Trace Context and Baggage.
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{},
propagation.Baggage{},
))
return tracerProvider.Shutdown, nil // Returns a function to shut down the tracer provider.
}
```
## OpenTelemetry for Ruby [#opentelemetry-for-ruby]
To send traces to an OpenTelemetry Collector using the [OTLP over HTTP in Ruby](https://github.com/open-telemetry/opentelemetry-ruby), use the `opentelemetry-exporter-otlp-http` gem provided by the OpenTelemetry project.
```bash
require 'opentelemetry/sdk'
require 'opentelemetry/exporter/otlp'
require 'opentelemetry/instrumentation/all'
OpenTelemetry::SDK.configure do |c|
c.service_name = 'ruby-traces' # Set your service name
c.use_all # or specify individual instrumentation you need
c.add_span_processor(
OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(
OpenTelemetry::Exporter::OTLP::Exporter.new(
endpoint: 'https://AXIOM_DOMAIN/v1/traces',
headers: {
'Authorization' => 'Bearer API_TOKEN',
'X-AXIOM-DATASET' => 'DATASET_NAME'
}
)
)
)
end
```
## OpenTelemetry for Java [#opentelemetry-for-java]
Here is a basic configuration for a Java app that sends traces to an OpenTelemetry Collector using OTLP over HTTP using the [OpenTelemetry Java SDK](https://github.com/open-telemetry/opentelemetry-java):
```java
package com.example;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import java.util.concurrent.TimeUnit;
public class OtelConfiguration {
// OpenTelemetry configuration
private static final String SERVICE_NAME = "SERVICE_NAME";
private static final String SERVICE_VERSION = "SERVICE_VERSION";
private static final String OTLP_ENDPOINT = "https://AXIOM_DOMAIN/v1/traces";
private static final String BEARER_TOKEN = "Bearer API_TOKEN";
private static final String AXIOM_DATASET = "DATASET_NAME";
public static OpenTelemetry initializeOpenTelemetry() {
// Create a Resource with service name and version
Resource resource = Resource.getDefault()
.merge(Resource.create(Attributes.of(
AttributeKey.stringKey("service.name"), SERVICE_NAME,
AttributeKey.stringKey("service.version"), SERVICE_VERSION
)));
// Create an OTLP/HTTP span exporter
OtlpHttpSpanExporter spanExporter = OtlpHttpSpanExporter.builder()
.setEndpoint(OTLP_ENDPOINT)
.addHeader("Authorization", BEARER_TOKEN)
.addHeader("X-Axiom-Dataset", AXIOM_DATASET)
.build();
// Create a BatchSpanProcessor with the OTLP/HTTP exporter
SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder()
.addSpanProcessor(BatchSpanProcessor.builder(spanExporter)
.setScheduleDelay(100, TimeUnit.MILLISECONDS)
.build())
.setResource(resource)
.build();
// Build and register the OpenTelemetry SDK
OpenTelemetrySdk openTelemetry = OpenTelemetrySdk.builder()
.setTracerProvider(sdkTracerProvider)
.buildAndRegisterGlobal();
// Add a shutdown hook to properly close the SDK
Runtime.getRuntime().addShutdownHook(new Thread(sdkTracerProvider::close));
return openTelemetry;
}
}
```
## OpenTelemetry for .NET [#opentelemetry-for-net]
You can send traces to Axiom using the [OpenTelemetry .NET SDK](https://github.com/open-telemetry/opentelemetry-dotnet) by configuring an OTLP HTTP exporter in your .NET app. Here is a simple example:
```csharp
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using System;
using System.Diagnostics;
using System.Reflection;
// Class to configure OpenTelemetry tracing
public static class TracingConfiguration
{
// Declares an ActivitySource for creating tracing activities
private static readonly ActivitySource ActivitySource = new("MyCustomActivitySource");
// Configures OpenTelemetry with custom settings and instrumentation
public static void ConfigureOpenTelemetry()
{
// Retrieve the service name and version from the executing assembly metadata
var serviceName = Assembly.GetExecutingAssembly().GetName().Name ?? "UnknownService";
var serviceVersion = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "UnknownVersion";
// Setting up the tracer provider with various configurations
Sdk.CreateTracerProviderBuilder()
.SetResourceBuilder(
// Set resource attributes including service name and version
ResourceBuilder.CreateDefault().AddService(serviceName, serviceVersion: serviceVersion)
.AddAttributes(new[] { new KeyValuePair("environment", "development") }) // Additional attributes
.AddTelemetrySdk() // Add telemetry SDK information to the traces
.AddEnvironmentVariableDetector()) // Detect resource attributes from environment variables
.AddSource(ActivitySource.Name) // Add the ActivitySource defined above
.AddAspNetCoreInstrumentation() // Add automatic instrumentation for ASP.NET Core
.AddHttpClientInstrumentation() // Add automatic instrumentation for HttpClient requests
.AddOtlpExporter(options => // Configure the OTLP exporter
{
options.Endpoint = new Uri("https://AXIOM_DOMAIN/v1/traces"); // Set the endpoint for the exporter
options.Protocol = OpenTelemetry.Exporter.OtlpExportProtocol.HttpProtobuf; // Set the protocol
options.Headers = "Authorization=Bearer API_TOKEN, X-Axiom-Dataset=DATASET_NAME"; // Update API token and dataset
})
.Build(); // Build the tracer provider
}
// Method to start a new tracing activity with an optional activity kind
public static Activity? StartActivity(string activityName, ActivityKind kind = ActivityKind.Internal)
{
// Starts and returns a new activity if sampling allows it, otherwise returns null
return ActivitySource.StartActivity(activityName, kind);
}
}
```
## OpenTelemetry for Python [#opentelemetry-for-python]
You can send traces to Axiom using the [OpenTelemetry Python SDK](https://github.com/open-telemetry/opentelemetry-python) by configuring an OTLP HTTP exporter in your Python app. Here is a simple example:
```python
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.resources import Resource, SERVICE_NAME
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
# Define the service name resource for the tracer.
resource = Resource(attributes={
SERVICE_NAME: "NAME_OF_SERVICE" # Replace `NAME_OF_SERVICE` with the name of the service you want to trace.
})
# Create a TracerProvider with the defined resource for creating tracers.
provider = TracerProvider(resource=resource)
# Configure the OTLP/HTTP Span Exporter with Axiom headers and endpoint. Replace `API_TOKEN` with your Axiom API key, and replace `DATASET_NAME` with the name of the Axiom dataset where you want to send data.
otlp_exporter = OTLPSpanExporter(
endpoint="https://AXIOM_DOMAIN/v1/traces",
headers={
"Authorization": "Bearer API_TOKEN",
"X-Axiom-Dataset": "DATASET_NAME"
}
)
# Create a BatchSpanProcessor with the OTLP exporter to batch and send trace spans.
processor = BatchSpanProcessor(otlp_exporter)
provider.add_span_processor(processor)
# Set the TracerProvider as the global tracer provider.
trace.set_tracer_provider(provider)
# Define a tracer for external use in different parts of the app.
service1_tracer = trace.get_tracer("service1")
```
## OpenTelemetry for Node [#opentelemetry-for-node]
You can send traces to Axiom using the [OpenTelemetry Node SDK](https://github.com/open-telemetry/opentelemetry-js) by configuring an OTLP HTTP exporter in your Node app. Here is a simple example:
```js
const opentelemetry = require('@opentelemetry/sdk-node');
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-proto');
const { BatchSpanProcessor } = require('@opentelemetry/sdk-trace-base');
const { Resource } = require('@opentelemetry/resources');
const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions');
// Initialize OTLP trace exporter with the URL and headers for the Axiom API
const traceExporter = new OTLPTraceExporter({
url: 'https://AXIOM_DOMAIN/v1/traces', // Axiom API endpoint for trace data
headers: {
'Authorization': 'Bearer API_TOKEN', // Replace API_TOKEN with your actual API token
'X-Axiom-Dataset': 'DATASET_NAME' // Replace DATASET_NAME with your dataset
},
});
// Define the resource attributes, in this case, setting the service name for the traces
const resource = new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: 'node traces', // Name for the tracing service
});
// Create a NodeSDK instance with the configured span processor, resource, and auto-instrumentations
const sdk = new opentelemetry.NodeSDK({
spanProcessor: new BatchSpanProcessor(traceExporter), // Use BatchSpanProcessor for batching and sending traces
resource: resource, // Attach the defined resource to provide additional context
instrumentations: [getNodeAutoInstrumentations()], // Automatically instrument common Node.js modules
});
// Start the OpenTelemetry SDK
sdk.start();
```
## OpenTelemetry for Cloudflare Workers [#opentelemetry-for-cloudflare-workers]
Configure OpenTelemetry in Cloudflare Workers to send telemetry data to Axiom using the [OTel CF Worker package](https://github.com/evanderkoogh/otel-cf-workers). Here is an example exporter configuration:
```js
// index.ts
import { trace } from '@opentelemetry/api';
import { instrument, ResolveConfigFn } from '@microlabs/otel-cf-workers';
export interface Env {
AXIOM_TOKEN: string,
AXIOM_DATASET: string,
AXIOM_DOMAIN: string
}
const handler = {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise {
await fetch('https://cloudflare.com');
const greeting = "Welcome to Axiom Cloudflare instrumentation";
trace.getActiveSpan()?.setAttribute('greeting', greeting);
ctx.waitUntil(fetch('https://workers.dev'));
return new Response(`${greeting}!`);
},
};
const config: ResolveConfigFn = (env: Env, _trigger) => {
return {
exporter: {
url: `https://${env.AXIOM_DOMAIN}/v1/traces`,
headers: {
'Authorization': `Bearer ${env.AXIOM_TOKEN}`,
'X-Axiom-Dataset': `${env.AXIOM_DATASET}`
},
},
service: { name: 'axiom-cloudflare-workers' },
};
};
export default instrument(handler, config);
```
### Requirements for log level fields [#requirements-for-log-level-fields]
Axiom supports [severity matching](/reference/limits#requirements-for-log-level-fields) for OpenTelemetry logs.
## Additional resources [#additional-resources]
For further guidance on integrating OpenTelemetry with Axiom, explore the following guides:
* [Node.js OpenTelemetry guide](/guides/opentelemetry-nodejs)
* [Python OpenTelemetry guide](/guides/opentelemetry-python)
* [Golang OpenTelemetry guide](/guides/opentelemetry-go)
* [Cloudflare Workers guide](/guides/opentelemetry-cloudflare-workers)
* [Ruby on Rails OpenTelemetry guide](/guides/opentelemetry-ruby)
* [.NET OpenTelemetry guide](/guides/opentelemetry-dotnet)
---
# Send PgBouncer metrics to Axiom
Source: https://axiom.co/docs/send-data/pgbouncer
PgBouncer tracks detailed pool and query statistics, but it only exposes them through its admin console (`SHOW STATS`, `SHOW POOLS`) over the PostgreSQL wire protocol — there’s no native Prometheus or OTLP endpoint. To send these metrics to Axiom, run the Prometheus community’s [pgbouncer\_exporter](https://github.com/prometheus-community/pgbouncer_exporter) next to PgBouncer, and an OpenTelemetry Collector that scrapes the exporter and forwards the metrics to Axiom.
The Prometheus receiver is part of the [contrib distribution](https://github.com/open-telemetry/opentelemetry-collector-releases) of the OpenTelemetry Collector (`otelcol-contrib`). It isn’t included in the core distribution.
When you create the dataset, select **Metrics** as the dataset type. Metrics require their own dedicated dataset. For more information, see [Create dataset](/reference/datasets#create-dataset).
## Expose PgBouncer stats with pgbouncer\_exporter [#expose-pgbouncer-stats-with-pgbouncer_exporter]
In `pgbouncer.ini`, allow a user to read stats and let the exporter connect:
```ini
stats_users = stats
ignore_startup_parameters = extra_float_digits
```
Then run the exporter, pointing it at PgBouncer’s special `pgbouncer` admin database:
```shell
docker run -d -p 9127:9127 prometheuscommunity/pgbouncer-exporter \
--pgBouncer.connectionString="postgres://stats:PASSWORD@pgbouncer:6432/pgbouncer?sslmode=disable"
```
Replace the connection string with your PgBouncer host, port, and stats user. You can also set it with the `PGBOUNCER_EXPORTER_CONNECTION_STRING` environment variable. The exporter then serves metrics at `http://localhost:9127/metrics`.
## Configure the OpenTelemetry Collector [#configure-the-opentelemetry-collector]
Add a Prometheus receiver that scrapes the exporter and an OTLP/HTTP exporter that sends data to Axiom:
```yaml
receivers:
prometheus:
config:
scrape_configs:
- job_name: pgbouncer
scrape_interval: 15s
static_configs:
- targets: ["pgbouncer-exporter:9127"] # host:port of pgbouncer_exporter
processors:
memory_limiter:
check_interval: 1s
limit_percentage: 80
spike_limit_percentage: 25
batch:
send_batch_max_size: 8192
exporters:
otlphttp:
compression: zstd
endpoint: https://AXIOM_DOMAIN
headers:
authorization: Bearer API_TOKEN
x-axiom-metrics-dataset: DATASET_NAME
service:
pipelines:
metrics:
receivers:
- prometheus
processors:
- memory_limiter
- batch
exporters:
- otlphttp
```
For metrics, use the `x-axiom-metrics-dataset` header instead of `x-axiom-dataset`.
## Query your metrics [#query-your-metrics]
Once data is flowing, query your PgBouncer metrics like any other OTel metrics in Axiom. Pool metrics carry `database` and `user` tags. For example, to chart active client connections per database:
```mpl
`DATASET_NAME`:`pgbouncer_pools_client_active_connections`
| align to $__interval using last
| group by `database` using sum
```
For more information, see [Metrics](/query-data/metrics).
---
# Send data from client-side React apps to Axiom
Source: https://axiom.co/docs/send-data/react
React is a popular open-source JavaScript library developed by Meta for building user interfaces. Known for its component-based architecture and efficient rendering with a virtual DOM, React is widely used by companies of all sizes to create fast, scalable, and dynamic web applications.
This page explains how to use the @axiomhq/react library to send data from your client-side React apps to Axiom.
The @axiomhq/react library is part of the Axiom JavaScript SDK, an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/axiom-js).
* A new or existing React app.
## Install @axiomhq/react library [#install-axiomhqreact-library]
1. In your terminal, go to the root folder of your React app and run the following command:
```sh
npm install --save @axiomhq/logging @axiomhq/react
```
2. Create a `Logger` instance and export the utils. The example below uses the `useLogger` and `WebVitals` components.
```tsx [expandable]
'use client';
import { Logger, AxiomJSTransport } from '@axiomhq/logging';
import { Axiom } from '@axiomhq/js';
import { createUseLogger, createWebVitalsComponent } from '@axiomhq/react';
const axiomClient = new Axiom({
token: process.env.AXIOM_TOKEN!,
});
export const logger = new Logger({
transports: [
new AxiomJSTransport({
axiom: axiomClient,
dataset: process.env.AXIOM_DATASET!,
}),
],
});
const useLogger = createUseLogger(logger);
const WebVitals = createWebVitalsComponent(logger);
export { useLogger, WebVitals };
```
## Send logs from components [#send-logs-from-components]
To send logs from components, use the `useLogger` hook that returns your logger instance.
```tsx
import { useLogger } from "@/lib/axiom/client";
import { useEffect } from "react";
export default function ClientComponent() {
const log = useLogger();
const handleClick = () => log.info("User logged out");
useEffect(() => {
log.info("User logged in", { userId: 42 });
}, []);
return (
Logged in
Log out
);
}
```
## Send Web Vitals [#send-web-vitals]
To send Web Vitals, mount the `WebVitals` component in the root of your React app.
```tsx
import { WebVitals } from "@/lib/axiom/client";
export default function App({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
---
# Reference architectures
Source: https://axiom.co/docs/send-data/reference-architectures
Successfully adopting a new platform at scale requires a robust and reliable data collection strategy. In complex distributed systems, how you collect and forward telemetry is as important as the platform that analyzes it.
While Axiom is flexible and supports dozens of [methods](/send-data/methods), there is a confident, battle-tested recommendation for large-scale environments. This guide outlines Axiom’s recommended architectural patterns using two popular tools: the [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) and [Vector](https://vector.dev/).
These patterns are designed to provide:
* **Resilience:** Ensure no data is lost during network partitions or downstream issues.
* **Enrichment:** Add valuable, consistent metadata to all your telemetry at the source.
* **Performance:** Offload processing and batching from your applications.
* **Governance:** Centrally manage data routing, filtering, and sampling to control costs.
While these patterns are recommended for large-scale environments, Axiom has many other simpler [methods](/send-data/methods) available to send data.
## The core patterns [#the-core-patterns]
There are two primary deployment patterns for a collector: the Agent model and the Aggregator model. Most large organizations use a hybrid of both.
Most organizations find it easy to send data to Axiom. If you are having trouble, please [contact](https://axiom.co/contact) the Axiom team for help. We can provide ad-hoc guidance or design tailored implementation services for larger projects.
### Agent pattern [#agent-pattern]
In this model, a lightweight collector runs as an agent on every host or as a sidecar in every pod. It’s responsible for collecting telemetry from applications on that specific node and forwarding it directly to Axiom.
**Best for:** Capturing rich, host-specific metadata (for example, `k8s.pod.name`, `host.id`) and providing a resilient, decentralized collection point with local buffering.
### Aggregator pattern [#aggregator-pattern]
In this model, a separate, horizontally scalable pool of collectors acts as a centralized aggregation layer. Applications and agents send their data to this layer, which then handles final processing, enrichment, and forwarding to Axiom.
**Best for:** Centralized control over data routing and filtering, managing data from sources that can't run an agent (for example, third-party APIs, cloud provider log streams), and simplifying management by maintaining a small fleet of aggregators instead of thousands of agents.
## Tool recommendations [#tool-recommendations]
Both the OpenTelemetry Collector and Vector are excellent choices that can be deployed in either an Agent or Aggregator pattern. The best choice depends on your team’s existing ecosystem and primary use case.
### OpenTelemetry Collector [#opentelemetry-collector]
The [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) is the CNCF-backed, vendor-neutral standard for collecting and processing telemetry. It’s the ideal choice when your organization is standardizing on the OpenTelemetry framework for all signals (logs, metrics, and traces).
**Use the OTel Collector when:**
* You are instrumenting your applications with OpenTelemetry SDKs.
* You need to process traces, metrics, and logs in a single, unified pipeline.
* You want to align with the fastest-growing standard in the observability community.
Axiom natively supports the OpenTelemetry Line Protocol (OTLP). Configuring the collector to send data to Axiom is simple.
**Example Collector Configuration (`otel-collector-config.yaml`):**
```yaml
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_percentage: 80
spike_limit_percentage: 25
batch:
batch/metrics:
send_batch_max_size: 8192
exporters:
# Exporter for logs and traces
otlphttp:
compression: zstd
endpoint: https://AXIOM_DOMAIN
headers:
authorization: Bearer API_TOKEN
x-axiom-dataset: DATASET_NAME
# Exporter for metrics
otlphttp/metrics:
compression: zstd
endpoint: https://AXIOM_DOMAIN
headers:
authorization: Bearer API_TOKEN
x-axiom-metrics-dataset: DATASET_NAME
service:
pipelines:
traces:
receivers:
- otlp
processors:
- memory_limiter
- batch
exporters:
- otlphttp
logs:
receivers:
- otlp
processors:
- memory_limiter
- batch
exporters:
- otlphttp
metrics:
receivers:
- otlp
processors:
- memory_limiter
- batch/metrics
exporters:
- otlphttp/metrics
```
When configuring metrics, use the `x-axiom-metrics-dataset` header instead of `x-axiom-dataset`.
### Vector [#vector]
[Vector](https://vector.dev/) is a high-performance, Rust-based observability data pipeline. It excels at log collection and transformation, offering a powerful domain-specific language (VRL) for complex data manipulation.
**Use Vector when:**
* Your primary focus is on logs from a wide variety of sources (files, syslog, APIs).
* You need to perform complex parsing, filtering, enrichment, or redaction on your event data.
* You require an extremely lightweight and memory-efficient agent for edge deployments.
Vector has a [native sink](https://vector.dev/docs/reference/configuration/sinks/axiom/) for Axiom, making configuration straightforward.
**Example Vector Configuration (`vector.toml`):**
```toml
[sources.VECTOR_SOURCE_ID]
type = "file"
include = ["PATH_TO_LOGS"]
[sinks.SINK_ID]
type = "axiom"
inputs = ["VECTOR_SOURCE_ID"]
token = "API_TOKEN"
dataset = "DATASET_NAME"
```
Replace `VECTOR_SOURCE_ID` with the Vector source ID.
Replace `PATH_TO_LOGS` with the path to the log files. For example, `/var/log/**/*.log`.
Replace `SINK_ID` with the sink ID.
## Summary [#summary]
| Aspect | OpenTelemetry Collector | Vector |
| :------------------- | :--------------------------------------------- | :------------------------------------------------------ |
| **Primary Use Case** | Unified pipeline for logs, metrics, and traces | High-performance log collection and transformation |
| **Ecosystem** | CNCF and OpenTelemetry standard | Standalone, broad source/sink compatibility |
| **Transformation** | Processors (limited for complex logic) | Vector Remap Language (VRL) for advanced logic |
| **Performance** | Excellent | Excellent, often with lower resource footprint for logs |
Both are first-class choices for sending data to Axiom. Your decision should be based on whether you need a unified OTel pipeline or a specialized, high-performance log processing tool.
### What’s next? [#whats-next]
* Explore the complete range of options for sending data in the [Methods](/send-data/methods) page.
* For direct ingestion, see the [Axiom REST API](/restapi/introduction).
---
# Send logs from Render to Axiom
Source: https://axiom.co/docs/send-data/render
Render is a unified cloud to build and run all your apps and websites. Axiom provides complete visibility into your Render projects, allowing you to monitor the behavior of your websites and apps.
Render log streams forward logs to a syslog destination over TLS. To send them to Axiom, run a syslog receiver such as Vector on infrastructure you control, and let it forward the logs to Axiom over HTTPS.
* [Create an account on Render](https://dashboard.render.com/login).
## Setup [#setup]
### Run a syslog receiver [#run-a-syslog-receiver]
Set up Vector with a TLS-enabled `syslog` source and an `axiom` sink. For the configuration, see [Send data from syslog to Axiom over a secure connection](/send-data/secure-syslog). The receiver must be reachable from the internet so that Render can connect to it.
### Create log stream in Render [#create-log-stream-in-render]
In Render, create a log stream. For more information, see the [Render documentation](https://render.com/docs/log-streams). As the log endpoint, use the host and port where your receiver listens, for example `syslog.example.com:6514`.
Back in your Axiom dataset, you see logs coming from Render.
---
# Send data from syslog to Axiom over a secure connection
Source: https://axiom.co/docs/send-data/secure-syslog
This page explains how to send syslog data to Axiom over a TLS-encrypted connection. Run a syslog receiver on infrastructure you control, point your syslog clients at it, and let the receiver forward the data to Axiom over HTTPS.
Axiom recommends [Vector](https://vector.dev/) as the receiver. Vector accepts syslog over TLS and adds the batching, retries, and error reporting that the syslog protocol lacks. If your clients are on a trusted network and don’t need TLS, you can also use the [Axiom Syslog Proxy](/send-data/syslog-proxy).
* [Install Vector](https://vector.dev/docs/setup/installation/) on a host that your syslog clients can reach.
* A TLS certificate and private key for that host.
## Configure Vector [#configure-vector]
Create a configuration file, for example `vector.toml`, with a `syslog` source that listens over TLS and an `axiom` sink:
```toml
[sources.syslog_tls]
type = "syslog"
address = "0.0.0.0:6514"
mode = "tcp"
max_length = 102_400
[sources.syslog_tls.tls]
enabled = true
crt_file = "/etc/vector/server.crt"
key_file = "/etc/vector/server.key"
[sinks.axiom]
type = "axiom"
inputs = ["syslog_tls"]
dataset = "DATASET_NAME"
token = "API_TOKEN"
region = "AXIOM_DOMAIN"
```
Start Vector with the configuration file: `vector --config /path/to/vector.toml`.
Axiom highlights Syslog events by severity. For supported fields and levels, see [Log level detection](/reference/limits#supported-schemas).
For more configuration options, see the [Vector syslog source](https://vector.dev/docs/reference/configuration/sources/syslog/) and [Axiom sink](https://vector.dev/docs/reference/configuration/sinks/axiom/) documentation, and [Send data from Vector to Axiom](/send-data/vector).
Axiom highlights Syslog events by severity. For supported fields and levels, see [Log level detection](/reference/limits#supported-schemas).
## Configure syslog client [#configure-syslog-client]
Configure your syslog client to send messages over TCP with TLS to the address and port where Vector listens, for example `syslog.example.com:6514`. Ensure the client trusts the certificate authority that issued the receiver’s certificate.
In Axiom, click the **Stream** tab, select your dataset, and check that the messages arrive.
---
# Send data from Serverless to Axiom
Source: https://axiom.co/docs/send-data/serverless
Serverless is an open-source web framework for building apps on AWS Lambda. Sending event data from your Serverless apps to Axiom allows you to gain deep insights into your apps’ performance and behavior without complex setup or configuration.
To send data from Serverless to Axiom:
1. [Create an Axiom account](https://app.axiom.co/register).
2. [Create an API token in Axiom](/reference/tokens) with **Ingest**, **Query**, **Datasets**, **Dashboards**, and **Monitors** permissions.
3. [Create a Serverless account](https://app.serverless.com/).
4. Set up your app with Serverless using the [Serverless documentation](https://www.serverless.com/framework/docs/getting-started).
5. Configure Axiom in your Serverless Framework Service using the [Serverless documentation](https://www.serverless.com/framework/docs/guides/observability/axiom).
---
# Send data to Axiom using the Splunk HEC API
Source: https://axiom.co/docs/send-data/splunk-hec
Axiom offers a Splunk [HTTP Event Collector (HEC)](https://docs.splunk.com/Documentation/Splunk/latest/Data/UsetheHTTPEventCollector) compatible API so you can send events from Splunk forwarders, the OpenTelemetry `splunk_hec` exporter, and any other HEC client without changing your existing tooling.
The HEC API is served from a dedicated host on your edge deployment: `hec.AXIOM_DOMAIN`. For example, if your edge deployment’s base domain is `us-east-1.aws.edge.axiom.co`, the HEC endpoint is `https://hec.us-east-1.aws.edge.axiom.co`.
The HEC endpoints are hosted at `hec.AXIOM_DOMAIN`, a dedicated subdomain of your edge deployment’s base domain.
## Authentication [#authentication]
Authenticate every request with an Axiom [API token](/reference/tokens) that has permission to ingest into the target dataset. The HEC API accepts the token in any of the following schemes:
| Scheme | Header |
| :--------------------------- | :---------------------------------------------------------------------------------- |
| Splunk (default HEC clients) | `Authorization: Splunk API_TOKEN` |
| Bearer | `Authorization: Bearer API_TOKEN` |
| Basic | `Authorization: Basic ` (for example, `curl -u x:API_TOKEN`) |
Requests without a valid token are rejected with `401 Unauthorized` (missing token) or `403 Forbidden` (token not permitted for the dataset).
## Choose the target dataset [#choose-the-target-dataset]
In Splunk, events are routed by `index`. Axiom maps the HEC `index` to an Axiom [dataset](/reference/datasets) and resolves it in the following order:
1. The `index` query parameter, for example `?index=DATASET_NAME`.
2. The `index` field inside the event envelope.
3. The dataset the API token is scoped to, when the token grants ingest access to exactly one dataset.
If none of these resolve to a dataset, the request is rejected with HEC code `7` (Incorrect index).
## Send events [#send-events]
Send JSON events to `/services/collector/event`. The bare `/services/collector` path is an alias of the event endpoint. Each request body is one or more HEC event envelopes, which may be concatenated (newline-delimited or back-to-back).
```shell wrap
curl -X POST 'https://hec.AXIOM_DOMAIN/services/collector/event?index=DATASET_NAME' \
-H 'Authorization: Splunk API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{"event": {"message": "hello from HEC", "severity": "INFO"}, "sourcetype": "httpevent"}'
```
A successful ingest returns `200 OK` with the Splunk status body:
```json
{"text": "Success", "code": 0}
```
### Event envelope fields [#event-envelope-fields]
Axiom interprets the standard HEC envelope fields as follows:
| Field | Behavior |
| :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `event` | When an object, its keys become top-level fields of the Axiom event. When a string, it is stored in the `_raw` field. |
| `fields` | Merged into the event as top-level fields. |
| `time` | Parsed as the event timestamp (`_time`). Accepts epoch seconds, epoch milliseconds, or an RFC 3339 string. When omitted, Axiom assigns the ingest time. |
| `index` | Selects the target dataset (see [Choose the target dataset](#choose-the-target-dataset)) and is also retained as a field. |
| `host`, `source`, `sourcetype` | Retained as fields on the event. |
## Send raw events [#send-raw-events]
Send arbitrary payloads to `/services/collector/raw`. Metadata is supplied through query parameters rather than an envelope. Each line of a `text/plain` body becomes an event; JSON bodies are also accepted.
```shell wrap
curl -X POST 'https://hec.AXIOM_DOMAIN/services/collector/raw?index=DATASET_NAME&sourcetype=mysourcetype&source=mysource&host=myhost' \
-H 'Authorization: Splunk API_TOKEN' \
-H 'Content-Type: text/plain' \
--data-binary 'a raw log line
another raw log line'
```
## Compressed payloads [#compressed-payloads]
The HEC API accepts gzip-compressed request bodies. Set `Content-Encoding: gzip` and send the gzipped payload:
```shell wrap
curl -X POST 'https://hec.AXIOM_DOMAIN/services/collector/event?index=DATASET_NAME' \
-H 'Authorization: Splunk API_TOKEN' \
-H 'Content-Type: application/json' \
-H 'Content-Encoding: gzip' \
--data-binary @events.json.gz
```
## Check service health [#check-service-health]
`GET /services/collector/health` (and the versioned `/services/collector/health/1.0`) report whether the collector is accepting data. No authentication is required.
```shell wrap
curl 'https://hec.AXIOM_DOMAIN/services/collector/health'
```
```json
{"text": "HEC is healthy", "code": 17}
```
## Response codes [#response-codes]
Responses follow the Splunk HEC convention: an HTTP status code plus a JSON body carrying a Splunk `code`.
| HTTP status | HEC code | Meaning |
| :---------- | :------- | :--------------------------------------------------------- |
| `200` | `0` | Success. |
| `200` | `17` | The collector is healthy (health endpoints only). |
| `400` | `5` | No data. The request body was empty. |
| `400` | `6` | Invalid data format. The body could not be parsed. |
| `400` | `7` | Incorrect index. The target dataset could not be resolved. |
| `401` | — | Missing or unsupported authentication. |
| `403` | — | The token is not permitted to ingest into the dataset. |
---
# Send data from Splunk to Axiom
Source: https://axiom.co/docs/send-data/splunk
This page explains how to send data from Splunk forwarders and Splunk logging libraries to Axiom.
Axiom provides a [Splunk HEC compatible API](/send-data/splunk-hec) on your edge deployment. Any tool that sends data to a Splunk HTTP Event Collector (HEC) can send the same data to Axiom without changes to its code.
## Configure Splunk clients [#configure-splunk-clients]
In your Splunk forwarder or HEC client, specify the following:
* The HEC URL is `https://hec.AXIOM_DOMAIN/services/collector/event?index=DATASET_NAME`. For raw text payloads, use `https://hec.AXIOM_DOMAIN/services/collector/raw?index=DATASET_NAME`.
* The HEC token is your Axiom API token. The API accepts `Authorization: Splunk API_TOKEN`, `Authorization: Bearer API_TOKEN`, and HTTP basic authentication.
* Optional: If your client sets the `index` field on events instead of in the URL, Axiom sends each event to the dataset with that name.
For the full description of the API, including envelope fields and response codes, see [Send data to Axiom using the Splunk HEC API](/send-data/splunk-hec).
## Examples [#examples]
### Send logs from JavaScript using `splunk-logging` [#send-logs-from-javascript-using-splunk-logging]
```js
var SplunkLogger = require('splunk-logging').Logger;
var config = {
token: 'API_TOKEN',
url: 'https://hec.AXIOM_DOMAIN:443/services/collector/event?index=DATASET_NAME',
};
var Logger = new SplunkLogger(config);
var payload = {
// Message can be anything; doesn’t have to be an object
message: {
temperature: '70F',
chickenCount: 500,
},
};
console.log('Sending payload', payload);
Logger.send(payload, function (err, resp, body) {
// If successful, body will be { text: 'Success', code: 0 }
console.log('Response from Axiom', body);
});
```
### Send logs from Python using `splunk_handler` [#send-logs-from-python-using-splunk_handler]
```py
import logging
from splunk_handler import SplunkHandler
splunk = SplunkHandler(
host='hec.AXIOM_DOMAIN',
port='443',
protocol='https',
token='API_TOKEN',
index='DATASET_NAME'
)
logging.getLogger('').addHandler(splunk)
logging.warning('Hello from Axiom!')
```
### Send logs from Go using `net/http` [#send-logs-from-go-using-nethttp]
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
)
func main() {
event := map[string]any{
"time": time.Now().Unix(),
"sourcetype": "httpevent",
"event": map[string]any{
"message": "hello from Axiom",
"level": "info",
},
}
body, _ := json.Marshal(event)
req, _ := http.NewRequest(http.MethodPost, "https://hec.AXIOM_DOMAIN/services/collector/event?index=DATASET_NAME", bytes.NewReader(body))
req.Header.Set("Authorization", "Splunk API_TOKEN")
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}
```
---
# Send StatsD metrics to Axiom
Source: https://axiom.co/docs/send-data/statsd
StatsD is a simple push-based protocol for app metrics like counters, gauges, and timers. Axiom doesn’t provide a native StatsD listener. Instead, you send StatsD metrics to Axiom with the [StatsD receiver](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/statsdreceiver) of the OpenTelemetry Collector. The receiver listens for StatsD packets, aggregates them, and forwards the results to Axiom as OpenTelemetry metrics.
The StatsD receiver is part of the [contrib distribution](https://github.com/open-telemetry/opentelemetry-collector-releases) of the OpenTelemetry Collector (`otelcol-contrib`). It isn’t included in the core distribution.
When you create the dataset, select **Metrics** as the dataset type. StatsD data arrives in Axiom as OTel metrics, and metrics require their own dedicated dataset. For more information, see [Create dataset](/reference/datasets#create-dataset).
## Configure the OpenTelemetry Collector [#configure-the-opentelemetry-collector]
Add the StatsD receiver and an OTLP/HTTP exporter that sends data to Axiom:
```yaml
receivers:
statsd:
endpoint: 0.0.0.0:8125 # UDP by default. Defaults to localhost:8125 if omitted.
aggregation_interval: 60s # How often aggregated metrics are flushed to the exporter.
processors:
batch:
send_batch_max_size: 8192
exporters:
otlphttp:
compression: zstd
endpoint: https://AXIOM_DOMAIN
headers:
authorization: Bearer API_TOKEN
x-axiom-metrics-dataset: DATASET_NAME
service:
pipelines:
metrics:
receivers:
- statsd
processors:
- batch
exporters:
- otlphttp
```
For metrics, use the `x-axiom-metrics-dataset` header instead of `x-axiom-dataset`.
Point your StatsD clients at the collector’s address and port (UDP 8125 in the example above) instead of your previous StatsD server.
## Send a test metric [#send-a-test-metric]
With the collector running, send a test counter using netcat:
```shell
echo -n "test.requests:1|c" | nc -u -w1 localhost 8125
```
After the next aggregation interval, the `test.requests` metric appears in your Metrics dataset in Axiom.
## Metric types [#metric-types]
The StatsD receiver maps StatsD metric types to OpenTelemetry metric types:
| StatsD type | OpenTelemetry type |
| :------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Counter (`c`) | Sum |
| Gauge (`g`) | Gauge |
| Timer (`ms`), histogram (`h`), distribution (`d`) | Configurable with the receiver’s [`timer_histogram_mapping`](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/statsdreceiver) option: `histogram`, `summary`, or `gauge` |
Axiom supports all of these resulting types. For the full list of supported OTel metric types and current limitations, see [Supported data types](/query-data/metrics#supported-data-types).
## Query your metrics [#query-your-metrics]
Once data is flowing, query your StatsD metrics like any other OTel metrics in Axiom. For more information, see [Metrics](/query-data/metrics).
---
# Send data from syslog to Axiom
Source: https://axiom.co/docs/send-data/syslog-proxy
The Axiom Syslog Proxy acts as a syslog server to send data to Axiom.
The Axiom Syslog Proxy is an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/axiom-syslog-proxy).
## Syslog limitations and recommended alternatives [#syslog-limitations-and-recommended-alternatives]
Syslog is an outdated protocol. Some of the limitations are the following:
* Lack of error reporting and feedback mechanisms when issues occur.
* Inability to gracefully end the connection. This can result in missing data.
For a more reliable and modern logging experience, consider using tools like [Vector](https://vector.dev/) to receive syslog messages and [forward them to Axiom](/send-data/vector). This approach bypasses many of syslog’s limitations.
Other requirements:
* **Message size limit:** Axiom currently enforces a 64KB per-message size limit. This is in line with RFC5425 guidelines. Any message exceeding the limit causes the connection to close because Axiom doesn’t support ingesting truncated messages.
* **TLS requirement:** Axiom only supports syslog over TLS, specifically following RFC5425. Configure your syslog client accordingly.
* **Port requirements:** UDP log messages are sent on UDP port `514` to the Syslog server. TCP log messages are sent on TCP port `601` to the Syslog server.
Ensure your messages conform to the size limit and TLS requirements. If the connection is frequently re-established and messages are rejected, the issue can be the size of the messages or other formatting issues.
Axiom highlights Syslog events by severity. For supported fields and levels, see [Log level detection](/reference/limits#supported-schemas).
## Install Axiom Syslog Proxy [#install-axiom-syslog-proxy]
To install the Axiom Syslog Proxy, choose one of the following options:
* [Install using a pre-compiled binary file](#install-using-pre-compiled-binary-file)
* [Install using Homebrew](#install-using-homebrew)
* [Install using Go command](#install-using-go-command)
* [Install from the GitHub source](#install-from-github-source)
* [Install using a Docker image](#install-using-docker-image)
### Install using pre-compiled binary file [#install-using-pre-compiled-binary-file]
To install the Axiom Syslog Proxy using a pre-compiled binary file, download one of the [releases in GitHub](https://github.com/axiomhq/axiom-syslog-proxy/releases/latest).
### Install using Homebrew [#install-using-homebrew]
Run the following to install the Axiom Syslog Proxy using Homebrew:
```shell
brew tap axiomhq/tap
brew install axiom-syslog-proxy
```
### Install using Go command [#install-using-go-command]
Run the following to install the Axiom Syslog Proxy using `go get`:
```shell
go install github.com/axiomhq/axiom-syslog-proxy/cmd/axiom-syslog-proxy@latest
```
### Install from GitHub source [#install-from-github-source]
Run the following to install the Axiom Syslog Proxy from the GitHub source:
```shell
git clone https://github.com/axiomhq/axiom-syslog-proxy.git
cd axiom-syslog-proxy
make install
```
### Install using Docker image [#install-using-docker-image]
To install the Axiom Syslog Proxy using a Docker image, use a [Docker image from DockerHub](https://hub.docker.com/r/axiomhq/axiom-syslog-proxy/tags)
## Configure Axiom Syslog Proxy [#configure-axiom-syslog-proxy]
Set the following environment variables to connect to Axiom:
* `AXIOM_TOKEN` is the Axiom API token you have generated.
* `AXIOM_DATASET` is the name of the Axiom dataset where you want to send data.
* Optional: `AXIOM_URL` is the URL of the Axiom API. By default, it uses the `US East 1 (AWS)` edge deployment. Change the default value if your organization uses another edge deployment. For more information, see [Edge deployments](/reference/edge-deployments).
## Run Axiom Syslog Proxy [#run-axiom-syslog-proxy]
To run Axiom Syslog Proxy, run the following in your terminal.
```shell
./axiom-syslog-proxy
```
If you use Docker, run the following:
```shell
docker run -p601:601/tcp -p514:514/udp \
-e=AXIOM_TOKEN=API_TOKEN \
-e=AXIOM_DATASET=DATASET_NAME \
axiomhq/axiom-syslog-proxy
```
## Test configuration [#test-configuration]
To test that the Axiom Syslog Proxy configuration:
1. Run the following in your terminal to send two messages:
```shell
echo -n "tcp message" | nc -w1 localhost 601
echo -n "udp message" | nc -u -w1 localhost 514
```
2. In Axiom, click the **Stream** tab.
3. Click your dataset.
4. Check whether Axiom displays the messages you have sent.
---
# Send Traefik metrics to Axiom
Source: https://axiom.co/docs/send-data/traefik
Traefik exposes detailed metrics about its entrypoints, routers, and services in Prometheus format. Axiom ingests metrics over OTLP and doesn’t accept Prometheus remote-write, so the recommended setup is an OpenTelemetry Collector that scrapes Traefik’s Prometheus endpoint and forwards the metrics to Axiom. The same pattern works for any app that exposes Prometheus metrics.
The Prometheus receiver is part of the [contrib distribution](https://github.com/open-telemetry/opentelemetry-collector-releases) of the OpenTelemetry Collector (`otelcol-contrib`). It isn’t included in the core distribution.
When you create the dataset, select **Metrics** as the dataset type. Metrics require their own dedicated dataset. For more information, see [Create dataset](/reference/datasets#create-dataset).
## Enable Prometheus metrics in Traefik [#enable-prometheus-metrics-in-traefik]
Enable the Prometheus metrics provider in Traefik’s static configuration:
```yaml
metrics:
prometheus:
addEntryPointsLabels: true
addServicesLabels: true
```
Traefik then serves metrics at `/metrics` on the internal `traefik` entrypoint (port 8080 by default). To add per-router metrics, set `addRoutersLabels: true` as well. For all options, see the [Traefik documentation](https://doc.traefik.io/traefik/reference/install-configuration/observability/metrics/).
## Configure the OpenTelemetry Collector [#configure-the-opentelemetry-collector]
Add a Prometheus receiver that scrapes Traefik and an OTLP/HTTP exporter that sends data to Axiom:
```yaml
receivers:
prometheus:
config:
scrape_configs:
- job_name: traefik
scrape_interval: 15s
static_configs:
- targets: ["traefik:8080"] # host:port of Traefik's metrics entrypoint
processors:
memory_limiter:
check_interval: 1s
limit_percentage: 80
spike_limit_percentage: 25
batch:
send_batch_max_size: 8192
exporters:
otlphttp:
compression: zstd
endpoint: https://AXIOM_DOMAIN
headers:
authorization: Bearer API_TOKEN
x-axiom-metrics-dataset: DATASET_NAME
service:
pipelines:
metrics:
receivers:
- prometheus
processors:
- memory_limiter
- batch
exporters:
- otlphttp
```
For metrics, use the `x-axiom-metrics-dataset` header instead of `x-axiom-dataset`.
Traefik v3 can also push OTLP metrics directly (`metrics.otlp`) — for example, to the OTLP receiver of an OpenTelemetry Collector that forwards to Axiom as shown above. For more information, see the [Traefik documentation](https://doc.traefik.io/traefik/reference/install-configuration/observability/metrics/).
## Query your metrics [#query-your-metrics]
Once data is flowing, query your Traefik metrics like any other OTel metrics in Axiom. For example, to chart the request rate per service:
```mpl
`DATASET_NAME`:`traefik_service_requests_total`
| align to $__interval using prom::rate
| group by `service` using sum
```
For more information, see [Metrics](/query-data/metrics).
---
# Send data from Tremor to Axiom
Source: https://axiom.co/docs/send-data/tremor
Axiom provides a unique way of ingesting [Tremor logs](https://www.tremor.rs/) into Axiom. With your connector definitions, you can configure Tremor connectors and events components to interact with your external systems, such as databases, message queues, or APIs, and eventually ingest data from these sources into Axiom.
## Installation [#installation]
Install the latest package from the runtime [releases tag](https://github.com/tremor-rs/tremor-runtime/releases) on your local machine.
## Configuration using HTTP [#configuration-using-http]
To send logs via Tremor to Axiom, you need to create a configuration file. For example, create `axiom-http.troy` with the following content (using a file as example data source):
```text
define flow client_sink_only
flow
use std::time::nanos;
use tremor::pipelines;
define connector input from file
args
file = "in.json" # Default input file is 'in.json' in current working directory
with
codec = "json", # Data is JSON encoded
preprocessors = ["separate"], # Data is newline separated
config = {
"path": args.file,
"mode": "read"
},
end;
create connector input;
define connector http_client from http_client
args
dataset,
token
with
config = {
"url": "https://AXIOM_DOMAIN/v1/ingest/#{args.dataset}",
"tls": true,
"method": "POST",
"headers": {
"Authorization": "Bearer #{args.token}"
},
"timeout": nanos::from_seconds(10),
"mime_mapping": {
"*/*": {"name": "json"},
}
}
end;
create connector http_client
with
dataset = "DATASET_NAME",
token = "API_TOKEN"
end;
create pipeline passthrough from pipelines::passthrough;
connect /connector/input to /pipeline/passthrough;
connect /pipeline/passthrough to /connector/http_client;
end;
deploy flow client_sink_only;
```
This assumes you have set `TREMOR_PATH` in your environment pointing to `tremor-runtime/tremor-script/lib` if you are using a `src` clone then you can execute it as follows `tremor server run axiom-http.troy`
---
# Send data from Vector to Axiom
Source: https://axiom.co/docs/send-data/vector
Vector is a lightweight and ultra-fast tool for building observability pipelines. It has a built-in support for shipping logs to Axiom through the [`axiom` sink](https://vector.dev/docs/reference/configuration/sinks/axiom/).
## Installation [#installation]
Follow the [quickstart guide in the Vector documentation](https://vector.dev/docs/setup/quickstart/) to install Vector, and to configure sources and sinks.
If you use Vector version v0.41.1 (released on September 11, 2024) or earlier, use the `@timestamp` field instead of `_time` to specify the timestamp of the events. For more information, see [Timestamp in legacy Vector versions](#timestamp-in-legacy-vector-versions).
If you upgrade from Vector version v0.41.1 or earlier to a newer version, update your configuration. For more information, see [Upgrade from legacy Vector version](#upgrade-from-legacy-vector-version).
## Configuration [#configuration]
Send data to Axiom with Vector using the [`file` method](https://vector.dev/docs/reference/configuration/sources/file/) and the [`axiom` sink](https://vector.dev/docs/reference/configuration/sinks/axiom/).
The example below configures Vector to read and collect logs from files and send them to Axiom.
1. Create a vector configuration file `vector.toml` with the following content:
```toml
[sources.VECTOR_SOURCE_ID]
type = "file"
include = ["PATH_TO_LOGS"]
[sinks.SINK_ID]
type = "axiom"
inputs = ["VECTOR_SOURCE_ID"]
token = "API_TOKEN"
dataset = "DATASET_NAME"
region = "AXIOM_DOMAIN"
```
Replace `VECTOR_SOURCE_ID` with the Vector source ID.
Replace `PATH_TO_LOGS` with the path to the log files. For example, `/var/log/**/*.log`.
Replace `SINK_ID` with the sink ID.
2. Run Vector to send logs to Axiom.
### Example with data transformation [#example-with-data-transformation]
The example below deletes a field before sending the data to Axiom:
```toml
[sources.VECTOR_SOURCE_ID]
type = "file"
include = ["PATH_TO_LOGS"]
[transforms.filter_json_fields]
type = "remap"
inputs = ["VECTOR_SOURCE_ID"]
source = '''
. = del(.FIELD_TO_REMOVE)
'''
[sinks.SINK_ID]
type = "axiom"
inputs = ["filter_json_fields"]
token = "API_TOKEN"
dataset = "DATASET_NAME"
region = "AXIOM_DOMAIN"
```
Replace `VECTOR_SOURCE_ID` with the Vector source ID.
Replace `PATH_TO_LOGS` with the path to the log files. For example, `/var/log/**/*.log`.
Replace `FIELD_TO_REMOVE` with the field you want to remove.
Replace `SINK_ID` with the sink ID.
Any changes to Vector’s `file` method can make the code example above outdated. If this happens, please refer to the [official Vector documentation on the `file` method](https://vector.dev/docs/reference/configuration/sources/file/), and we kindly ask you to inform us of the issue using the feedback tool at the bottom of this page.
## Send Kubernetes logs to Axiom [#send-kubernetes-logs-to-axiom]
Send Kubernetes logs to Axiom using the Kubernetes source.
```toml
[sources.my_source_id]
type = "kubernetes_logs"
auto_partial_merge = true
ignore_older_secs = 600
read_from = "beginning"
self_node_name = "${VECTOR_SELF_NODE_NAME}"
exclude_paths_glob_patterns = [ "**/exclude/**" ]
extra_field_selector = "metadata.name!=pod-name-to-exclude"
extra_label_selector = "my_custom_label!=my_value"
extra_namespace_label_selector = "my_custom_label!=my_value"
max_read_bytes = 2_048
max_line_bytes = 32_768
fingerprint_lines = 1
glob_minimum_cooldown_ms = 60_000
delay_deletion_ms = 60_000
data_dir = "/var/lib/vector"
timezone = "local"
[sinks.axiom]
type = "axiom"
inputs = ["my_source_id"]
token = "API_TOKEN"
dataset = "DATASET_NAME"
region = "AXIOM_DOMAIN"
```
## Send Docker logs to Axiom [#send-docker-logs-to-axiom]
To send Docker logs using the Axiom sink, you need to create a configuration file, for example, `vector.toml`, with the following content:
```toml
# Define the Docker logs source
[sources.docker_logs]
type = "docker_logs"
docker_host = "unix:///var/run/docker.sock"
# Define the Axiom sink
[sinks.axiom]
type = "axiom"
inputs = ["docker_logs"]
dataset = "DATASET_NAME"
token = "API_TOKEN"
region = "AXIOM_DOMAIN"
```
Run Vector: Start Vector with the configuration file you just created:
```bash
vector --config /path/to/vector.toml
```
Vector collects logs from Docker and forward them to Axiom using the Axiom sink. You can view and analyze your logs in your dataset.
## Send AWS S3 logs to Axiom [#send-aws-s3-logs-to-axiom]
To send AWS S3 logs using the Axiom sink, create a configuration file, for example, `vector.toml`, with the following content:
```toml
[sources.my_s3_source]
type = "aws_s3"
bucket = "my-bucket" # replace with your bucket name
region = "us-west-2" # replace with the AWS region of your bucket
[sinks.axiom]
type = "axiom"
inputs = ["my_s3_source"]
dataset = "DATASET_NAME"
token = "API_TOKEN"
region = "AXIOM_DOMAIN"
```
Finally, run Vector with the configuration file using `vector --config ./vector.toml`. This starts Vector and begins reading logs from the specified S3 bucket and sending them to the specified Axiom dataset.
## Send Kafka logs to Axiom [#send-kafka-logs-to-axiom]
To send Kafka logs using the Axiom sink, you need to create a configuration file, for example, `vector.toml`, with the following code:
```toml
[sources.my_kafka_source]
type = "kafka" # must be: kafka
bootstrap_servers = "10.14.22.123:9092" # your Kafka bootstrap servers
group_id = "my_group_id" # your Kafka consumer group ID
topics = ["my_topic"] # the Kafka topics to consume from
auto_offset_reset = "earliest" # start reading from the beginning
[sinks.axiom]
type = "axiom"
inputs = ["my_kafka_source"] # connect the Axiom sink to your Kafka source
dataset = "DATASET_NAME" # replace with the name of your Axiom dataset
token = "API_TOKEN" # replace with your Axiom API token
region = "AXIOM_DOMAIN"
```
Finally, you can start Vector with your configuration file: `vector --config /path/to/your/vector.toml`
## Send NGINX metrics to Axiom [#send-nginx-metrics-to-axiom]
To send NGINX metrics using Vector to the Axiom sink, first enable NGINX to emit metrics, then use Vector to capture and forward those metrics. Here is a step-by-step guide:
### Step 1: Enable NGINX Metrics [#step-1-enable-nginx-metrics]
Configure NGINX to expose metrics. This typically involves enabling the `ngx_http_stub_status_module` module in your NGINX configuration.
1. Open your NGINX configuration file (often located at `/etc/nginx/nginx.conf`) and in your `server` block, add:
```bash
location /metrics {
stub_status;
allow 127.0.0.1; # only allow requests from localhost
deny all; # deny all other hosts
}
```
2. Restart or reload NGINX to apply the changes:
```bash
sudo systemctl restart nginx
```
This exposes basic NGINX metrics at the `/metrics` endpoint on your server.
### Step 2: Configure Vector [#step-2-configure-vector]
Configure Vector to scrape the NGINX metrics and send them to Axiom. Create a new configuration file (`vector.toml`), and add the following:
```toml
[sources.nginx_metrics]
type = "nginx_metrics" # must be: nginx_metrics
endpoints = ["http://localhost/metrics"] # the endpoint where NGINX metrics are exposed
[sinks.axiom]
type = "axiom" # must be: axiom
inputs = ["nginx_metrics"] # use the metrics from the NGINX source
dataset = "DATASET_NAME" # replace with the name of your Axiom dataset
token = "API_TOKEN" # replace with your Axiom API token
region = "AXIOM_DOMAIN"
```
Finally, you can start Vector with your configuration file: `vector --config /path/to/your/vector.toml`
## Send Syslog logs to Axiom [#send-syslog-logs-to-axiom]
To send Syslog logs using the Axiom sink, you need to create a configuration file, for example, `vector.toml`, with the following code:
```toml
[sources.my_source_id]
type="syslog"
address="0.0.0.0:6514"
max_length=102_400
mode="tcp"
[sinks.axiom]
type="axiom"
inputs = [ "my_source_id" ] # required
dataset="DATASET_NAME" # replace with the name of your Axiom dataset
token="API_TOKEN" # replace with your Axiom API token
region = "AXIOM_DOMAIN"
```
## Send Prometheus metrics to Axiom [#send-prometheus-metrics-to-axiom]
To send Prometheus scrape metrics using the Axiom sink, you need to create a configuration file, for example, `vector.toml`, with the following code:
```toml
# Define the Prometheus source that scrapes metrics
[sources.my_prometheus_source]
type = "prometheus_scrape" # scrape metrics from a Prometheus endpoint
endpoints = ["http://localhost:9090/metrics"] # replace with your Prometheus endpoint
# Define Axiom sink where logs will be sent
[sinks.axiom]
type = "axiom" # Axiom type
inputs = ["my_prometheus_source"] # connect the Axiom sink to your Prometheus source
dataset = "DATASET_NAME" # replace with the name of your Axiom dataset
token = "API_TOKEN" # replace with your Axiom API token
region = "AXIOM_DOMAIN"
```
Check out the [advanced configuration on Batch, Buffer configuration, and Encoding on Vector Documentation](https://vector.dev/docs/reference/configuration/sinks/axiom/)
## Timestamp in legacy Vector versions [#timestamp-in-legacy-vector-versions]
If you use Vector version v0.41.1 (released on September 11, 2024) or earlier, use the `@timestamp` field instead of `_time` to specify the timestamp in the event data you send to Axiom. For example: `{"@timestamp":"2022-04-14T21:30:30.658Z..."}`. For more information, see [Requirements of the timestamp field](/reference/limits#requirements-of-the-timestamp-field). In the case of Vector version v0.41.1 or earlier, the requirements explained on the page apply to the `@timestamp` field, not to `_time`.
If you use Vector version v0.42.0 (released on October 21, 2024) or newer, use the `_time` field as usual for other collectors.
### Upgrade from legacy Vector version [#upgrade-from-legacy-vector-version]
If you upgrade from Vector version v0.41.1 or earlier to a newer version, change all references from the `timestamp` field to the `_time` field and remap the logic.
Example `vrl` file:
```text example.vrl
# Set time explicitly rather than allowing Axiom to default to the current time
. = set!(value: ., path: ["_time"], data: .timestamp)
# Remove the original value as it’s effectively a duplicate
del(.timestamp)
```
Example Vector configuration file:
```toml
# ...
[transforms.migrate]
type = "remap"
inputs = [ "k8s"]
file= 'example.vrl' # See above
[sinks.debug]
type = "axiom"
inputs = [ "migrate" ]
dataset = "DATASET_NAME" # No change
token = "API_TOKEN" # No change
region = "AXIOM_DOMAIN"
[sinks.debug.encoding]
codec = "json"
```
### Set compression algorithm [#set-compression-algorithm]
Upgrading to Vector version v0.42.0 or newer automatically enables the `zstd` compression algorithm by default.
To set another compression algorithm, use the example below:
```toml
# ...
[transforms.migrate]
type = "remap"
inputs = [ "k8s"]
file= 'example.vrl' # See above
[sinks.debug]
type = "axiom"
compression = "gzip" # Set the compression algorithm
inputs = [ "migrate" ]
dataset = "DATASET_NAME" # No change
token = "API_TOKEN" # No change
region = "AXIOM_DOMAIN"
[sinks.debug.encoding]
codec = "json"
```
---
# LLM observability
Source: https://axiom.co/docs/use-cases/llm-observability
Axiom provides first-class observability for generative AI applications. Instrument your app using OpenTelemetry and Axiom automatically provisions a GenAI dashboard and waterfall trace view for every dataset containing AI telemetry.
## Instrument your app [#instrument-your-app]
## Visualize traces in Console [#visualize-traces-in-console]
Visualizing and making sense of this telemetry data is a core part of the Axiom Console experience:
* A dedicated **AI traces waterfall view** visualizes single and multi-step LLM workflows, with clear input/output inspection at each stage.
* A pre-built **GenAI OTel dashboard** automatically appears for any dataset receiving AI telemetry. It features elements for tracking cost per invocation, time-to-first-token, call counts by model, and error rates.
### Access AI traces waterfall view [#access-ai-traces-waterfall-view]
1. Click the Query tab.
2. Create an APL query about your GenAI dataset. For example:
```kusto
['otel-demo-genai']
| where ['attributes.gen_ai.operation.name'] == "chat"
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-genai'%5D%20%7C%20where%20%5B'attributes.gen_ai.operation.name'%5D%20%3D%3D%20'chat'%22%7D)
3. In the list of trace IDs, click the trace you want to explore.
4. Explore how spans within the trace are related to each other in the waterfall view. To only display AI spans, click **AI spans** in the top left.
### Access GenAI dashboard [#access-genai-dashboard]
Axiom automatically creates the GenAI dashboard if the field `attributes.gen_ai.operation.name` is present in your data.
To access the GenAI dashboard:
1. Click the Dashboards tab.
2. Click the dashboard **Generative AI Overview (DATASET\_NAME)** where `DATASET_NAME` is the name of your GenAI dataset.
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/dashboards/genai.otel-demo-genai)
The GenAI dashboard provides you with important insights about your GenAI app such as:
* Vitals about requests, broken down by operation, capability, and step.
* Token usage and cost analysis
* Error analysis
* Comparison of performance and reliability of different AI models
## What’s next? [#whats-next]
* Use [GenAI APL functions](/apl/scalar-functions/genai-functions) to query and analyze your LLM data.
* See [GenAI attributes](/use-cases/llm-observability/gen-ai-attributes) for the full list of OpenTelemetry attributes Axiom recognizes.
---
# OCSF security data in Axiom
Source: https://axiom.co/docs/use-cases/ocsf
The [Open Cybersecurity Schema Framework](https://schema.ocsf.io) (OCSF) is an open standard for security events. Firewalls, EDR tools, identity providers, and cloud audit logs map their native formats onto a shared set of event classes such as Network Activity, Authentication, and Detection Finding. Each event names its class in `class_uid`, and fields like `src_endpoint.ip` or `user.name` mean the same thing whichever product produced them.
Axiom stores OCSF events in a dataset that follows the Axiom OCSF schema, a layout for OCSF 1.9.0 data. Every documented OCSF attribute up to a fixed depth becomes a typed Axiom column, and everything else is kept, not dropped, in a single `unmapped` map field. You query the result with APL in Axiom, or with SPL from Splunk through the Axiom Portal for Splunk and the Axiom for Splunk app.
Axiom highlights OCSF events by severity. For supported fields and levels, see [Log level detection](/reference/limits#supported-schemas).
## How OCSF data flows through Axiom [#how-ocsf-data-flows-through-axiom]
1. **Produce OCSF.** You already produce OCSF events, for example with Cribl’s OCSF mapping packs or a vendor’s native OCSF export that reaches Cribl Stream.
2. **Conform and send.** The OCSF for Axiom Cribl pack reshapes each event to the Axiom OCSF schema and sends it to Axiom’s ingest API. For more information, see [Send OCSF data to Axiom](/use-cases/ocsf/send-data).
3. **Store.** One dataset holds every OCSF class. You prepare it once so that the map fields the schema relies on are registered before data arrives.
4. **Query.** Query the dataset with APL. For more information, see [Query OCSF data](/use-cases/ocsf/query). Splunk users search the same dataset with SPL, or as CIM data for data models and Enterprise Security. For more information, see [Search OCSF data from Splunk](/splunk/portal/ocsf) and [Search OCSF data as Splunk CIM](/splunk/portal/ocsf-cim).
## The Axiom OCSF schema [#the-axiom-ocsf-schema]
The Axiom OCSF schema defines how OCSF 1.9.0 data is stored in Axiom. It fixes which OCSF attributes become columns, the Axiom type of each column, and where everything else goes. The OCSF for Axiom Cribl pack shapes events to it, and the Axiom Portal for Splunk reads data in that shape.
The full OCSF object graph nests recursively, so flattening every possible path isn’t practical: the full closure of OCSF 1.9.0 runs to over 100,000 paths. Instead, every OCSF attribute lands in exactly one of three places:
| Where | What goes there | How you query it |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| **Promoted columns** | Every class attribute, the immediate scalar attributes of every object attribute (for example, `src_endpoint.ip` and `traffic.bytes`), and a few deeper objects whose attributes OCSF requires or that readers commonly need: `actor.user`, `actor.process`, `metadata.product`, `http_request.url`, `process.parent_process`, and `process.file`. Across all classes, the schema defines 1,636 columns, including the map fields in the next row. | As ordinary typed columns, for example `['src_endpoint.ip']` |
| **Map fields** | Six arrays of objects kept whole so that their elements stay paired: `observables`, `vulnerabilities`, `answers`, `attacks`, `file.hashes`, and `process.file.hashes`. Also 16 OCSF attributes whose type is a free-form JSON object, such as `resource.data`. | With index notation, for example `['attacks'][0]['technique']['uid']` |
| **`unmapped`** | Everything else: deeper subtrees, other arrays of objects, vendor extensions, and attributes from newer or older OCSF versions. The original nesting is preserved. | With index notation, for example `['unmapped']['device']['os']['name']` |
Events are sparse. A dataset’s columns are the union of the classes you send, and each event fills only the columns of its own class. Axiom adds a column when an event first populates it, so a dataset contains only the columns your producers actually use, far fewer than 1,636. Check the number of fields your plan allows in [Limits](/reference/limits).
The schema follows three reading rules:
* `class_uid` is the discriminator. Filter and branch on it.
* Enumerations are ID-first. Trust the `*_id` integers, such as `status_id`, rather than their display-string siblings, such as `status`, which vary between vendors.
* `time` is the event time in epoch milliseconds, and `_time` is set from it.
## What happens to one event [#what-happens-to-one-event]
The diagram below follows a Detection Finding from the OCSF for Axiom pack’s synthetic sample data as it’s conformed:
* `finding_info.title` and `device.hostname` are immediate scalars of class attributes, so they become columns.
* `observables` and `attacks` are promoted arrays of objects. Each is stored whole in its own map field, so a technique ID stays next to its tactic.
* `finding_info.analytic` is an object nested inside an object, and `evidences` is an array of objects that isn’t promoted. Both move under `unmapped`.
* `raw_data` holds a full copy of the original event, and `_raw`, `host`, `source`, `sourcetype`, `index`, and `cribl_pipe` are Splunk and Cribl transport fields. The Cribl pack removes all of them. You can choose to keep `raw_data`, in which case it’s stored under `unmapped`.
Below is a Palo Alto Networks traffic event, class `4001`, before and after the OCSF for Axiom pack. The values are from the pack’s synthetic sample data and its expected test output, trimmed for readability.
```json
{
"_raw": ",,007200001056,TRAFFIC,end,1,2026/08/17 12:53:20,10.14.6.57,203.0.113.9,…",
"_time": 1787000000,
"host": "fw01.example.com",
"sourcetype": "pan:traffic",
"source": "pan:syslog",
"index": "pan_logs",
"cribl_pipe": "Palo-Alto-Networks_traffic-threat_OCSF-4001",
"class_uid": 4001,
"class_name": "Network Activity",
"activity_name": "Closed",
"status_id": 1,
"time": 1787000000123456,
"raw_data": ",,007200001056,TRAFFIC,end,1,2026/08/17 12:53:20,10.14.6.57,203.0.113.9,…",
"metadata": {
"version": "1.0.0-rc.2",
"product": {
"name": "Firewall",
"vendor_name": "Palo Alto Networks",
"feature": { "name": "TRAFFIC" }
}
},
"src_endpoint": { "ip": "10.14.6.57", "port": 58102 },
"dst_endpoint": { "ip": "203.0.113.9", "port": 443, "svc_name": "allow-web" },
"connection_info": { "direction_id": 2, "protocol_name": "TCP" },
"traffic": { "bytes": 1520, "bytes_in": 560, "bytes_out": 960 }
}
```
```json
{
"_time": "2026-08-17T20:53:20.123Z",
"class_uid": 4001,
"class_name": "Network Activity",
"activity_name": "Closed",
"status_id": 1,
"time": 1787000000123,
"metadata": {
"version": "1.0.0-rc.2",
"product": {
"name": "Firewall",
"vendor_name": "Palo Alto Networks"
}
},
"src_endpoint": { "ip": "10.14.6.57", "port": 58102 },
"dst_endpoint": { "ip": "203.0.113.9", "port": 443, "svc_name": "allow-web" },
"connection_info": { "direction_id": 2, "protocol_name": "TCP" },
"traffic": { "bytes": 1520, "bytes_in": 560, "bytes_out": 960 },
"unmapped": {
"metadata": { "product": { "feature": { "name": "TRAFFIC" } } }
}
}
```
| Change | Before | After |
| ----------------- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Event time | `time` in microseconds: `1787000000123456` | `time` in milliseconds, as OCSF requires: `1787000000123`. `_time` is set from it, so Axiom stores the event at its real time with millisecond precision. |
| Duplicate payload | `raw_data` repeats the whole original log line | Dropped, which roughly halves the event size |
| Transport fields | `_raw`, `host`, `sourcetype`, `source`, `index`, `cribl_pipe` | Dropped |
| Deep attribute | `metadata.product.feature.name` | Moved to `['unmapped']['metadata']['product']['feature']['name']` |
| Everything else | Nested JSON | Unchanged. At ingest, Axiom flattens the nested objects into dotted columns such as `src_endpoint.ip` and `traffic.bytes`, and keeps `unmapped` as one map field |
## Use one dataset [#use-one-dataset]
Send all OCSF classes to one dataset, for example `ocsf`. The most common security workflow is an entity investigation, such as everything a user or host touched, and it spans authentication, network, and endpoint classes. With one dataset, that’s one query. Readers branch on `class_uid`, not on dataset names.
Split OCSF data into more datasets only when you need different retention, for example high-volume network flow and DNS events on short retention in `ocsf_flow`, and findings on long retention in `ocsf`. Each dataset is prepared the same way and follows the same schema.
## What’s next [#whats-next]
* [Send OCSF data to Axiom](/use-cases/ocsf/send-data)
* [Query OCSF data](/use-cases/ocsf/query)
* [Search OCSF data from Splunk](/splunk/portal/ocsf)
---
# Query histogram and summary metrics
Source: https://axiom.co/docs/mpl/histograms-summaries
Unlike other OpenTelemetry (OTel) metric types, a histogram or summary metric doesn't hold a single measurement. Each one carries several components that mean different things, such as an observation count alongside a distribution. Query these metric types with a function that's aware of that shape, or by selecting the component you want.
## Histogram metrics [#histogram-metrics]
Query histogram metrics with `bucket` and an `interpolate_` function: `interpolate_cumulative_histogram` for cumulative temporality, `interpolate_delta_histogram` for delta temporality. Use them when you want the observation count, the average, or an estimated quantile such as the 90th percentile. For the syntax, see [Bucket](/mpl/introduction#bucket). For examples, see [Sample MPL queries](/mpl/sample-queries#histogram).
Unless you want to sketch which series a metric contains, don't run a plain `align` or `group` over a histogram metric. Its components mean different things, so aggregating them together produces a meaningless result. Use a `bucket` function instead.
## Summary metrics [#summary-metrics]
The [OTel data model](https://opentelemetry.io/docs/specs/otel/metrics/data-model/#summary-legacy) marks summary as a legacy type. It isn't recommended for new applications and exists for compatibility with other formats. If you can choose the instrumentation, a histogram is the better option.
MPL has no `interpolate_` function for summaries because the producer already computed the quantiles. Instead, select the component you want with the reserved `axiom.summary` and `axiom.quantile` tags, and derive anything else with [compute](/mpl/introduction#compute).
### Count and sum [#count-and-sum]
Filter to the component you want.
```mpl
`my-metrics`:`service.request.duration`
| where `service.name` == "checkout"
| where `axiom.summary` == "count"
| align to 5m using sum
```
```mpl
`my-dataset`:`service.request.duration`
| where `service.name` == "checkout"
| where `axiom.summary` == "sum"
| align to 5m using sum
```
### Average [#average]
Divide the `sum` component by the `count` component with `compute`.
```mpl
(
`my-dataset`:`service.request.duration`
| where `service.name` == "checkout"
| where `axiom.summary` == "sum"
| group using sum,
`my-dataset`:`service.request.duration`
| where `service.name` == "checkout"
| where `axiom.summary` == "count"
| group using sum
)
| compute average using /
```
### Minimum and maximum [#minimum-and-maximum]
If the producer emits the `0.0` and `1.0` quantiles, use them as the minimum and the maximum.
```mpl
// Minimum
`my-dataset`:`service.request.duration`
| where `service.name` == "checkout"
| where `axiom.summary` == "bucket" and `axiom.quantile` == 0.0
```
```mpl
// Maximum
`my-dataset`:`service.request.duration`
| where `service.name` == "checkout"
| where `axiom.summary` == "bucket" and `axiom.quantile` == 1.0
```
### Quantiles [#quantiles]
A summary only contains the quantiles the producer computed. You can select one of them, but you can't derive a quantile that isn't there.
```mpl
// Median, if the producer emits the 0.5 quantile
`my-dataset`:`service.request.duration`
| where `service.name` == "checkout"
| where `axiom.summary` == "bucket" and `axiom.quantile` == 0.5
```
As with histograms, avoid a plain `align` or `group` over a summary metric unless you want to sketch which series it contains.
---
# Introduction to MPL
Source: https://axiom.co/docs/mpl/introduction
MPL is a metric-focused query language that combines the simplicity of APL with the expressive power of PromQL. It enables effective querying, transformation, and aggregation of metric data, supporting diverse observability use cases.
If you use PromQL, your existing expressions can be translated to MPL for quick onboarding and greater flexibility. For more information, see [Migrate PromQL queries to Axiom](/mpl/migrate-metrics).
Support for MPL (Metrics Processing Language) is currently in public preview. For more information, see [Feature states](/platform-overview/roadmap#feature-states).
## Limitations [#limitations]
The current implementation of MPL comes with the following limitations:
* You can only query one dataset in a query.
## Concepts [#concepts]
* **Dataset:** A group of related metrics.
* **Metric:** Two-dimensional time series data with a metric name and a set of tags.
* **Tag:** Key-value pair identifying a series.
* **Series:** A unique combination of a metric and tag set.
## Query structure [#query-structure]
A typical MPL query contains the following:
1. **Source**: Defines dataset, metric, and optional time range
2. **Filter**: Applies conditions to series via tags
3. **Transformation** can be the following:
* **Map:** Maps the data to a new value.
* **Align:** Aggregates the data over time to align to a given time interval.
* **Group:** Aggregates the data over tag values.
* **Bucket:** A two-dimensional transformation that aggregates along both the time and tag dimensions.
**Example:**
```mpl
`otel-demo-metrics`:`go.memory.used`
| where `k8s.deployment.name` == "checkout"
| align to 5m using avg
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%60otel-demo-metrics%60%3A%60go.memory.used%60%20%7C%20where%20%60k8s.deployment.name%60%20%3D%3D%20%5C%22checkout%5C%22%20%7C%20align%20to%205m%20using%20avg%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
This example queries the `otel-demo-metrics` dataset's `go.memory.used` metric one hour before the current time. It filters results to the `frontend` service and aggregates values over 5-minute time windows into their average.
## Elements of queries [#elements-of-queries]
The following explains each element of an MPL query.
To learn more about the language features of MPL, see [Language features](#language-features).
### Directives [#directives]
Use `set` directives at the start of a query to control query behavior and visualization settings.
Directives must appear before the query body.
**Syntax:**
```mpl
set = ;
```
#### Supported directives [#supported-directives]
The following directives are currently supported in Axiom's MPL implementation:
| Directive | Description |
| ------------- | ----------------------------------------------------------- |
| `custom_unit` | Sets the unit used when visualizing query results in Axiom. |
Use string values for `custom_unit`. Set it to `"1"` to render values as unitless numbers.
**Examples:**
```mpl
set custom_unit = "ms";
`otel-demo-metrics`:`http.server.request.duration`
| align to 5m using avg
```
```mpl
set custom_unit = "1";
`otel-demo-metrics`:`http.server.request.duration`
| align to 5m using avg
```
### Source [#source]
Specify the dataset, the metric, and optional time bounds.
**Syntax:**
```mpl
:[][ as ]
```
* **dataset**: Name of the dataset.
* **metric**: Name of the metric.
* **time range**: Optional: The time range of the query. For more information, see [Time ranges](#time-ranges).
* **alias**: Optional: Renames the metric for later use.
**Examples:**
```mpl
`otel-demo-metrics`:`go.memory.used`[1h..]
`otel-demo-metrics`:`go.memory.used`[2h..5m]
`otel-demo-metrics`:`go.memory.used`[2025-03-01T13:00:00Z..+1h] as mem_usage
```
### Filter [#filter]
Use `where` to filter series based on tag values.
**Syntax:**
```mpl
| where
```
A filter expression can be one of the following:
* ` ` — a single tag filter
* ` and ` — logical AND of two expressions
* ` or ` — logical OR of two expressions
* `not ` — negation of an expression
* `()` — parentheses to control order of evaluation
Available operators for single tag filters:
* Equality: `==`, `!=`
* Comparisons: `<`, `<=`, `>`, `>=`
The value must be one of the [supported data types](#data-types).
**Examples:**
```mpl
| where environment == "production" and status_code >= 200 and status_code < 300
| where (environment == "production" or environment == "staging") and not status_code == 500
```
### Map [#map]
Use `map` to transform individual values.
Available functions:
| Function | Description |
| --------------------- | -------------------------------------------------------------------- |
| `rate` | Computes the per-second rate of change for a metric. |
| `increase` | Calculates the increase between the data point and the previous one. |
| `min(arg)` | Returns the minimum between the argument and the value. |
| `max(arg)` | Returns the maximum between the argument and the value. |
| `abs` | Returns the absolute value of each data point. |
| `fill::prev` | Fills missing values using the previous non-null value. |
| `fill::const(arg)` | Fills missing values with a constant. |
| `interpolate::linear` | Linear interpolation of missing values. |
| `+`, `-`, `*`, `/` | Performs the respective mathematical calculation on each value. |
**Examples:**
```mpl
// Calculate rate per second for the metric
| map rate
// Add 5 to each value
| map + 5
// Fill empty values with the latest value
| map fill::prev
// Fill empty values with zeros
| map fill::const(0)
```
#### filter:: functions [#filter-functions]
Use `filter::` functions to remove data points that don't match a condition. Data points that don't match are removed from the series entirely. Unlike `where`, which filters series based on tag values, `filter::` operates on the numeric values of data points within a series.
| Function | Description |
| ---------------- | ---------------------------------------------------- |
| `filter::eq(v)` | Keeps only data points equal to `v`. |
| `filter::neq(v)` | Keeps only data points not equal to `v`. |
| `filter::gt(v)` | Keeps only data points greater than `v`. |
| `filter::gte(v)` | Keeps only data points greater than or equal to `v`. |
| `filter::lt(v)` | Keeps only data points less than `v`. |
| `filter::lte(v)` | Keeps only data points less than or equal to `v`. |
**Example:**
```mpl
// Remove data points where latency exceeds 400ms
| map filter::lt(0.4)
```
#### is:: functions [#is-functions]
Use `is::` functions to test data points against a condition. Matching data points are set to `1.0` and non-matching data points are set to `0.0`. The series retains all its data points.
Use `is::` instead of `filter::` when you need to preserve the shape of the time series, for example in SLO calculations where gaps in data would produce incorrect results.
| Function | Description |
| ------------ | ---------------------------------------------------------------------------- |
| `is::eq(v)` | Sets data points equal to `v` to `1.0`, all others to `0.0`. |
| `is::neq(v)` | Sets data points not equal to `v` to `1.0`, all others to `0.0`. |
| `is::gt(v)` | Sets data points greater than `v` to `1.0`, all others to `0.0`. |
| `is::gte(v)` | Sets data points greater than or equal to `v` to `1.0`, all others to `0.0`. |
| `is::lt(v)` | Sets data points less than `v` to `1.0`, all others to `0.0`. |
| `is::lte(v)` | Sets data points less than or equal to `v` to `1.0`, all others to `0.0`. |
**Example:**
```mpl
// Set to 1.0 where latency is within SLO (below 400ms), 0.0 otherwise
| map is::lt(0.4)
```
### Align [#align]
Use `align` to aggregate over time windows. You can specify the time window and the aggregation function to apply.
If you omit `to `, `align` aggregates over the full query range and returns a single value per series.
**Syntax:**
```mpl
| align to using
| align using
```
Available aggregation functions:
| Function | Description |
| ------------ | -------------------------------------- |
| `avg` | Averages values in each interval. |
| `count` | Counts non-null values per interval. |
| `max` | Takes the maximum value per interval. |
| `min` | Takes the minimum value per interval. |
| `prom::rate` | PromQL-style rate calculation. |
| `sum` | Sums values in each interval. |
| `last` | Takes the last value in each interval. |
**Examples:**
```mpl
// Calculate the average over 5-minute time windows
| align to 5m using avg
// Count the data points in the last hour
| align to 1h using count
// Sum over the full query range
| align using sum
```
### Group [#group]
Use `group by` to combine series by tags.
**Syntax:**
```mpl
| group [by , ] using
```
If you don't specify tags, Axiom aggregates all series into one group.
Available aggregation functions:
| Function | Description |
| -------- | ------------------------------------- |
| `avg` | Averages values in each interval. |
| `sum` | Sums values in each interval. |
| `min` | Takes the minimum value per interval. |
| `max` | Takes the maximum value per interval. |
| `count` | Counts non-null values per interval. |
**Examples:**
```mpl
// Calculate the number of series
| group using count
// Sum all series into a single total
| group using sum
// Group data by the `service` and `namespace` tags using the `sum` aggregation
| group by service, namespace using sum
```
### Bucket [#bucket]
Use `bucket` to aggregate over time and tag dimensions simultaneously.
If you omit `to `, `bucket` aggregates over the full query range and returns a single value per series.
**Syntax:**
```mpl
| bucket [by ] to using
| bucket [by ] using
```
Available functions:
| Function | Description |
| ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `histogram(specs)` | Aggregates non-histogram series into buckets. `specs` is one or more quantile values between 0 and 1, or aggregation functions (`count`, `avg`, `sum`, `min`, `max`). |
| `interpolate_cumulative_histogram(mode, specs)` | Aggregates cumulative-temporality histogram series. `mode` is `rate` or `increase`. `specs` is one or more quantile values or aggregation functions. |
| `interpolate_delta_histogram(specs)` | Aggregates delta-temporality histogram series. `specs` is one or more quantile values or aggregation functions. |
`interpolate_cumulative_histogram` works on histogram metrics using cumulative temporality. `interpolate_delta_histogram` works on histogram metrics using delta temporality.
MPL has no equivalent function for summary metrics. For more information, see [Query histogram and summary metrics](/mpl/histograms-summaries).
**Examples:**
```mpl
// Bucket over the `service` and `endpoint` tags using the histogram aggregation
| bucket by service, endpoint to 5m using histogram(max)
// Compute the 50th and 99th percentiles of request duration for histogram data stored using cumulative temporality
| bucket by service to 1m using interpolate_cumulative_histogram(rate, 0.50, 0.99)
// Compute the 50th and 99th percentiles of request duration for histogram data stored using delta temporality
| bucket by service to 1m using interpolate_delta_histogram(0.50, 0.99)
```
### Extend [#extend]
Use `extend` to add new tags to every series in the query result. `extend` supports `${}` interpolation to reference existing tag values or parameters.
`extend` can only be applied after aggregations (after `align`, `group`, `bucket`, and `map`).
**Syntax:**
```mpl
| extend = [, = ...]
```
* The value must be a string, integer, float, or boolean literal.
* The tag name must be net-new: if any input series already has a tag with the same name, the query fails. To overwrite an existing tag, first drop it with `group by`, then re-add it with `extend`.
**Examples:**
```mpl
// Add a constant string tag
| extend environment = "production"
// Reference existing tag values
`my-metrics`:http_latency
| where host is string and port is int
| align to 5m using avg
| extend url = "http://${host}:${port}"
```
## Other operations [#other-operations]
### Compute [#compute]
Combine multiple metrics in one query block.
**Syntax:**
```mpl
(
,
)
| compute using
```
Available operators:
| Operator | Description |
| -------- | ------------------------------------ |
| `+` | Adds subquery results. |
| `-` | Subtracts one subquery from another. |
| `*` | Multiplies subquery results. |
| `/` | Divides one subquery by another. |
| `min` | Minimum across result series. |
| `max` | Maximum across result series. |
| `avg` | Average across result series. |
`compute` uses strict intersection semantics. It only combines series with matching tag sets, and it only emits values for timestamps present on both sides. If you want results for timestamps where only one side has a value, fill missing values using `map` functions.
```mpl
// Use 0 as the default for addition
(
| map fill::const(0),
| map fill::const(0)
)
| compute total using +
// Use 1 as the default for multiplication
(
| map fill::const(1),
| map fill::const(1)
)
| compute product using *
```
**Example:**
```mpl
// Return the average error rate over the past 5 minutes
(
`otel-demo-metrics`:`http.server.request.duration`
| where `http.response.status_code` >= 500
| map rate
| align to 5m using avg
| group using sum,
`otel-demo-metrics`:`http.server.request.duration`
| map rate
| align to 5m using avg
| group using sum
)
| compute error_rate using /
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22\(%20%60otel-demo-metrics%60%3A%60http.server.request.duration%60%20%7C%20where%20%60http.response.status_code%60%20%3E%3D%20500%20%7C%20map%20rate%20%7C%20align%20to%205m%20using%20avg%20%7C%20group%20using%20sum%2C%20%60otel-demo-metrics%60%3A%60http.server.request.duration%60%20%7C%20map%20rate%20%7C%20align%20to%205m%20using%20avg%20%7C%20group%20using%20sum%20\)%20%7C%20compute%20error_rate%20using%20%2F%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
### Offset [#offset]
Use `offset` to read a source from an earlier or later time window. This lets you compare a metric with its own values at another time, for example this hour against the same hour yesterday.
**Syntax:**
```mpl
| offset
```
* **duration**: How far to move the window. A negative duration such as `-1h` reads earlier data. A positive duration such as `+1h` or `1h` reads later data. Use the same time units as in [time ranges](#time-ranges), such as `5m`, `1h`, `1d`, or `1w`.
`offset` must come immediately after the source, before any other operation. Each source can have one `offset`.
Axiom keeps the time range of the query and shifts the window it reads data from. Axiom then moves the returned timestamps by the same amount in the opposite direction, so the results line up with the query’s time range. For example, if the query’s time range is 10:00 to 11:00:
* With `offset -1h`, Axiom reads data from 9:00 to 10:00, and the value at 10:15 in the results is the value measured at 9:15.
* With `offset +1h`, Axiom reads data from 11:00 to 12:00, and the value at 10:15 in the results is the value measured at 11:15.
In PromQL, `offset 1h` reads data from one hour earlier. In MPL, the sign matches the direction in time, so you write `offset -1h`. In MPL, `offset 1h` reads data from one hour later.
**Examples:**
```mpl
// Read memory usage from one day earlier
`otel-demo-metrics`:`go.memory.used`
| offset -1d
| where `k8s.deployment.name` == "checkout"
| align to 5m using avg
```
```mpl
// Compare the current request rate with the same time one week earlier
(
`otel-demo-metrics`:`http.server.request.duration`
| align to 5m using prom::rate
| group using sum,
`otel-demo-metrics`:`http.server.request.duration`
| offset -1w
| align to 5m using prom::rate
| group using sum
)
| compute week_over_week using /
```
To compare the results of a [compute](#compute) operation over time, add `offset` to each source inside it. You can’t apply `offset` to the result of `compute`.
## Language features [#language-features]
### Data types [#data-types]
* Strings: `"string"`
Use double quotes (`"`) to enclose the string. Don't use single quotes (`'`).
* Integers: `42`
* Floats: `3.14`
* Booleans: `true`, `false`
* Regex: `#/.*metrics.*/`
### Identifier naming rules [#identifier-naming-rules]
Identifiers represent fields, metrics, datasets, function names, and other named entities in your query.
Valid identifier names are case-sensitive and follow these rules:
* Start with an ASCII letter.
* Followed by zero or more ASCII letters, digits, or underscores (`_`).
### Quote identifiers [#quote-identifiers]
Quote an identifier in your MPL query if any of the following is true:
* The identifier name doesn't match the rules for [valid identifier names](#identifier-naming-rules).
* The identifier name is identical to one of the reserved keywords of the MPL query language. For example, `by` or `where`.
If any of the above is true, you must quote the identifier by enclosing it in backticks (`` ` ``). For example, `` `my-field` ``.
If none of the above is true, you don't need to quote the identifier in your MPL query. For example, `myfield`. In this case, quoting the identifier name is optional.
### Built-in variables [#built-in-variables]
MPL provides the following built-in variables that can be used in queries:
| Variable | Type | Description |
| ------------- | -------- | ----------------------------------------------------------------------------------------- |
| `$__interval` | duration | Provides a suitable interval size for charting, depending on the time range of the query. |
**Example:**
```mpl
`otel-demo-metrics`:`http.server.request.duration`
| align to $__interval using avg
```
### Time ranges [#time-ranges]
**Syntax:**
```mpl
[..?]
```
Define time ranges with the following:
* **Start time:** Inclusive beginning of the time range.
* **End time:** Optional, exclusive end of the time range. If you don't specify the end time, Axiom uses the current time.
Separate the start and the end times with `..`.
Time can be defined in one of the following ways:
* Relative time. The time unit can be one of the following:
* `ms` for milliseconds (will be rounded to seconds)
* `s` for seconds
* `m` for minutes
* `h` for hours
* `d` for days
* `w` for weeks
* `M` for months
* `y` for years
Examples: `-1h`, `+5m`
* Unix epoch timestamp in seconds. For example: `1723982394`
* An RFC3339 timestamp. For example: `2025-03-01T13:00:00Z`
**Examples:**
```mpl
// One hour ago until the current time
[1h..]
// One hour after a Unix timestamp
[1747077736..+1h]
// One hour before a Unix timestamp
[-1h..1747077736]
// One hour before an RFC3339 date
[-1h..2025-03-01T13:00:00Z]
```
---
# Migrate PromQL queries to Axiom
Source: https://axiom.co/docs/mpl/migrate-metrics
To migrate your PromQL queries to Metrics Processing Language (MPL), consider the following differences and examples comparing Metrics Processing Language (MPL) to PromQL.
## Differences between MPL and PromQL [#differences-between-mpl-and-promql]
While MPL and PromQL are both designed for querying metrics data, they differ in fundamental ways that impact how queries are written and interpreted. This section outlines the key differences to help you adapt PromQL workflows when migrating to Axiom.
### Richer type system [#richer-type-system]
Prometheus treats all label values as strings, which often leads users to rely heavily on regular expressions for filtering. MPL, by contrast, supports a broader and more expressive type system, including native types like numbers, booleans, and timestamps. This means you can write cleaner, type-aware queries and avoid the pitfalls of string-only comparisons.
For OpenTelemetry (OTel) data, this difference means that MPL preserves source types, enabling more accurate and efficient filtering and aggregation.
### Labels versus fields [#labels-versus-fields]
PromQL is optimized for a sparse label space and performs poorly with high-cardinality label sets. This design limits how many dimensions can be encoded as labels.
MPL doesn't impose the same restrictions. It encourages richer, high-cardinality data ingestion, allowing you to store and query more attributes per event without performance degradation.
Additionally, PromQL users often use enrichment queries to simulate dimensional joins and join label values from one series into another. MPL doesn't currently support this pattern because it diverges from OpenTelemetry semantics, which emphasize event-based modeling over metric enrichment.
### Histogram behavior [#histogram-behavior]
Histogram support differs significantly. In PromQL, histogram queries typically yield one time series per bucket or a single quantile series depending on the function.
MPL allows histogram operations that can output multiple series in a single query, providing greater flexibility for analyzing distributions or rendering percentile summaries directly.
### Regular expression syntax [#regular-expression-syntax]
In PromQL, regular expressions are written as string literals using the `=~` operator. This requires escaping special characters using double quotes and backslashes, which can be error-prone.
MPL treats regular expressions as a first-class type. Use the `==` and `!=` operators with a regex literal prefixed by `#/`. There is no `=~` operator in MPL.
```promql PromQL
service=~"checkout|payment"
```
```mpl MPL equivalent
| where service == #/checkout|payment/
```
Regex is a native type in MPL. Denote regex using `#/` and `/` instead of quotation marks (`'` or `"`).
In regex, escape slash (`/`), but don't escape quotation marks (`'` or `"`).
### Offset direction [#offset-direction]
In PromQL, `offset` takes a positive duration and reads data from that far in the past. In MPL, the sign matches the direction in time: a negative duration reads data from the past, and a positive duration reads data from later. When you migrate a PromQL query, add a minus sign. Otherwise, `offset 1h` reads data from one hour later instead of one hour earlier.
Place `offset` immediately after the source. For more information, see [Offset](/mpl/introduction#offset).
```promql PromQL
rate(http_server_request_duration_seconds_count[5m] offset 1h)
```
```mpl MPL equivalent
`otel-demo-metrics`:`http.server.request.duration`
| offset -1h
| align to 5m using prom::rate
```
## Examples [#examples]
### Average over time [#average-over-time]
Calculate the fraction of time JVM CPU utilization stays below 80% over a 7-day window.
```promql Prometheus example
avg_over_time(
(
max(jvm_cpu_recent_utilization_ratio) < bool 0.8
)[7d:]
)
```
```mpl MPL equivalent
`otel-demo-metrics`:`jvm.cpu.recent_utilization`
| group using max
| map is::lt(0.8)
| align to 7d using avg
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%60otel-demo-metrics%60%3A%60jvm.cpu.recent_utilization%60%20%7C%20group%20using%20max%20%7C%20map%20is%3A%3Alt\(0.8\)%20%7C%20align%20to%207d%20using%20avg%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
### Multiply each value by 100 [#multiply-each-value-by-100]
Convert CPU utilization from a ratio (0–1) to a percentage (0–100).
```promql Prometheus example
process_cpu_utilization_ratio{} * 100
```
```mpl MPL equivalent
`otel-demo-metrics`:`process.cpu.utilization`
| map * 100
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%60otel-demo-metrics%60%3A%60process.cpu.utilization%60%20%7C%20map%20*%20100%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
### Calculate average error rate [#calculate-average-error-rate]
Calculate the average error rate per 5-minute windows for HTTP server requests.
```promql Prometheus example
sum(rate(http_server_request_duration_seconds_count{status_code=~"5.."}[5m]))
/
sum(rate(http_server_request_duration_seconds_count{}[5m]))
```
```mpl MPL equivalent
(
`otel-demo-metrics`:`http.server.request.duration`
| where `http.response.status_code` >= 500
| map rate
| align to 5m using avg
| group using sum,
`otel-demo-metrics`:`http.server.request.duration`
| map rate
| align to 5m using avg
| group using sum
)
| compute error_rate using /
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22\(%20%60otel-demo-metrics%60%3A%60http.server.request.duration%60%20%7C%20where%20%60http.response.status_code%60%20%3E%3D%20500%20%7C%20map%20rate%20%7C%20align%20to%205m%20using%20avg%20%7C%20group%20using%20sum%2C%20%60otel-demo-metrics%60%3A%60http.server.request.duration%60%20%7C%20map%20rate%20%7C%20align%20to%205m%20using%20avg%20%7C%20group%20using%20sum%20\)%20%7C%20compute%20error_rate%20using%20%2F%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
### Calculate rate [#calculate-rate]
Calculate the rate of HTTP requests by method, route, and status code.
```promql Prometheus example
sum by (method, route, status_code) (
rate(
http_server_request_duration_seconds_count{
status_code=~"[123].."
}[5m]
)
)
```
```mpl MPL equivalent
`otel-demo-metrics`:`http.server.request.duration`
| where `http.response.status_code` == #/[123]../
| map rate
| align to 5m using avg
| group by `http.request.method`, `http.route`, `http.response.status_code` using sum
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%60otel-demo-metrics%60%3A%60http.server.request.duration%60%20%7C%20where%20%60http.response.status_code%60%20%3D%3D%20%23%2F%5B123%5D..%2F%20%7C%20map%20rate%20%7C%20align%20to%205m%20using%20avg%20%7C%20group%20by%20%60http.request.method%60%2C%20%60http.route%60%2C%20%60http.response.status_code%60%20using%20sum%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
---
# Sample MPL queries
Source: https://axiom.co/docs/mpl/sample-queries
## Sum rate [#sum-rate]
Calculate the rate of successful HTTP requests by method and route.
```mpl
`otel-demo-metrics`:`http.server.request.duration`
| where `axiom.histogram` == "count"
| where `http.response.status_code` < 400
| align to 5m using prom::rate
| group by `http.request.method`, `http.route` using sum
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%60otel-demo-metrics%60%3A%60http.server.request.duration%60%20%7C%20where%20%60axiom.histogram%60%20%3D%3D%20%5C%22count%5C%22%20%7C%20where%20%60http.response.status_code%60%20%3C%20400%20%7C%20align%20to%205m%20using%20prom%3A%3Arate%20%7C%20group%20by%20%60http.request.method%60%2C%20%60http.route%60%20using%20sum%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
## Histogram [#histogram]
Calculate the 90th and 99th percentile HTTP request durations by service.
```mpl
`otel-demo-metrics`:`http.server.request.duration`
| where `http.response.status_code` < 400
| bucket by `service.name` to 5m using interpolate_delta_histogram(0.90, 0.99)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%60otel-demo-metrics%60%3A%60http.server.request.duration%60%20%7C%20where%20%60http.response.status_code%60%20%3C%20400%20%7C%20bucket%20by%20%60service.name%60%20to%205m%20using%20interpolate_delta_histogram\(0.90%2C%200.99\)%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
### Cumulative histogram [#cumulative-histogram]
`interpolate_cumulative_histogram` works on histogram metrics using cumulative temporality. `interpolate_delta_histogram` works on histogram metrics using delta temporality.
```mpl
`otel-demo-metrics`:`http.server.request.duration`
| where `http.response.status_code` < 400
| bucket by `http.request.method`, `http.route` to 5m using interpolate_cumulative_histogram(rate, 0.90, 0.99)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%60otel-demo-metrics%60%3A%60http.server.request.duration%60%20%7C%20where%20%60http.response.status_code%60%20%3C%20400%20%7C%20bucket%20by%20%60http.request.method%60%2C%20%60http.route%60%20to%205m%20using%20interpolate_cumulative_histogram\(rate%2C%200.90%2C%200.99\)%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
### Bucket distribution [#bucket-distribution]
Show how request durations are distributed across a histogram's buckets. Visualize the result with a [heatmap](/dashboard-elements/heatmap) dashboard element.
```mpl
`otel-demo-metrics`:`http.server.request.duration`
| where `axiom.histogram` == "bucket"
| align to 5m using prom::rate
| group by `axiom.le` using sum
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%60otel-demo-metrics%60%3A%60http.server.request.duration%60%20%7C%20where%20%60axiom.histogram%60%20%3D%3D%20%5C%22bucket%5C%22%20%7C%20align%20to%205m%20using%20prom%3A%3Arate%20%7C%20group%20by%20%60axiom.le%60%20using%20sum%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
## Compute [#compute]
### Compute error rate [#compute-error-rate]
Calculate the fraction of HTTP requests returning 5xx errors.
```mpl
(
`otel-demo-metrics`:`http.server.request.duration`
| where `http.response.status_code` >= 500
| map rate
| align to 5m using avg
| group using sum,
`otel-demo-metrics`:`http.server.request.duration`
| map rate
| align to 5m using avg
| group using sum
)
| compute error_rate using /
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22\(%20%60otel-demo-metrics%60%3A%60http.server.request.duration%60%20%7C%20where%20%60http.response.status_code%60%20%3E%3D%20500%20%7C%20map%20rate%20%7C%20align%20to%205m%20using%20avg%20%7C%20group%20using%20sum%2C%20%60otel-demo-metrics%60%3A%60http.server.request.duration%60%20%7C%20map%20rate%20%7C%20align%20to%205m%20using%20avg%20%7C%20group%20using%20sum%20\)%20%7C%20compute%20error_rate%20using%20%2F%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
### Compare with the previous week [#compare-with-the-previous-week]
Calculate the ratio between the current request rate and the request rate at the same time one week earlier. A value of `1.2` means 20% more requests than the week before.
```mpl
(
`otel-demo-metrics`:`http.server.request.duration`
| align to 5m using prom::rate
| group using sum,
`otel-demo-metrics`:`http.server.request.duration`
| offset -1w
| align to 5m using prom::rate
| group using sum
)
| compute week_over_week using /
```
## Service Level Objectives (SLO) [#service-level-objectives-slo]
### SLO compliance over time [#slo-compliance-over-time]
Calculate the fraction of time JVM CPU utilization stays below 80% over a 7-day window.
```mpl
`otel-demo-metrics`:`jvm.cpu.recent_utilization`
| group using max
| map is::lt(0.8)
| align to 7d using avg
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%60otel-demo-metrics%60%3A%60jvm.cpu.recent_utilization%60%20%7C%20group%20using%20max%20%7C%20map%20is%3A%3Alt\(0.8\)%20%7C%20align%20to%207d%20using%20avg%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
### SLO histogram [#slo-histogram]
Calculate the fraction of requests completing within the `400ms` latency SLO target, measured weekly.
```mpl
`otel-demo-metrics`:`http.server.request.duration`
| bucket to 5m using interpolate_cumulative_histogram(rate, 0.99)
| map is::lt(0.4)
| align to 7d using avg
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%60otel-demo-metrics%60%3A%60http.server.request.duration%60%20%7C%20bucket%20to%205m%20using%20interpolate_cumulative_histogram\(rate%2C%200.99\)%20%7C%20map%20is%3A%3Alt\(0.4\)%20%7C%20align%20to%207d%20using%20avg%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
---
# All features of Axiom Processing Language (APL)
Source: https://axiom.co/docs/apl/apl-features
| Category | Feature | Description |
| :---------------------- | :-------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Aggregation function | [arg\_max](/apl/aggregation-function/arg-max) | Returns the row where an expression evaluates to the maximum value. |
| Aggregation function | [arg\_min](/apl/aggregation-function/arg-min) | Returns the row where an expression evaluates to the minimum value. |
| Aggregation function | [avg](/apl/aggregation-function/avg) | Returns an average value across the group. |
| Aggregation function | [avgif](/apl/aggregation-function/avgif) | Calculates the average value of an expression in records for which the predicate evaluates to true. |
| Aggregation function | [count](/apl/aggregation-function/count) | Returns a count of the group without/with a predicate. |
| Aggregation function | [countif](/apl/aggregation-function/countif) | Returns a count of rows for which the predicate evaluates to true. |
| Aggregation function | [dcount](/apl/aggregation-function/dcount) | Returns an estimate for the number of distinct values that are taken by a scalar expression in the summary group. |
| Aggregation function | [dcountif](/apl/aggregation-function/dcountif) | Returns an estimate of the number of distinct values of an expression of rows for which the predicate evaluates to true. |
| Aggregation function | [histogram](/apl/aggregation-function/histogram) | Returns a timeseries heatmap chart across the group. |
| Aggregation function | [histogramif](/apl/aggregation-function/histogramif) | Creates a histogram for rows where a condition evaluates to true. |
| Aggregation function | [make\_list\_if](/apl/aggregation-function/make-list-if) | Creates a dynamic JSON object (array) of an expression values in the group for which the predicate evaluates to true. |
| Aggregation function | [make\_list](/apl/aggregation-function/make-list) | Creates a dynamic JSON object (array) of all the values of an expression in the group. |
| Aggregation function | [make\_set\_if](/apl/aggregation-function/make-set-if) | Creates a dynamic JSON object (array) of the set of distinct values that an expression takes in records for which the predicate evaluates to true. |
| Aggregation function | [make\_set](/apl/aggregation-function/make-set) | Creates a dynamic JSON array of the set of distinct values that an expression takes in the group. |
| Aggregation function | [max](/apl/aggregation-function/max) | Returns the maximum value across the group. |
| Aggregation function | [maxif](/apl/aggregation-function/maxif) | Calculates the maximum value of an expression in records for which the predicate evaluates to true. |
| Aggregation function | [min](/apl/aggregation-function/min) | Returns the minimum value across the group. |
| Aggregation function | [minif](/apl/aggregation-function/minif) | Returns the minimum of an expression in records for which the predicate evaluates to true. |
| Aggregation function | [percentile](/apl/aggregation-function/percentile) | Calculates the requested percentiles of the group and produces a timeseries chart. |
| Aggregation function | [percentileif](/apl/aggregation-function/percentileif) | Calculates the requested percentiles of the field for the rows where the predicate evaluates to true. |
| Aggregation function | [percentiles\_array](/apl/aggregation-function/percentiles-array) | Returns an array of numbers where each element is the value at the corresponding percentile. |
| Aggregation function | [percentiles\_arrayif](/apl/aggregation-function/percentiles-arrayif) | Returns an array of percentile values for the records that satisfy the condition. |
| Aggregation function | [rate](/apl/aggregation-function/rate) | Calculates the rate of values in a group per second. |
| Aggregation function | [spotlight](/apl/aggregation-function/spotlight) | Compares a selected set of events against a baseline and surface the most significant differences. |
| Aggregation function | [stdev](/apl/aggregation-function/stdev) | Calculates the standard deviation of an expression across the group. |
| Aggregation function | [stdevif](/apl/aggregation-function/stdevif) | Calculates the standard deviation of an expression in records for which the predicate evaluates to true. |
| Aggregation function | [sum](/apl/aggregation-function/sum) | Calculates the sum of an expression across the group. |
| Aggregation function | [sumif](/apl/aggregation-function/sumif) | Calculates the sum of an expression in records for which the predicate evaluates to true. |
| Aggregation function | [topk](/apl/aggregation-function/topk) | Calculates the top values of an expression across the group in a dataset. |
| Aggregation function | [topkif](/apl/aggregation-function/topkif) | Calculates the top values of an expression in records for which the predicate evaluates to true. |
| Aggregation function | [variance](/apl/aggregation-function/variance) | Calculates the variance of an expression across the group. |
| Aggregation function | [varianceif](/apl/aggregation-function/varianceif) | Calculates the variance of an expression in records for which the predicate evaluates to true. |
| Aggregation function | [phrases](/apl/aggregation-function/phrases) | Extracts and counts common phrases or word sequences from text fields. |
| Array function | [array\_concat](/apl/scalar-functions/array-functions/array-concat) | Concatenates arrays into one. |
| Array function | [array\_extract](/apl/scalar-functions/array-functions/array-extract) | Extracts values from a nested array. |
| Array function | [array\_iff](/apl/scalar-functions/array-functions/array-iff) | Filters array by condition. |
| Array function | [array\_index\_of](/apl/scalar-functions/array-functions/array-index-of) | Returns index of item in array. |
| Array function | [array\_length](/apl/scalar-functions/array-functions/array-length) | Returns length of array. |
| Array function | [array\_reverse](/apl/scalar-functions/array-functions/array-reverse) | Reverses array elements. |
| Array function | [array\_rotate\_left](/apl/scalar-functions/array-functions/array-rotate-left) | Rotates array values to the left. |
| Array function | [array\_rotate\_right](/apl/scalar-functions/array-functions/array-rotate-right) | Rotates array values to the right. |
| Array function | [array\_select\_dict](/apl/scalar-functions/array-functions/array-select-dict) | Selects dictionary from array of dictionaries. |
| Array function | [array\_shift\_left](/apl/scalar-functions/array-functions/array-shift-left) | Shifts array values to the left. |
| Array function | [array\_shift\_right](/apl/scalar-functions/array-functions/array-shift-right) | Shifts array values to the right. |
| Array function | [array\_slice](/apl/scalar-functions/array-functions/array-slice) | Returns slice of an array. |
| Array function | [array\_sort\_asc](/apl/scalar-functions/array-functions/array-sort-asc) | Sorts an array in ascending order. |
| Array function | [array\_sort\_desc](/apl/scalar-functions/array-functions/array-sort-desc) | Sorts an array in descending order. |
| Array function | [array\_split](/apl/scalar-functions/array-functions/array-split) | Splits array by indices. |
| Array function | [array\_sum](/apl/scalar-functions/array-functions/array-sum) | Sums array elements. |
| Array function | [bag\_has\_key](/apl/scalar-functions/array-functions/bag-has-key) | Checks if dynamic object has a specific key. |
| Array function | [bag\_keys](/apl/scalar-functions/array-functions/bag-keys) | Returns keys of a dynamic property bag. |
| Array function | [bag\_pack](/apl/scalar-functions/array-functions/bag-pack) | Creates a dynamic property bag from key-value pairs. |
| Array function | [bag\_zip](/apl/scalar-functions/array-functions/bag-zip) | Combines two arrays of keys and values into a dynamic property bag. |
| Array function | [isarray](/apl/scalar-functions/array-functions/isarray) | Checks if value is an array. |
| Array function | [len](/apl/scalar-functions/array-functions/len) | Returns array or string length. |
| Array function | [pack\_array](/apl/scalar-functions/array-functions/pack-array) | Packs input into a dynamic array. |
| Array function | [pack\_dictionary](/apl/scalar-functions/array-functions/pack-dictionary) | Returns a dictionary from key-value mappings. |
| Array function | [strcat\_array](/apl/scalar-functions/array-functions/strcat-array) | Joins array elements into a string using a delimiter. |
| Conditional function | [case](/apl/scalar-functions/conditional-function/case) | Evaluates conditions and returns the first matched result. |
| Conditional function | [iff](/apl/scalar-functions/conditional-function/iff) | Returns one of two values based on predicate. |
| Conversion function | [dynamic\_to\_json](/apl/scalar-functions/conversion-functions/dynamic-to-json) | Converts dynamic value to JSON string. |
| Conversion function | [ensure\_field](/apl/scalar-functions/conversion-functions/ensure-field) | Returns value of field or typed null. |
| Conversion function | [isbool](/apl/scalar-functions/conversion-functions/isbool) | Checks if expression evaluates to boolean. |
| Conversion function | [toarray](/apl/scalar-functions/conversion-functions/toarray) | Converts to array. |
| Conversion function | [tobool](/apl/scalar-functions/conversion-functions/tobool) | Converts to boolean. |
| Conversion function | [todatetime](/apl/scalar-functions/conversion-functions/todatetime) | Converts to datetime. |
| Conversion function | [todouble](/apl/scalar-functions/conversion-functions/todouble) | Converts to real. `todouble` and `toreal` are synonyms. |
| Conversion function | [todynamic](/apl/scalar-functions/conversion-functions/todynamic) | Converts to dynamic. |
| Conversion function | [tohex](/apl/scalar-functions/conversion-functions/tohex) | Converts to hexadecimal string. |
| Conversion function | [toint](/apl/scalar-functions/conversion-functions/toint) | Converts to integer. `toint` and `tolong` are synonyms. |
| Conversion function | [tolong](/apl/scalar-functions/conversion-functions/toint) | Converts to signed 64-bit long. `toint` and `tolong` are synonyms. |
| Conversion function | [toreal](/apl/scalar-functions/conversion-functions/todouble) | Converts to real. `todouble` and `toreal` are synonyms. |
| Conversion function | [tostring](/apl/scalar-functions/conversion-functions/tostring) | Converts to string. |
| Conversion function | [totimespan](/apl/scalar-functions/conversion-functions/totimespan) | Converts to timespan. |
| Datetime function | [ago](/apl/scalar-functions/datetime-functions/ago) | Subtracts timespan from current time. |
| Datetime function | [datetime\_add](/apl/scalar-functions/datetime-functions/datetime-add) | Adds amount to datetime. |
| Datetime function | [datetime\_diff](/apl/scalar-functions/datetime-functions/datetime-diff) | Difference between two datetimes. |
| Datetime function | [datetime\_part](/apl/scalar-functions/datetime-functions/datetime-part) | Extracts part of a datetime. |
| Datetime function | [dayofmonth](/apl/scalar-functions/datetime-functions/dayofmonth) | Day number in month. |
| Datetime function | [dayofweek](/apl/scalar-functions/datetime-functions/dayofweek) | Days since previous Sunday. |
| Datetime function | [dayofyear](/apl/scalar-functions/datetime-functions/dayofyear) | Day number in year. |
| Datetime function | [endofday](/apl/scalar-functions/datetime-functions/endofday) | Returns end of day. |
| Datetime function | [endofmonth](/apl/scalar-functions/datetime-functions/endofmonth) | Returns end of month. |
| Datetime function | [endofweek](/apl/scalar-functions/datetime-functions/endofweek) | Returns end of week. |
| Datetime function | [endofyear](/apl/scalar-functions/datetime-functions/endofyear) | Returns end of year. |
| Datetime function | [getmonth](/apl/scalar-functions/datetime-functions/getmonth) | Month of a datetime. |
| Datetime function | [getyear](/apl/scalar-functions/datetime-functions/getyear) | Year of a datetime. |
| Datetime function | [hourofday](/apl/scalar-functions/datetime-functions/hourofday) | Hour number of the day. |
| Datetime function | [monthofyear](/apl/scalar-functions/datetime-functions/monthofyear) | Month number of year. |
| Datetime function | [now](/apl/scalar-functions/datetime-functions/now) | Returns current UTC time. |
| Datetime function | [startofday](/apl/scalar-functions/datetime-functions/startofday) | Returns start of day. |
| Datetime function | [startofmonth](/apl/scalar-functions/datetime-functions/startofmonth) | Returns start of month. |
| Datetime function | [startofweek](/apl/scalar-functions/datetime-functions/startofweek) | Returns start of week. |
| Datetime function | [startofyear](/apl/scalar-functions/datetime-functions/startofyear) | Returns start of year. |
| Datetime function | [unixtime\_microseconds\_todatetime](/apl/scalar-functions/datetime-functions/unixtime-microseconds-todatetime) | Converts microsecond Unix timestamp to datetime. |
| Datetime function | [unixtime\_milliseconds\_todatetime](/apl/scalar-functions/datetime-functions/unixtime-milliseconds-todatetime) | Converts millisecond Unix timestamp to datetime. |
| Datetime function | [unixtime\_nanoseconds\_todatetime](/apl/scalar-functions/datetime-functions/unixtime-nanoseconds-todatetime) | Converts nanosecond Unix timestamp to datetime. |
| Datetime function | [unixtime\_seconds\_todatetime](/apl/scalar-functions/datetime-functions/unixtime-seconds-todatetime) | Converts second Unix timestamp to datetime. |
| Datetime function | [week\_of\_year](/apl/scalar-functions/datetime-functions/week-of-year) | Returns the ISO 8601 week number from a datetime expression. |
| GenAI function | [genai\_concat\_contents](/apl/scalar-functions/genai-functions/genai-concat-contents) | Concatenates message contents from a GenAI conversation array. |
| GenAI function | [genai\_conversation\_turns](/apl/scalar-functions/genai-functions/genai-conversation-turns) | Counts the number of conversation turns in GenAI messages. |
| GenAI function | [genai\_cost](/apl/scalar-functions/genai-functions/genai-cost) | Calculates the total cost for input and output tokens. |
| GenAI function | [genai\_estimate\_tokens](/apl/scalar-functions/genai-functions/genai-estimate-tokens) | Estimates the number of tokens in a text string. |
| GenAI function | [genai\_extract\_assistant\_response](/apl/scalar-functions/genai-functions/genai-extract-assistant-response) | Extracts the assistant’s response from a GenAI conversation. |
| GenAI function | [genai\_extract\_function\_results](/apl/scalar-functions/genai-functions/genai-extract-function-results) | Extracts function call results from GenAI messages. |
| GenAI function | [genai\_extract\_system\_prompt](/apl/scalar-functions/genai-functions/genai-extract-system-prompt) | Extracts the system prompt from a GenAI conversation. |
| GenAI function | [genai\_extract\_tool\_calls](/apl/scalar-functions/genai-functions/genai-extract-tool-calls) | Extracts tool calls from GenAI messages. |
| GenAI function | [genai\_extract\_user\_prompt](/apl/scalar-functions/genai-functions/genai-extract-user-prompt) | Extracts the user prompt from a GenAI conversation. |
| GenAI function | [genai\_get\_content\_by\_index](/apl/scalar-functions/genai-functions/genai-get-content-by-index) | Gets message content by index position. |
| GenAI function | [genai\_get\_content\_by\_role](/apl/scalar-functions/genai-functions/genai-get-content-by-role) | Gets message content by role. |
| GenAI function | [genai\_get\_pricing](/apl/scalar-functions/genai-functions/genai-get-pricing) | Gets pricing information for a specific AI model. |
| GenAI function | [genai\_get\_role](/apl/scalar-functions/genai-functions/genai-get-role) | Gets the role of a message at a specific index. |
| GenAI function | [genai\_has\_tool\_calls](/apl/scalar-functions/genai-functions/genai-has-tool-calls) | Checks if GenAI messages contain tool calls. |
| GenAI function | [genai\_input\_cost](/apl/scalar-functions/genai-functions/genai-input-cost) | Calculates the cost for input tokens. |
| GenAI function | [genai\_is\_truncated](/apl/scalar-functions/genai-functions/genai-is-truncated) | Checks if a GenAI response was truncated. |
| GenAI function | [genai\_message\_roles](/apl/scalar-functions/genai-functions/genai-message-roles) | Extracts all message roles from a GenAI conversation. |
| GenAI function | [genai\_output\_cost](/apl/scalar-functions/genai-functions/genai-output-cost) | Calculates the cost for output tokens. |
| Hash function | [hash\_md5](/apl/scalar-functions/hash-functions/hash-md5) | Returns MD5 hash. |
| Hash function | [hash\_sha1](/apl/scalar-functions/hash-functions/hash-sha1) | Returns SHA-1 hash. |
| Hash function | [hash\_sha256](/apl/scalar-functions/hash-functions/hash-sha256) | Returns SHA256 hash. |
| Hash function | [hash\_sha512](/apl/scalar-functions/hash-functions/hash-sha512) | Returns SHA512 hash. |
| Hash function | [hash](/apl/scalar-functions/hash-functions/hash) | Returns integer hash of input. |
| IP function | [format\_ipv4\_mask](/apl/scalar-functions/ip-functions/format-ipv4-mask) | Formats IPv4 and mask to CIDR. |
| IP function | [format\_ipv4](/apl/scalar-functions/ip-functions/format-ipv4) | Formats netmask into IPv4 string. |
| IP function | [geo\_info\_from\_ip\_address](/apl/scalar-functions/ip-functions/geo-info-from-ip-address) | Extracts geolocation from IP address. |
| IP function | [has\_any\_ipv4\_prefix](/apl/scalar-functions/ip-functions/has-any-ipv4-prefix) | Checks if IPv4 starts with any prefix. |
| IP function | [has\_any\_ipv4](/apl/scalar-functions/ip-functions/has-any-ipv4) | Checks if any of given IPv4s exist in column. |
| IP function | [has\_ipv4\_prefix](/apl/scalar-functions/ip-functions/has-ipv4-prefix) | Checks if IPv4 starts with specified prefix. |
| IP function | [has\_ipv4](/apl/scalar-functions/ip-functions/has-ipv4) | Checks if IPv4 is valid and in source text. |
| IP function | [ipv4\_compare](/apl/scalar-functions/ip-functions/ipv4-compare) | Compares two IPv4 addresses. |
| IP function | [ipv4\_is\_in\_any\_range](/apl/scalar-functions/ip-functions/ipv4-is-in-any-range) | Checks if IPv4 is in any specified range. |
| IP function | [ipv4\_is\_in\_range](/apl/scalar-functions/ip-functions/ipv4-is-in-range) | Checks if IPv4 is in a given range. |
| IP function | [ipv4\_is\_match](/apl/scalar-functions/ip-functions/ipv4-is-match) | Matches IPv4 against a pattern. |
| IP function | [ipv4\_is\_private](/apl/scalar-functions/ip-functions/ipv4-is-private) | Checks if IPv4 is private. |
| IP function | [ipv4\_netmask\_suffix](/apl/scalar-functions/ip-functions/ipv4-netmask-suffix) | Extracts netmask suffix. |
| IP function | [ipv6\_compare](/apl/scalar-functions/ip-functions/ipv6-compare) | Compares two IPv6 addresses. |
| IP function | [ipv6\_is\_in\_any\_range](/apl/scalar-functions/ip-functions/ipv6-is-in-any-range) | Checks if IPv6 is in any range. |
| IP function | [ipv6\_is\_in\_range](/apl/scalar-functions/ip-functions/ipv6-is-in-range) | Checks if IPv6 is in range. |
| IP function | [ipv6\_is\_match](/apl/scalar-functions/ip-functions/ipv6-is-match) | Checks if IPv6 matches pattern. |
| IP function | [parse\_ipv4\_mask](/apl/scalar-functions/ip-functions/parse-ipv4-mask) | Converts IPv4 and mask to long integer. |
| IP function | [parse\_ipv4](/apl/scalar-functions/ip-functions/parse-ipv4) | Converts IPv4 to long integer. |
| Logical operator | [!=](/apl/scalar-operators/logical-operators) | Returns `true` if either one (or both) of the operands are null, or they aren’t equal to each other. Otherwise, `false`. |
| Logical operator | [==](/apl/scalar-operators/logical-operators) | Returns `true` if both operands are non-null and equal to each other. Otherwise, `false`. |
| Logical operator | [and](/apl/scalar-operators/logical-operators) | Returns `true` if both operands are `true`. |
| Logical operator | [or](/apl/scalar-operators/logical-operators) | Returns `true` if one of the operands is `true`, regardless of the other operand. |
| Mathematical function | [abs](/apl/scalar-functions/mathematical-functions/abs) | Returns absolute value. |
| Mathematical function | [acos](/apl/scalar-functions/mathematical-functions/acos) | Returns arccosine of a number. |
| Mathematical function | [asin](/apl/scalar-functions/mathematical-functions/asin) | Returns arcsine of a number. |
| Mathematical function | [atan](/apl/scalar-functions/mathematical-functions/atan) | Returns arctangent of a number. |
| Mathematical function | [atan2](/apl/scalar-functions/mathematical-functions/atan2) | Returns angle between x-axis and point (y, x). |
| Mathematical function | [cos](/apl/scalar-functions/mathematical-functions/cos) | Returns cosine of a number. |
| Mathematical function | [cot](/apl/scalar-functions/mathematical-functions/cot) | Returns cotangent of a number. |
| Mathematical function | [degrees](/apl/scalar-functions/mathematical-functions/degrees) | Converts radians to degrees. |
| Mathematical function | [exp](/apl/scalar-functions/mathematical-functions/exp) | Returns e^x. |
| Mathematical function | [exp10](/apl/scalar-functions/mathematical-functions/exp10) | Returns 10^x. |
| Mathematical function | [exp2](/apl/scalar-functions/mathematical-functions/exp2) | Returns 2^x. |
| Mathematical function | [gamma](/apl/scalar-functions/mathematical-functions/gamma) | Returns gamma function of x. |
| Mathematical function | [isfinite](/apl/scalar-functions/mathematical-functions/isfinite) | Returns `true` if x is finite. |
| Mathematical function | [isinf](/apl/scalar-functions/mathematical-functions/isinf) | Returns `true` if x is infinite. |
| Mathematical function | [isint](/apl/scalar-functions/mathematical-functions/isint) | Returns `true` if x is an integer. |
| Mathematical function | [isnan](/apl/scalar-functions/mathematical-functions/isnan) | Returns `true` if x is NaN. |
| Mathematical function | [log](/apl/scalar-functions/mathematical-functions/log) | Returns natural logarithm of x. |
| Mathematical function | [log10](/apl/scalar-functions/mathematical-functions/log10) | Returns base-10 logarithm. |
| Mathematical function | [log2](/apl/scalar-functions/mathematical-functions/log2) | Returns base-2 logarithm. |
| Mathematical function | [loggamma](/apl/scalar-functions/mathematical-functions/loggamma) | Returns log of absolute gamma function. |
| Mathematical function | [max\_of](/apl/scalar-functions/mathematical-functions/max-of) | Returns largest value among arguments. |
| Mathematical function | [min\_of](/apl/scalar-functions/mathematical-functions/min-of) | Returns smallest value among arguments. |
| Mathematical function | [not](/apl/scalar-functions/mathematical-functions/not) | Reverses boolean value. |
| Mathematical function | [pi](/apl/scalar-functions/mathematical-functions/pi) | Returns value of Pi. |
| Mathematical function | [pow](/apl/scalar-functions/mathematical-functions/pow) | Returns value raised to a power. |
| Mathematical function | [radians](/apl/scalar-functions/mathematical-functions/radians) | Converts degrees to radians. |
| Mathematical function | [rand](/apl/scalar-functions/mathematical-functions/rand) | Returns pseudo-random numbers between 0 (inclusive) and 1 (exclusive). |
| Mathematical function | [range](/apl/scalar-functions/mathematical-functions/range) | Returns a dynamic array of evenly spaced values. |
| Mathematical function | [round](/apl/scalar-functions/mathematical-functions/round) | Rounds value to given precision. |
| Mathematical function | [set\_difference](/apl/scalar-functions/mathematical-functions/set-difference) | Returns array difference. |
| Mathematical function | [set\_has\_element](/apl/scalar-functions/mathematical-functions/set-has-element) | Returns `true` if set contains an element. |
| Mathematical function | [set\_intersect](/apl/scalar-functions/mathematical-functions/set-intersect) | Returns array intersection. |
| Mathematical function | [set\_union](/apl/scalar-functions/mathematical-functions/set-union) | Returns array union. |
| Mathematical function | [sign](/apl/scalar-functions/mathematical-functions/sign) | Returns sign of number. |
| Mathematical function | [sin](/apl/scalar-functions/mathematical-functions/sin) | Returns sine of a number. |
| Mathematical function | [sqrt](/apl/scalar-functions/mathematical-functions/sqrt) | Returns square root of a number. |
| Mathematical function | [tan](/apl/scalar-functions/mathematical-functions/tan) | Returns tangent of a number. |
| Metadata function | [column\_ifexists](/apl/scalar-functions/metadata-functions/column-ifexists) | Checks if a field with a given name exists in the dataset. |
| Metadata function | [cursor\_current](/apl/scalar-functions/metadata-functions/cursor-current) | Retrieves a cursor string representing the current query execution point. |
| Metadata function | [ingestion\_time](/apl/scalar-functions/metadata-functions/ingestion-time) | Retrieves the timestamp of when each record was ingested into Axiom. |
| Numerical operator | [-](/apl/scalar-operators/numerical-operators) | Subtract. Example: `0.26 - 0.23` |
| Numerical operator | [!=](/apl/scalar-operators/numerical-operators) | Not equals. Example: `2 != 1` |
| Numerical operator | [\*](/apl/scalar-operators/numerical-operators) | Multiply. Example: `1s * 5`, `5 * 5` |
| Numerical operator | [/](/apl/scalar-operators/numerical-operators) | Divide. Example: `10m / 1s`, `4 / 2` |
| Numerical operator | [\<](/apl/scalar-operators/numerical-operators) | Less. Example: `1 < 2`, `1 <= 1` |
| Numerical operator | [\<=](/apl/scalar-operators/numerical-operators) | Less or Equal. Example: `5 <= 6` |
| Numerical operator | [%](/apl/scalar-operators/numerical-operators) | Modulo. Example: `10 % 3`, `5 % 2` |
| Numerical operator | [+](/apl/scalar-operators/numerical-operators) | Add. Example: `3.19 + 3.19`, `ago(10m) + 10m` |
| Numerical operator | [==](/apl/scalar-operators/numerical-operators) | Equals. Example: `3 == 3` |
| Numerical operator | [>](/apl/scalar-operators/numerical-operators) | Greater. Example: `0.23 > 0.22`, `now() > ago(1d)` |
| Numerical operator | [>=](/apl/scalar-operators/numerical-operators) | Greater or Equal. Example: `7 >= 6` |
| Pair function | [find\_pair](/apl/scalar-functions/pair-functions/find-pair) | Searches an array of key-value pairs for the first pair matching specified patterns. |
| Pair function | [pair](/apl/scalar-functions/pair-functions/pair) | Creates a dynamic object representing a key-value pair. |
| Pair function | [parse\_pair](/apl/scalar-functions/pair-functions/parse-pair) | Parses a pair string into its key and value components. |
| Rounding function | [bin](/apl/scalar-functions/rounding-functions/bin) | Rounds values down to an integer multiple of a specified bin size. |
| Rounding function | [bin\_auto](/apl/scalar-functions/rounding-functions/bin-auto) | Rounds datetime values down to a fixed-size bin with automatic size selection. |
| Rounding function | [ceiling](/apl/scalar-functions/rounding-functions/ceiling) | Rounds a number up to the smallest integer greater than or equal to the input. |
| Rounding function | [floor](/apl/scalar-functions/rounding-functions/floor) | Rounds a number down to the largest integer less than or equal to the input. |
| Set membership operator | [in](/apl/scalar-operators/in-operators/in-operator) | Equals to one of the elements (case-sensitive). Example: `"abc" in ("123", "345", "abc")` |
| Set membership operator | [in\~](/apl/scalar-operators/in-operators/in-tilde-operator) | Equals to one of the elements (case-insensitive). Example: `"abc" in~ ("123", "345", "ABC")` |
| Set membership operator | [!in](/apl/scalar-operators/in-operators/not-in-operator) | Not equals to any of the elements (case-sensitive). Example: `"bca" !in ("123", "345", "abc")` |
| Set membership operator | [!in\~](/apl/scalar-operators/in-operators/not-in-tilde-operator) | Not equals to any of the elements (case-insensitive). Example: `"bca" !in~ ("123", "345", "ABC")` |
| SQL function | [format\_sql](/apl/scalar-functions/sql-functions/format-sql) | Converts parsed SQL data model back into SQL statement. |
| SQL function | [parse\_sql](/apl/scalar-functions/sql-functions/parse-sql) | Parses and analyzes SQL queries. |
| String function | [base64\_decode\_toarray](/apl/scalar-functions/string-functions/base64-decode-toarray) | Decodes a Base64-encoded string into an array of bytes. |
| String function | [base64\_decode\_tostring](/apl/scalar-functions/string-functions/base64-decode-tostring) | Decodes a base64 string to a UTF-8 string. |
| String function | [base64\_encode\_fromarray](/apl/scalar-functions/string-functions/base64-encode-fromarray) | Converts a sequence of bytes into a Base64-encoded string. |
| String function | [base64\_encode\_tostring](/apl/scalar-functions/string-functions/base64-encode-tostring) | Encodes a string as base64 string. |
| String function | [coalesce](/apl/scalar-functions/string-functions/coalesce) | Returns the first non-null/non-empty value from a list. |
| String function | [countof\_regex](/apl/scalar-functions/string-functions/countof-regex) | Counts occurrences of a regex in a string. |
| String function | [countof](/apl/scalar-functions/string-functions/countof) | Counts occurrences of a substring in a string. |
| String function | [extract\_all](/apl/scalar-functions/string-functions/extract-all) | Gets all matches for a regular expression from a text string. |
| String function | [extract](/apl/scalar-functions/string-functions/extract) | Gets a match for a regular expression from a text string. |
| String function | [format\_bytes](/apl/scalar-functions/string-functions/format-bytes) | Formats a number of bytes as a string including units. |
| String function | [format\_url](/apl/scalar-functions/string-functions/format-url) | Formats a string into a valid URL. |
| String function | [gettype](/apl/scalar-functions/string-functions/gettype) | Returns the runtime type of an argument. |
| String function | [indexof](/apl/scalar-functions/string-functions/indexof) | Returns index of the first occurrence of a substring. |
| String function | [isascii](/apl/scalar-functions/string-functions/isascii) | Returns `true` if all characters in an input string are ASCII characters. |
| String function | [isempty](/apl/scalar-functions/string-functions/isempty) | Returns `true` if the argument is empty or null. |
| String function | [isnotempty](/apl/scalar-functions/string-functions/isnotempty) | Returns `true` if the argument isn’t empty or null. |
| String function | [isnotnull](/apl/scalar-functions/string-functions/isnotnull) | Returns `true` if the argument isn’t null. |
| String function | [isnull](/apl/scalar-functions/string-functions/isnull) | Returns `true` if the argument is null. |
| String function | [parse\_bytes](/apl/scalar-functions/string-functions/parse-bytes) | Parses byte-size string to number of bytes. |
| String function | [parse\_csv](/apl/scalar-functions/string-functions/parse-csv) | Splits a CSV-formatted string into an array. |
| String function | [parse\_json](/apl/scalar-functions/string-functions/parse-json) | Parses a string as a JSON value. |
| String function | [parse\_url](/apl/scalar-functions/string-functions/parse-url) | Parses a URL string and returns parts in a dynamic object. |
| String function | [parse\_urlquery](/apl/scalar-functions/string-functions/parse-urlquery) | Parses a URL query string into key-value pairs. |
| String function | [quote](/apl/scalar-functions/string-functions/quote) | Returns a string representing the input enclosed in double quotes, with internal quotes and escape sequences handled appropriately. |
| String function | [replace\_regex](/apl/scalar-functions/string-functions/replace-regex) | Replaces regex matches with another string. |
| String function | [replace\_string](/apl/scalar-functions/string-functions/replace-string) | Replaces string matches with another string. |
| String function | [replace](/apl/scalar-functions/string-functions/replace) | Replaces all regex matches with another string. |
| String function | [reverse](/apl/scalar-functions/string-functions/reverse) | Reverses a string. |
| String function | [split](/apl/scalar-functions/string-functions/split) | Splits a string into an array using a delimiter. |
| String function | [strcat\_delim](/apl/scalar-functions/string-functions/strcat-delim) | Concatenates 2–64 arguments with a delimiter. |
| String function | [strcat](/apl/scalar-functions/string-functions/strcat) | Concatenates 1–64 arguments. |
| String function | [strcmp](/apl/scalar-functions/string-functions/strcmp) | Compares two strings. |
| String function | [string-size](/apl/scalar-functions/string-functions/string-size) | Returns the length, in characters, of the input string. |
| String function | [strip\_ansi\_escapes](/apl/scalar-functions/string-functions/strip-ansi-escapes) | Removes ANSI escape sequences from strings. |
| String function | [strlen](/apl/scalar-functions/string-functions/strlen) | Returns the length of a string. |
| String function | [strrep](/apl/scalar-functions/string-functions/strrep) | Repeats a string a given number of times. |
| String function | [substring](/apl/scalar-functions/string-functions/substring) | Extracts a substring. |
| String function | [tolower](/apl/scalar-functions/string-functions/tolower) | Converts string to lowercase. |
| String function | [totitle](/apl/scalar-functions/string-functions/totitle) | Converts string to title case. |
| String function | [toupper](/apl/scalar-functions/string-functions/toupper) | Converts string to uppercase. |
| String function | [translate](/apl/scalar-functions/string-functions/translate) | Substitutes characters in a string, one by one, based on their position in two input lists. |
| String function | [trim\_end\_regex](/apl/scalar-functions/string-functions/trim-end-regex) | Trims trailing characters using regex. |
| String function | [trim\_end](/apl/scalar-functions/string-functions/trim-end) | Trims trailing characters. |
| String function | [trim\_regex](/apl/scalar-functions/string-functions/trim-regex) | Trims characters matching a regex. |
| String function | [trim\_space](/apl/scalar-functions/string-functions/trim-space) | Removes all leading and trailing whitespace from a string. |
| String function | [trim\_start\_regex](/apl/scalar-functions/string-functions/trim-start-regex) | Trims leading characters using regex. |
| String function | [trim\_start](/apl/scalar-functions/string-functions/trim-start) | Trims leading characters. |
| String function | [trim](/apl/scalar-functions/string-functions/trim) | Trims leading/trailing characters. |
| String function | [unicode\_codepoints\_from\_string](/apl/scalar-functions/string-functions/unicode-codepoints-from-string) | Converts a UTF-8 string into an array of Unicode code points. |
| String function | [unicode\_codepoints\_to\_string](/apl/scalar-functions/string-functions/unicode-codepoints-to-string) | Converts an array of Unicode code points into a UTF-8 encoded string. |
| String function | [url\_decode](/apl/scalar-functions/string-functions/url-decode) | Decodes a URL-encoded string. |
| String function | [url\_encode](/apl/scalar-functions/string-functions/url-encode) | Encodes characters into a URL-friendly format. |
| String operator | [!=](/apl/scalar-operators/string-operators) | Not equals (case-sensitive). Example: `"abc" != "ABC"` |
| String operator | [!\~](/apl/scalar-operators/string-operators) | Not equals (case-insensitive). Example: `"aBc" !~ "xyz"` |
| String operator | [!contains\_cs](/apl/scalar-operators/string-operators) | RHS doesn’t occur in LHS (case-sensitive). Example: `"parentSpanId" !contains_cs "Id"` |
| String operator | [!contains](/apl/scalar-operators/string-operators) | RHS doesn’t occur in LHS (case-insensitive). Example: `"parentSpanId" !contains "abc"` |
| String operator | [!endswith\_cs](/apl/scalar-operators/string-operators) | RHS isn’t a closing subsequence of LHS (case-sensitive). Example: `"parentSpanId" !endswith_cs "Span"` |
| String operator | [!endswith](/apl/scalar-operators/string-operators) | RHS isn’t a closing subsequence of LHS (case-insensitive). Example: `"parentSpanId" !endswith "Span"` |
| String operator | [!has\_cs](/apl/scalar-operators/string-operators) | RHS isn’t a whole term in LHS (case-sensitive). Example: `"North America" !has_cs "America"` |
| String operator | [!has](/apl/scalar-operators/string-operators) | RHS isn’t a whole term in LHS (case-insensitive). Example: `"North America" !has "america"` |
| String operator | [!hasprefix\_cs](/apl/scalar-operators/string-operators) | LHS string doesn’t start with the RHS string (case-sensitive). Example: `"DOCS_file" !hasprefix_cs "DOCS"` |
| String operator | [!hasprefix](/apl/scalar-operators/string-operators) | LHS string doesn’t start with the RHS string (case-insensitive). Example: `"Admin_User" !hasprefix "Admin"` |
| String operator | [!hassuffix\_cs](/apl/scalar-operators/string-operators) | LHS string doesn’t end with the RHS string (case-sensitive). Example: `"Document.HTML" !hassuffix_cs ".HTML"` |
| String operator | [!hassuffix](/apl/scalar-operators/string-operators) | LHS string doesn’t end with the RHS string (case-insensitive). Example: `"documentation.docx" !hassuffix ".docx"` |
| String operator | [!matches regex](/apl/scalar-operators/string-operators) | LHS doesn’t contain a match for RHS. Example: `"parentSpanId" !matches regex "g.*r"` |
| String operator | [!startswith\_cs](/apl/scalar-operators/string-operators) | RHS isn’t an initial subsequence of LHS (case-sensitive). Example: `"parentSpanId" !startswith_cs "parent"` |
| String operator | [!startswith](/apl/scalar-operators/string-operators) | RHS isn’t an initial subsequence of LHS (case-insensitive). Example: `"parentSpanId" !startswith "Id"` |
| String operator | [==](/apl/scalar-operators/string-operators) | Equals (case-sensitive). Example: `"aBc" == "aBc"` |
| String operator | [=\~](/apl/scalar-operators/string-operators) | Equals (case-insensitive). Example: `"abc" =~ "ABC"` |
| String operator | [contains\_cs](/apl/scalar-operators/string-operators) | RHS occurs as a subsequence of LHS (case-sensitive). Example: `"parentSpanId" contains_cs "Id"` |
| String operator | [contains](/apl/scalar-operators/string-operators) | RHS occurs as a subsequence of LHS (case-insensitive). Example: `"parentSpanId" contains "Span"` |
| String operator | [endswith\_cs](/apl/scalar-operators/string-operators) | RHS is a closing subsequence of LHS (case-sensitive). Example: `"parentSpanId" endswith_cs "Id"` |
| String operator | [endswith](/apl/scalar-operators/string-operators) | RHS is a closing subsequence of LHS (case-insensitive). Example: `"parentSpanId" endswith "Id"` |
| String operator | [has\_cs](/apl/scalar-operators/string-operators) | RHS is a whole term in LHS (case-sensitive). Example: `"North America" has_cs "America"` |
| String operator | [has](/apl/scalar-operators/string-operators) | RHS is a whole term in LHS (case-insensitive). Example: `"North America" has "america"` |
| String operator | [has\_any](/apl/scalar-operators/string-operators) | RHS has any whole term in LHS (case-insensitive). Example: `"North America" has_any ("america", "europe")` |
| String operator | [has\_any\_cs](/apl/scalar-operators/string-operators) | RHS has any whole term in LHS (case-sensitive). Example: `"North America" has_any_cs ("America", "Europe")` |
| String operator | [hasprefix\_cs](/apl/scalar-operators/string-operators) | LHS string starts with the RHS string (case-sensitive). Example: `"DOCS_file" hasprefix_cs "DOCS"` |
| String operator | [hasprefix](/apl/scalar-operators/string-operators) | LHS string starts with the RHS string (case-insensitive). Example: `"Admin_User" hasprefix "Admin"` |
| String operator | [hassuffix\_cs](/apl/scalar-operators/string-operators) | LHS string ends with the RHS string (case-sensitive). Example: `"Document.HTML" hassuffix_cs ".HTML"` |
| String operator | [hassuffix](/apl/scalar-operators/string-operators) | LHS string ends with the RHS string (case-insensitive). Example: `"documentation.docx" hassuffix ".docx"` |
| String operator | [matches regex](/apl/scalar-operators/string-operators) | LHS contains a match for RHS. Example: `"parentSpanId" matches regex "g.*r"` |
| String operator | [startswith\_cs](/apl/scalar-operators/string-operators) | RHS is an initial subsequence of LHS (case-sensitive). Example: `"parentSpanId" startswith_cs "parent"` |
| String operator | [startswith](/apl/scalar-operators/string-operators) | RHS is an initial subsequence of LHS (case-insensitive). Example: `"parentSpanId" startswith "parent"` |
| Tabular operator | [count](/apl/tabular-operators/count-operator) | Returns an integer representing the total number of records in the dataset. |
| Tabular operator | [distinct](/apl/tabular-operators/distinct-operator) | Returns a dataset with unique values from the specified fields, removing any duplicate entries. |
| Tabular operator | [extend-valid](/apl/tabular-operators/extend-valid-operator) | Returns a table where the specified fields are extended with new values based on the given expression for valid rows. |
| Tabular operator | [extend](/apl/tabular-operators/extend-operator) | Returns the original dataset with one or more new fields appended, based on the defined expressions. |
| Tabular operator | [externaldata](/apl/tabular-operators/externaldata-operator) | Returns a table with the specified schema, containing data retrieved from an external source. |
| Tabular operator | [getschema](/apl/tabular-operators/getschema-operator) | Returns the schema of the input, including field names and their data types. |
| Tabular operator | [join](/apl/tabular-operators/join-operator) | Returns a dataset containing rows from two different tables based on conditions. |
| Tabular operator | [limit](/apl/tabular-operators/limit-operator) | Returns the top N rows from the input dataset. |
| Tabular operator | [lookup](/apl/tabular-operators/lookup-operator) | Returns a dataset where rows from one dataset are enriched with matching columns from a lookup table based on conditions. |
| Tabular operator | [make-series](/apl/tabular-operators/make-series) | Returns a dataset where the specified field is aggregated into a time series. |
| Tabular operator | [mv-expand](/apl/tabular-operators/mv-expand) | Returns a dataset where the specified field is expanded into multiple rows. |
| Tabular operator | [order](/apl/tabular-operators/order-operator) | Returns the input dataset, sorted according to the specified fields and order. |
| Tabular operator | [parse](/apl/tabular-operators/parse-operator) | Returns the input dataset with new fields added based on the specified parsing pattern. |
| Tabular operator | [parse-kv](/apl/tabular-operators/parse-kv) | Returns a dataset where key-value pairs are extracted from a string field into individual columns. |
| Tabular operator | [parse-where](/apl/tabular-operators/parse-where) | Returns a dataset where values from a string are extracted based on a pattern. |
| Tabular operator | [project-away](/apl/tabular-operators/project-away-operator) | Returns the input dataset excluding the specified fields. |
| Tabular operator | [project-keep](/apl/tabular-operators/project-keep-operator) | Returns a dataset with only the specified fields. |
| Tabular operator | [project-rename](/apl/tabular-operators/project-rename) | Returns a dataset where the specified field is renamed according to the specified pattern. |
| Tabular operator | [project-reorder](/apl/tabular-operators/project-reorder-operator) | Returns a table with the specified fields reordered as requested followed by any unspecified fields in their original order. |
| Tabular operator | [project](/apl/tabular-operators/project-operator) | Returns a dataset containing only the specified fields. |
| Tabular operator | [redact](/apl/tabular-operators/redact-operator) | Returns the input dataset with sensitive data replaced or hashed. |
| Tabular operator | [sample](/apl/tabular-operators/sample-operator) | Returns a table containing the specified number of rows, selected randomly from the input dataset. |
| Tabular operator | [search](/apl/tabular-operators/search-operator) | Returns all rows where the specified keyword appears in any field. |
| Tabular operator | [sort](/apl/tabular-operators/sort-operator) | Returns a table with rows ordered based on the specified fields. |
| Tabular operator | [summarize](/apl/tabular-operators/summarize-operator) | Returns a table where each row represents a unique combination of values from the by fields, with the aggregated results calculated for the other fields. |
| Tabular operator | [take](/apl/tabular-operators/take-operator) | Returns the specified number of rows from the dataset. |
| Tabular operator | [top](/apl/tabular-operators/top-operator) | Returns the top N rows from the dataset based on the specified sorting criteria. |
| Tabular operator | [union](/apl/tabular-operators/union-operator) | Returns all rows from the specified tables or queries. |
| Tabular operator | [where](/apl/tabular-operators/where-operator) | Returns a filtered dataset containing only the rows where the condition evaluates to true. |
| Time series function | [series\_abs](/apl/scalar-functions/time-series/series-abs) | Returns the absolute value of a series. |
| Time series function | [series\_acos](/apl/scalar-functions/time-series/series-acos) | Returns the inverse cosine (arccos) of a series. |
| Time series function | [series\_add](/apl/scalar-functions/time-series/series-add) | Performs element-wise addition between two series. |
| Time series function | [series\_asin](/apl/scalar-functions/time-series/series-asin) | Returns the inverse sine (arcsin) of a series. |
| Time series function | [series\_atan](/apl/scalar-functions/time-series/series-atan) | Returns the inverse tangent (arctan) of a series. |
| Time series function | [series\_ceiling](/apl/scalar-functions/time-series/series-ceiling) | Rounds each element up to the nearest integer. |
| Time series function | [series\_cos](/apl/scalar-functions/time-series/series-cos) | Returns the cosine of a series. |
| Time series function | [series\_cosine\_similarity](/apl/scalar-functions/time-series/series-cosine-similarity) | Calculates the cosine similarity between two series. |
| Time series function | [series\_divide](/apl/scalar-functions/time-series/series-divide) | Performs element-wise division between two series. |
| Time series function | [series\_dot\_product](/apl/scalar-functions/time-series/series-dot-product) | Calculates the dot product between two series. |
| Time series function | [series\_equals](/apl/scalar-functions/time-series/series-equals) | Compares each element in a series to a specified value and returns a boolean array. |
| Time series function | [series\_exp](/apl/scalar-functions/time-series/series-exp) | Calculates the exponential (e^x) of each element in a series. |
| Time series function | [series\_fft](/apl/scalar-functions/time-series/series-fft) | Performs a Fast Fourier Transform on a series, converting time-domain data into frequency-domain representation. |
| Time series function | [series\_fill\_backward](/apl/scalar-functions/time-series/series-fill-backward) | Fills missing values by propagating the last known value backward through the array. |
| Time series function | [series\_fill\_const](/apl/scalar-functions/time-series/series-fill-const) | Fills missing values with a specified constant value. |
| Time series function | [series\_fill\_forward](/apl/scalar-functions/time-series/series-fill-forward) | Fills missing values by propagating the first known value forward through the array. |
| Time series function | [series\_fill\_linear](/apl/scalar-functions/time-series/series-fill-linear) | Fills missing values using linear interpolation between known values. |
| Time series function | [series\_fir](/apl/scalar-functions/time-series/series-fir) | Applies a Finite Impulse Response filter to a series using a specified filter kernel. |
| Time series function | [series\_floor](/apl/scalar-functions/time-series/series-floor) | Rounds down each element in a series to the nearest integer. |
| Time series function | [series\_greater](/apl/scalar-functions/time-series/series-greater) | Returns the elements of a series that are greater than a specified value. |
| Time series function | [series\_greater\_equals](/apl/scalar-functions/time-series/series-greater-equals) | Returns the elements of a series that are greater than or equal to a specified value. |
| Time series function | [series\_ifft](/apl/scalar-functions/time-series/series-ifft) | Performs an Inverse Fast Fourier Transform on a series, converting frequency-domain data back into time-domain representation. |
| Time series function | [series\_iir](/apl/scalar-functions/time-series/series-iir) | Applies an Infinite Impulse Response filter to a series. |
| Time series function | [series\_less](/apl/scalar-functions/time-series/series-less) | Returns the elements of a series that are less than a specified value. |
| Time series function | [series\_less\_equals](/apl/scalar-functions/time-series/series-less-equals) | Returns the elements of a series that are less than or equal to a specified value. |
| Time series function | [series\_log](/apl/scalar-functions/time-series/series-log) | Returns the natural logarithm of each element in a series. |
| Time series function | [series\_magnitude](/apl/scalar-functions/time-series/series-magnitude) | Calculates the Euclidean norm (magnitude) of a series. |
| Time series function | [series\_max](/apl/scalar-functions/time-series/series-max) | Returns the maximum value from a series. |
| Time series function | [series\_min](/apl/scalar-functions/time-series/series-min) | Returns the minimum value from a series. |
| Time series function | [series\_multiply](/apl/scalar-functions/time-series/series-multiply) | Performs element-wise multiplication of two series. |
| Time series function | [series\_not\_equals](/apl/scalar-functions/time-series/series-not-equals) | Returns the elements of a series that aren’t equal to a specified value. |
| Time series function | [series\_pearson\_correlation](/apl/scalar-functions/time-series/series-pearson-correlation) | Calculates the Pearson correlation coefficient between two series. |
| Time series function | [series\_pow](/apl/scalar-functions/time-series/series-pow) | Raises each element in a series to a specified power. |
| Time series function | [series\_sign](/apl/scalar-functions/time-series/series-sign) | Returns the sign of each element in a series. |
| Time series function | [series\_sin](/apl/scalar-functions/time-series/series-sin) | Returns the sine of a series. |
| Time series function | [series\_stats](/apl/scalar-functions/time-series/series-stats) | Computes comprehensive statistical measures for a series. |
| Time series function | [series\_stats\_dynamic](/apl/scalar-functions/time-series/series-stats-dynamic) | Computes statistical measures and returns them in a dynamic object format. |
| Time series function | [series\_subtract](/apl/scalar-functions/time-series/series-subtract) | Performs element-wise subtraction between two series. |
| Time series function | [series\_sum](/apl/scalar-functions/time-series/series-sum) | Returns the sum of a series. |
| Time series function | [series\_tan](/apl/scalar-functions/time-series/series-tan) | Returns the tangent of a series. |
| Type function | [iscc](/apl/scalar-functions/type-functions/iscc) | Checks whether a value is a valid credit card (CC) number. |
| Type function | [isimei](/apl/scalar-functions/type-functions/isimei) | Checks whether a value is a valid International Mobile Equipment Identity (IMEI) number. |
| Type function | [ismap](/apl/scalar-functions/type-functions/ismap) | Checks whether a value is of the `dynamic` type and represents a mapping. |
| Type function | [isreal](/apl/scalar-functions/type-functions/isreal) | Checks whether a value is a real number. |
| Type function | [isstring](/apl/scalar-functions/type-functions/isstring) | Checks whether a value is a string. |
| Type function | [isutf8](/apl/scalar-functions/type-functions/isutf8) | Checks whether a value is a valid UTF-8 encoded sequence. |
---
# Axiom Processing Language (APL)
Source: https://axiom.co/docs/apl/introduction
Axiom Processing Language (APL) is a text-based query language for logs, traces, and events stored in [EventDB](/platform-overview/architecture). It provides the flexibility to filter, manipulate, and summarize your data exactly the way you need it.
You can't use APL to query metrics. To query metrics, use [MPL](/mpl/introduction).
## Build an APL query [#build-an-apl-query]
APL queries consist of the following:
* **Data source:** The most common data source is one of your Axiom datasets.
* **Operators:** Operators filter, manipulate, and summarize your data.
Delimit operators with the pipe character (`|`).
A typical APL query has the following structure:
```kusto
DatasetName
| Operator ...
| Operator ...
```
* `DatasetName` is the name of the dataset you want to query.
* `Operator` is an operation you apply to the data.
Apart from Axiom datasets, you can use other data sources:
* External data sources using the [externaldata](/apl/tabular-operators/externaldata-operator) operator.
* Specify a data table in the APL query itself using the `let` statement.
## Example query [#example-query]
```kusto
['github-issue-comment-event']
| extend isBot = actor contains '-bot' or actor contains '[bot]'
| where isBot == true
| summarize count() by bin_auto(_time), actor
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'github-issue-comment-event'%5D%20%7C%20extend%20isBot%20%3D%20actor%20contains%20'-bot'%20or%20actor%20contains%20'%5Bbot%5D'%20%7C%20where%20isBot%20%3D%3D%20true%20%7C%20summarize%20count\(\)%20by%20bin_auto\(_time\)%2C%20actor%22%7D)
The query above uses a dataset called `github-issue-comment-event` as its data source. It uses the following operators:
* [extend](/apl/tabular-operators/extend-operator) adds a new field `isBot` to the query results. It sets the values of the new field to true if the values of the `actor` field in the original dataset contain `-bot` or `[bot]`.
* [where](/apl/tabular-operators/where-operator) filters for the values of the `isBot` field. It only returns rows where the value is true.
* [summarize](/apl/tabular-operators/summarize-operator) aggregates the data and produces a chart.
Each operator is separated using the pipe character (`|`).
## Example result [#example-result]
As a result, the query returns a chart and a table. The table counts the different values of the `actor` field where `isBot` is true, and the chart displays the distribution of these counts over time.
| actor | count\_ |
| -------------------- | ------- |
| github-actions\[bot] | 487 |
| sonarqubecloud\[bot] | 208 |
| dependabot\[bot] | 148 |
| vercel\[bot] | 91 |
| codecov\[bot] | 63 |
| openshift-ci\[bot] | 52 |
| coderabbitai\[bot] | 43 |
| netlify\[bot] | 37 |
The query results are a representation of your data based on your request. The query doesn’t change the original dataset.
## Quote dataset and field names [#quote-dataset-and-field-names]
If the name of a dataset or field contains at least one of the following special characters, quote the name in your APL query:
* Space (` `)
* Dot (`.`)
* Dash (`-`)
To quote the dataset or field in your APL query, enclose its name with quotation marks (`'` or `"`) and square brackets (`[]`). For example, `['my-field']`.
For more information on rules about naming and quoting entities, see [Entity names](/apl/entities/entity-names).
## Common patterns [#common-patterns]
### Handle nested JSON [#handle-nested-json]
A common scenario is dealing with fields that contain JSON objects. Use `parse_json` to access nested data.
```kusto
['sample-http-logs']
| extend parsed_headers = parse_json(req_duration_ms)
| where isnotempty(method)
| project _time, method, status, geo.city
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20extend%20parsed_headers%20%3D%20parse_json\(req_duration_ms\)%5Cn%7C%20where%20isnotempty\(method\)%5Cn%7C%20project%20_time%2C%20method%2C%20status%2C%20%5B'geo.city'%5D%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
* `extend parsedField = parse_json(...)` converts JSON text into a structured field you can access with dot notation.
* `project _time, method, status, geo.city` selects only the fields you need.
### Filter and project early [#filter-and-project-early]
A well-written query runs faster, consumes fewer resources, and gets you answers more efficiently. The two most important principles:
1. **Filter early.** Reduce the amount of data as soon as possible.
2. **Project only what you need.** Avoid selecting unnecessary fields.
Some datasets are wide, containing hundreds or thousands of fields. When you query these datasets with APL, use `project` to select only the fields you need. Without `project`, Axiom retrieves all fields for each event, which slows down queries.
**Sub-optimal:**
```kusto
['sample-http-logs']
| sort by _time desc
| take 10
```
This retrieves all fields for each of the 10 events.
**Optimized:**
```kusto
['sample-http-logs']
| project _time, method, status, uri, resp_body_size_bytes
| sort by _time desc
| take 10
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20project%20_time%2C%20method%2C%20status%2C%20uri%2C%20resp_body_size_bytes%5Cn%7C%20sort%20by%20_time%20desc%5Cn%7C%20take%2010%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
By adding `project`, the query ignores all other fields, minimizing I/O and reducing data sent over the network.
* Always use `project` or `project-away` after your `where` filters to reduce data volume. `project` keeps specified fields, `project-away` removes them.
* Place your most restrictive `where` filters as early as possible in the query.
### Virtual fields [#virtual-fields]
[Virtual fields](/query-data/virtual-fields) let you define new fields based on an APL expression. Instead of pre-processing data before sending it to Axiom, you create these fields on the fly during a query. This provides flexibility for analysis without altering the raw data.
**Example: Simple conversion**
This example converts a response body size from bytes to kilobytes:
* **Name:** `resp_size_kb`
* **Expression:** `resp_body_size_bytes / 1024`
**Example: Categorization**
This example uses conditional logic to segment data. Define a virtual field to categorize HTTP responses:
* **Name:** `response_category`
* **Expression:** `case(status >= 500, "Server Error", status >= 400, "Client Error", status >= 300, "Redirect", "Success")`
Now you can run queries like `... | summarize count() by response_category` to compare behavior across these groups.
* Use virtual fields to avoid sending redundant data. If you can derive a value, you don't need to add it to your raw logs.
* Use virtual fields to normalize data from different sources. If one service logs `request_time` and another logs `duration`, create a virtual field using `coalesce(request_time, duration)` to standardize them.
* For very common, expensive transformations queried frequently, consider performing them at ingest time instead.
### Factors impacting query performance [#factors-impacting-query-performance]
* **Catch-all queries:** Queries that don't specify fields with `project` select all fields. Avoid this on high-dimensionality datasets.
* **High cardinality `summarize` operations:** When the `by` field has very many unique values (like a `traceId`), the query may produce an enormous number of groups. Axiom has built-in limits to protect against this.
* **Mixed data types:** If a field has mixed types (for example, a status code is sometimes a number `200` and sometimes a string `"200"`), queries can produce unexpected results.
For best performance, aim for consistent typing. If you can't avoid mixed types, normalize the data at query time using typecasting functions like `tostring()` or `toint()`. For example, `| where tostring(status) startswith "2"` works reliably on a field with mixed types.
For more information, see [Performance](/reference/performance).
### Platform limits [#platform-limits]
* **Fields per dataset:** A dataset can have a maximum number of fields. While the limit is high, ingesting logs with thousands of fields can cause issues.
* **Data retention:** Datasets have a configurable retention period. Data older than this period is automatically deleted.
* **Query rate limits:** Axiom imposes rate limits on queries to ensure service stability.
For more information, see [Limits](/reference/limits).
## What’s next [#whats-next]
Check out the [list of example queries](/apl/tutorial) or explore the supported operators and functions:
* [Scalar functions](/apl/scalar-functions/string-functions)
* [Aggregation functions](/apl/aggregation-function/statistical-functions)
* [Tabular operators](/apl/tabular-operators/overview)
* [Scalar operators](/apl/scalar-operators/logical-operators)
---
# Query reference overview
Source: https://axiom.co/docs/apl/overview
Axiom provides two purpose-built query languages, each designed for different data types:
| | APL | MPL |
| :------------- | :----------------------------------------- | :------------------------------------------- |
| **Full name** | Axiom Processing Language | Metrics Processing Language |
| **Data types** | Logs, traces, events | Metrics |
| **Data store** | [EventDB](/platform-overview/architecture) | [MetricsDB](/platform-overview/architecture) |
| **Reference** | [APL reference](/apl/introduction) | [MPL reference](/mpl/introduction) |
## Why two query languages [#why-two-query-languages]
Logs, traces, and events are discrete records: each row is a self-contained entry with an arbitrary schema. The language designed for this kind of data is APL (Axiom Processing Language), which excels at slicing, extending, and summarizing data.
Metrics are structurally different. A metric is a named time series with a fixed set of tags. Rather than rows of events, you work with continuous streams of numerical values that need rate calculations, time-window alignment, tag-based grouping, and cross-metric arithmetic. Axiom stores metrics in [MetricsDB](/platform-overview/architecture), a purpose-built storage engine optimized for high-cardinality time-series data. MPL is the query language designed to match that storage model.
## APL (Axiom Processing Language) [#apl-axiom-processing-language]
APL is a text-based query language for querying logs, traces, and events stored in EventDB. It provides the flexibility to filter, manipulate, extend, and summarize your event data exactly the way you need it.
An APL query starts with a dataset name followed by a series of operators separated by the pipe character (`|`). Operators flow from left to right, top to bottom, transforming the data at each step.
```kusto
['sample-http-logs']
| where method == "GET" and status == "200"
| summarize count() by bin_auto(_time), ['geo.country']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20where%20method%20%3D%3D%20%5C%22GET%5C%22%20and%20status%20%3D%3D%20%5C%22200%5C%22%5Cn%7C%20summarize%20count\(\)%20by%20bin_auto\(_time\)%2C%20%5B'geo.country'%5D%22%7D)
APL supports a rich set of [tabular operators](/apl/tabular-operators/overview), [scalar functions](/apl/scalar-functions/string-functions), and [aggregation functions](/apl/aggregation-function/statistical-functions) that cover a wide range of use cases from simple filtering to complex joins, time-series analysis, and GenAI-specific computations.
For more information, see [Introduction to APL](/apl/introduction).
## MPL (Metrics Processing Language) [#mpl-metrics-processing-language]
MPL is a query language for querying metrics stored in MetricsDB. It combines a pipeline syntax similar to APL with expressive power suited to metrics workloads like rate calculations, time-window alignment, and tag-based grouping.
Support for MPL is currently in public preview. For more information, see [Feature states](/platform-overview/roadmap#feature-states).
An MPL query starts with a dataset and metric name, then pipes the data through filters and transformations.
```mpl
`otel-demo-metrics`:`go.memory.used`
| where `k8s.deployment.name` == "checkout"
| align to 5m using avg
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%60otel-demo-metrics%60%3A%60go.memory.used%60%20%7C%20where%20%60k8s.deployment.name%60%20%3D%3D%20%5C%22checkout%5C%22%20%7C%20align%20to%205m%20using%20avg%22%2C%22metricsDataset%22%3A%22otel-demo-metrics%22%7D)
MPL supports filtering by tags, mapping values with functions like `rate` and `fill::prev`, aligning data to time windows, grouping by tag dimensions, and computing across multiple metrics.
If you use PromQL, you can easily [translate your existing expressions to MPL](/mpl/migrate-metrics).
For more information, see [Introduction to MPL](/mpl/introduction).
## Write queries [#write-queries]
Write APL and MPL queries in the following ways:
* **Console**: Use the Query tab in the Axiom Console to write and run queries interactively. For more information, see [Query data using Editor](/query-data/query-editor).
* **API**: Run queries programmatically using Axiom API. For more information, see [API reference](/restapi/query).
* **AI**: Use natural language to generate APL queries in Console, or use [MCP Server](/console/intelligence/mcp-server) and [Skills](/console/intelligence/skills) to let AI agents query your data.
---
# Sample queries
Source: https://axiom.co/docs/apl/tutorial
This page shows you how to query your data using APL through a wide range of sample queries. You can try out each example in the [Axiom Playground](https://play.axiom.co/axiom-play-qf1k/query).
For an introduction to APL and to the structure of an APL query, see [Introduction to APL](/apl/introduction).
## Summarize data [#summarize-data]
[summarize](/apl/tabular-operators/summarize-operator) produces a table that aggregates the content of the dataset. Use the [aggregation functions](/apl/aggregation-function/statistical-functions) with the `summarize` operator to produce different fields.
The following query counts events by time bins.
```kusto
['sample-http-logs']
| summarize count() by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20summarize%20count%28%29%20by%20bin_auto%28_time%29%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
The example below summarizes the top 10 GitHub push events by maximum push ID.
```kusto
['github-push-event']
| summarize max_if = maxif(push_id, true) by size
| top 10 by max_if desc
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27github-push-event%27%5D%5Cn%7C%20summarize%20max_if%20%3D%20maxif%28push_id%2C%20true%29%20by%20size%5Cn%7C%20top%2010%20by%20max_if%20desc%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
The example below summarizes the distinct city count by server datacenter.
```kusto
['sample-http-logs']
| summarize cities = dcount(['geo.city']) by server_datacenter
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20summarize%20cities%20%3D%20dcount%28%5B%27geo.city%27%5D%29%20by%20server_datacenter%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
## Tabular operators [#tabular-operators]
### where [#where]
[where](/apl/tabular-operators/where-operator) filters the content of the dataset that meets a condition when executed.
The following query filters the data by `method` and `content_type`:
```kusto
['sample-http-logs']
| where method == "GET" and content_type == "application/octet-stream"
| project method , content_type
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20where%20method%20%3D%3D%20%5C%22GET%5C%22%20and%20content_type%20%3D%3D%20%5C%22application%2Foctet-stream%5C%22%5Cn%7C%20project%20method%20%2C%20content_type%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
### count [#count]
[count](/apl/tabular-operators/count-operator) returns the number of events from the input dataset.
```kusto
['sample-http-logs']
| count
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20count%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
### project [#project]
[project](/apl/tabular-operators/project-operator) selects a subset of fields.
```kusto
['sample-http-logs']
| project content_type, ['geo.country'], method, resp_body_size_bytes, resp_header_size_bytes
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20project%20content_type%2C%20%5B%27geo.country%27%5D%2C%20method%2C%20resp_body_size_bytes%2C%20resp_header_size_bytes%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
### take [#take]
[take](/apl/tabular-operators/take-operator) returns up to the specified number of rows.
```kusto
['sample-http-logs']
| take 100
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20take%20100%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
### limit [#limit]
The `limit` operator is an alias to the `take` operator.
```kusto
['sample-http-logs']
| limit 10
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20limit%2010%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
## Scalar functions [#scalar-functions]
### parse\_json [#parse_json]
[parse\_json](/apl/scalar-functions/string-functions#parse-json) extracts the JSON elements from an array.
```kusto
['sample-http-logs']
| project parsed_json = parse_json( "config_jsonified_metrics")
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20project%20parsed_json%20%3D%20parse_json%28%20%5C%22config_jsonified_metrics%5C%22%29%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
### replace\_string [#replace_string]
[replace\_string](/apl/scalar-functions/string-functions#parse-json) replaces all string matches with another string.
```kusto
['sample-http-logs']
| extend replaced_string = replace_string( "creator", "method", "machala" )
| project replaced_string
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20extend%20replaced_string%20%3D%20replace_string%28%20%5C%22creator%5C%22%2C%20%5C%22method%5C%22%2C%20%5C%22machala%5C%22%20%29%5Cn%7C%20project%20replaced_string%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
### split [#split]
[split](/apl/scalar-functions/string-functions#split) splits a given string according to a given delimiter and returns a string array.
```kusto
['sample-http-logs']
| project split_str = split("method_content_metrics", "_")
| take 20
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20project%20split_str%20%3D%20split%28%5C%22method_content_metrics%5C%22%2C%20%5C%22_%5C%22%29%5Cn%7C%20take%2020%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
### strcat\_delim [#strcat_delim]
[strcat\_delim](/apl/scalar-functions/string-functions#strcat-delim) concatenates a string array into a string with a given delimiter.
```kusto
['sample-http-logs']
| project strcat = strcat_delim(":", ['geo.city'], resp_body_size_bytes)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20project%20strcat%20%3D%20strcat_delim%28%5C%22%3A%5C%22%2C%20%5B%27geo.city%27%5D%2C%20resp_body_size_bytes%29%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
### indexof [#indexof]
[indexof](/apl/scalar-functions/string-functions#indexof) reports the zero-based index of the first occurrence of a specified string within the input string.
```kusto
['sample-http-logs']
| extend based_index = indexof( ['geo.country'], content_type, 45, 60, resp_body_size_bytes ), specified_time = bin(resp_header_size_bytes, 30)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20extend%20based_index%20%3D%20%20indexof%28%20%5B%27geo.country%27%5D%2C%20content_type%2C%2045%2C%2060%2C%20resp_body_size_bytes%20%29%2C%20specified_time%20%3D%20bin%28resp_header_size_bytes%2C%2030%29%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
## Regex examples [#regex-examples]
**Remove leading characters**
```kusto
['sample-http-logs']
| project remove_cutset = trim_start_regex("[^a-zA-Z]", content_type )
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20project%20remove_cutset%20%3D%20trim_start_regex%28%5C%22%5B%5Ea-zA-Z%5D%5C%22%2C%20content_type%20%29%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Find logs from a city**
```kusto
['sample-http-logs']
| where tostring(geo.city) matches regex "^Camaquã$"
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20where%20tostring%28%5B%27geo.city%27%5D%29%20matches%20regex%20%5C%22%5ECamaqu%C3%A3%24%5C%22%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Identify logs from a user agent**
```kusto
['sample-http-logs']
| where tostring(user_agent) matches regex "Mozilla/5.0"
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20where%20tostring%28user_agent%29%20matches%20regex%20%5C%22Mozilla%2F5.0%5C%22%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Find logs with response body size in a certain range**
```kusto
['sample-http-logs']
| where toint(resp_body_size_bytes) >= 4000 and toint(resp_body_size_bytes) <= 5000
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20where%20toint%28resp_body_size_bytes%29%20%3E%3D%204000%20and%20toint%28resp_body_size_bytes%29%20%3C%3D%205000%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Find logs with user agents containing Windows NT**
```kusto
['sample-http-logs']
| where tostring(user_agent) matches regex @"Windows NT [\d\.]+"
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?qid=m8yNkSVVjGq-s0z19c)
**Find logs with specific response header size**
```kusto
['sample-http-logs']
| where toint(resp_header_size_bytes) == 31
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20where%20toint%28resp_header_size_bytes%29%20%3D%3D%2031%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Find logs with specific request duration**
```kusto
['sample-http-logs']
| where toreal(req_duration_ms) < 1
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20where%20toreal%28req_duration_ms%29%20%3C%201%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Find logs where TLS is enabled and method is POST**
```kusto
['sample-http-logs']
| where tostring(is_tls) == "true" and tostring(method) == "POST"
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20where%20tostring%28is_tls%29%20%3D%3D%20%5C%22true%5C%22%20and%20tostring%28method%29%20%3D%3D%20%5C%22POST%5C%22%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
## Array functions [#array-functions]
### array\_concat [#array_concat]
[array\_concat](/apl/scalar-functions/array-functions#array_concat) concatenates a number of dynamic arrays to a single array.
```kusto
['sample-http-logs']
| extend concatenate = array_concat( dynamic([5,4,3,87,45,2,3,45]))
| project concatenate
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20extend%20concatenate%20%3D%20array_concat%28%20dynamic%28%5B5%2C4%2C3%2C87%2C45%2C2%2C3%2C45%5D%29%29%5Cn%7C%20project%20concatenate%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
### array\_sum [#array_sum]
[array\_sum](/apl/scalar-functions/array-functions#array-sum) calculates the sum of elements in a dynamic array.
```kusto
['sample-http-logs']
| extend summary_array=dynamic([1,2,3,4])
| project summary_array=array_sum(summary_array)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20extend%20summary_array%3Ddynamic%28%5B1%2C2%2C3%2C4%5D%29%5Cn%7C%20project%20summary_array%3Darray_sum%28summary_array%29%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
## Conversion functions [#conversion-functions]
### todatetime [#todatetime]
[todatetime](/apl/scalar-functions/conversion-functions#todatetime) converts input to datetime scalar.
```kusto
['sample-http-logs']
| extend dated_time = todatetime("2026-08-16")
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20extend%20dated_time%20%3D%20todatetime%28%5C%222026-08-16%5C%22%29%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
### dynamic\_to\_json [#dynamic_to_json]
[dynamic\_to\_json](/apl/scalar-functions/conversion-functions#dynamic-to-json) converts a scalar value of type dynamic to a canonical string representation.
```kusto
['sample-http-logs']
| extend dynamic_string = dynamic_to_json(dynamic([10,20,30,40 ]))
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20extend%20dynamic_string%20%3D%20dynamic_to_json%28dynamic%28%5B10%2C20%2C30%2C40%20%5D%29%29%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
## Scalar operators [#scalar-operators]
APL supports a wide range of scalar operators:
* [String operators](/apl/scalar-operators/string-operators)
* [Logical operators](/apl/scalar-operators/logical-operators)
* [Numerical operators](/apl/scalar-operators/numerical-operators)
### contains [#contains]
The query below uses the `contains` operator to find the strings that contain the string `-bot` and `[bot]`:
```kusto
['github-issue-comment-event']
| extend bot = actor contains "-bot" or actor contains "[bot]"
| where bot == true
| summarize count() by bin_auto(_time), actor
| take 20
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27github-issue-comment-event%27%5D%5Cn%7C%20extend%20bot%20%3D%20actor%20contains%20%5C%22-bot%5C%22%20or%20actor%20contains%20%5C%22%5Bbot%5D%5C%22%5Cn%7C%20where%20bot%20%3D%3D%20true%5Cn%7C%20summarize%20count%28%29%20by%20bin_auto%28_time%29%2C%20actor%5Cn%7C%20take%2020%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
```kusto
['sample-http-logs']
| extend user_status = status contains "200" , agent_flow = user_agent contains "(Windows NT 6.4; AppleWebKit/537.36 Chrome/41.0.2225.0 Safari/537.36"
| where user_status == true
| summarize count() by bin_auto(_time), status
| take 15
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20extend%20user_status%20%3D%20status%20contains%20%5C%22200%5C%22%20%2C%20agent_flow%20%3D%20user_agent%20contains%20%5C%22%28Windows%20NT%206.4%3B%20AppleWebKit%2F537.36%20Chrome%2F41.0.2225.0%20Safari%2F537.36%5C%22%5Cn%7C%20where%20user_status%20%3D%3D%20true%5Cn%7C%20summarize%20count%28%29%20by%20bin_auto%28_time%29%2C%20status%5Cn%7C%20take%2015%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
## Hash functions [#hash-functions]
* [hash\_md5](/apl/scalar-functions/hash-functions#hash-md5) returns an MD5 hash value for the input value.
* [hash\_sha256](/apl/scalar-functions/hash-functions#hash-sha256) returns a sha256 hash value for the input value.
* [hash\_sha1](/apl/scalar-functions/hash-functions#hash-sha1) returns a sha1 hash value for the input value.
```kusto
['sample-http-logs']
| extend sha_256 = hash_md5( "resp_header_size_bytes" ), sha_1 = hash_sha1( content_type), md5 = hash_md5( method), sha512 = hash_sha512( "resp_header_size_bytes" )
| project sha_256, sha_1, md5, sha512
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20extend%20sha_256%20%3D%20hash_md5%28%20%5C%22resp_header_size_bytes%5C%22%20%29%2C%20sha_1%20%3D%20hash_sha1%28%20content_type%29%2C%20md5%20%3D%20hash_md5%28%20method%29%2C%20sha512%20%3D%20hash_sha512%28%20%5C%22resp_header_size_bytes%5C%22%20%29%5Cn%7C%20project%20sha_256%2C%20sha_1%2C%20md5%2C%20sha512%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
## Rounding functions [#rounding-functions]
* [floor()](/apl/scalar-functions/rounding-functions#floor) calculates the largest integer less than, or equal to, the specified numeric expression.
* [ceiling()](/apl/scalar-functions/rounding-functions#ceiling) calculates the smallest integer greater than, or equal to, the specified numeric expression.
* [bin()](/apl/scalar-functions/rounding-functions#bin) rounds values down to an integer multiple of a given bin size.
```kusto
['sample-http-logs']
| extend largest_integer_less = floor( resp_header_size_bytes ), smallest_integer_greater = ceiling( req_duration_ms ), integer_multiple = bin( resp_body_size_bytes, 5 )
| project largest_integer_less, smallest_integer_greater, integer_multiple
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20extend%20largest_integer_less%20%3D%20floor%28%20resp_header_size_bytes%20%29%2C%20smallest_integer_greater%20%3D%20ceiling%28%20req_duration_ms%20%29%2C%20integer_multiple%20%3D%20bin%28%20resp_body_size_bytes%2C%205%20%29%5Cn%7C%20project%20largest_integer_less%2C%20smallest_integer_greater%2C%20integer_multiple%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Truncate decimals using round function**
```kusto
['sample-http-logs']
| project rounded_value = round(req_duration_ms, 2)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20project%20rounded_value%20%3D%20round%28req_duration_ms%2C%202%29%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Truncate decimals using floor function**
```kusto
['sample-http-logs']
| project floor_value = floor(resp_body_size_bytes), ceiling_value = ceiling(req_duration_ms)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20project%20floor_value%20%3D%20floor%28resp_body_size_bytes%29%2C%20ceiling_value%20%3D%20ceiling%28req_duration_ms%29%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
## Other examples [#other-examples]
**List all unique groups**
```kusto
['sample-http-logs']
| distinct ['id'], is_tls
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20distinct%20%5B'id'%5D%2C%20is_tls%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Count of all events per service**
```kusto
['sample-http-logs']
| summarize Count = count() by server_datacenter
| order by Count desc
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20summarize%20Count%20%3D%20count%28%29%20by%20server_datacenter%5Cn%7C%20order%20by%20Count%20desc%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Change the time clause**
```kusto
['github-issues-event']
| where _time == ago(1m)
| summarize count(), sum(['milestone.number']) by _time=bin(_time, 1m)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27github-issues-event%27%5D%5Cn%7C%20where%20_time%20%3D%3D%20ago%281m%29%5Cn%7C%20summarize%20count%28%29%2C%20sum%28%5B%27milestone.number%27%5D%29%20by%20_time%3Dbin%28_time%2C%201m%29%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**HTTP 5xx responses for the last 7 days, one bar per day**
```kusto
['sample-http-logs']
| where _time > ago(7d)
| where req_duration_ms >= 5 and req_duration_ms < 6
| summarize count(), histogram(resp_header_size_bytes, 20) by bin(_time, 1d)
| order by _time desc
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20where%20_time%20%3E%20ago\(7d\)%20%7C%20where%20req_duration_ms%20%3E%3D%205%20and%20req_duration_ms%20%3C%206%20%7C%20summarize%20count\(\)%2C%20histogram\(resp_header_size_bytes%2C%2020\)%20by%20bin\(_time%2C%201d\)%20%7C%20order%20by%20_time%20desc%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%227d%22%7D%7D)
**Implement a remapper on remote address logs**
```kusto
['sample-http-logs']
| extend RemappedStatus = case(req_duration_ms >= 0.57, "new data", resp_body_size_bytes >= 1000, "size bytes", resp_header_size_bytes == 40, "header values", "doesntmatch")
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20extend%20RemappedStatus%20%3D%20case%28req_duration_ms%20%3E%3D%200.57%2C%20%5C%22new%20data%5C%22%2C%20resp_body_size_bytes%20%3E%3D%201000%2C%20%5C%22size%20bytes%5C%22%2C%20resp_header_size_bytes%20%3D%3D%2040%2C%20%5C%22header%20values%5C%22%2C%20%5C%22doesntmatch%5C%22%29%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Advanced aggregations**
```kusto
['sample-http-logs']
| extend prospect = ['geo.city'] contains "Okayama" or uri contains "/api/v1/messages/back"
| extend possibility = server_datacenter contains "GRU" or status contains "301"
| summarize count(), topk( user_agent, 6 ) by bin(_time, 10d), ['geo.country']
| take 4
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20extend%20prospect%20%3D%20%5B%27geo.city%27%5D%20contains%20%5C%22Okayama%5C%22%20or%20uri%20contains%20%5C%22%2Fapi%2Fv1%2Fmessages%2Fback%5C%22%5Cn%7C%20extend%20possibility%20%3D%20server_datacenter%20contains%20%5C%22GRU%5C%22%20or%20status%20contains%20%5C%22301%5C%22%5Cn%7C%20summarize%20count%28%29%2C%20topk%28%20user_agent%2C%206%20%29%20by%20bin%28_time%2C%2010d%29%2C%20%5B%27geo.country%27%5D%5Cn%7C%20take%204%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Search map fields**
```kusto
['otel-demo-traces']
| where isnotnull( ['attributes.custom'])
| extend extra = tostring(['attributes.custom'])
| search extra:"0PUK6V6EV0"
| project _time, trace_id, name, ['attributes.custom']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%5Cn%7C%20where%20isnotnull%28%20%5B'attributes.custom'%5D%29%5Cn%7C%20extend%20extra%20%3D%20tostring%28%5B'attributes.custom'%5D%29%5Cn%7C%20search%20extra%3A%5C%220PUK6V6EV0%5C%22%5Cn%7C%20project%20_time%2C%20trace_id%2C%20name%2C%20%5B'attributes.custom'%5D%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Configure processing rules**
```kusto
['sample-http-logs']
| where _sysTime > ago(1d)
| summarize count() by method
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20where%20_sysTime%20%3E%20ago%281d%29%5Cn%7C%20summarize%20count%28%29%20by%20method%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%221d%22%7D%7D)
**Return different values based on the evaluation of a condition**
```kusto
['sample-http-logs']
| extend MemoryUsageStatus = iff(req_duration_ms > 10000, "Highest", "Normal")
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20extend%20MemoryUsageStatus%20%3D%20iff%28req_duration_ms%20%3E%2010000%2C%20%27Highest%27%2C%20%27Normal%27%29%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Working with different operators**
```kusto
['hn']
| extend superman = text contains "superman" or title contains "superman"
| extend batman = text contains "batman" or title contains "batman"
| extend hero = case(
superman and batman, "both",
superman, "superman ", // spaces change the color
batman, "batman ",
"none")
| where (superman or batman) and not (batman and superman)
| summarize count(), topk(type, 3) by bin(_time, 30d), hero
| take 10
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27hn%27%5D%5Cn%7C%20extend%20superman%20%3D%20text%20contains%20%5C%22superman%5C%22%20or%20title%20contains%20%5C%22superman%5C%22%5Cn%7C%20extend%20batman%20%3D%20text%20contains%20%5C%22batman%5C%22%20or%20title%20contains%20%5C%22batman%5C%22%5Cn%7C%20extend%20hero%20%3D%20case%28%5Cn%20%20%20%20superman%20and%20batman%2C%20%5C%22both%5C%22%2C%5Cn%20%20%20%20superman%2C%20%5C%22superman%20%20%20%5C%22%2C%20%2F%2F%20spaces%20change%20the%20color%5Cn%20%20%20%20batman%2C%20%5C%22batman%20%20%20%20%20%20%20%5C%22%2C%5Cn%20%20%20%20%5C%22none%5C%22%29%5Cn%7C%20where%20%28superman%20or%20batman%29%20and%20not%20%28batman%20and%20superman%29%5Cn%7C%20summarize%20count%28%29%2C%20topk%28type%2C%203%29%20by%20bin%28_time%2C%2030d%29%2C%20hero%5Cn%7C%20take%2010%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
```kusto
['sample-http-logs']
| summarize flow = dcount( content_type) by ['geo.country']
| take 50
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20summarize%20flow%20%3D%20dcount%28%20content_type%29%20by%20%5B%27geo.country%27%5D%5Cn%7C%20take%2050%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Get the JSON into a property bag using parse-json**
```kusto
example
| where isnotnull(log)
| extend parsed_log = parse_json(log)
| project service, parsed_log.level, parsed_log.message
```
**Get average response using project-keep**
```kusto
['sample-http-logs']
| where ['geo.country'] == "United States" or ['id'] == 'b2b1f597-0385-4fed-a911-140facb757ef'
| extend systematic_view = ceiling( resp_header_size_bytes )
| extend resp_avg = cos( resp_body_size_bytes )
| project-away systematic_view
| project-keep resp_avg
| take 5
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20where%20%5B'geo.country'%5D%20%3D%3D%20%5C%22United%20States%5C%22%20or%20%5B'id'%5D%20%3D%3D%20%5C%22b2b1f597-0385-4fed-a911-140facb757ef%5C%22%5Cn%7C%20extend%20systematic_view%20%3D%20ceiling%28%20resp_header_size_bytes%20%29%5Cn%7C%20extend%20resp_avg%20%3D%20cos%28%20resp_body_size_bytes%20%29%5Cn%7C%20project-away%20systematic_view%5Cn%7C%20project-keep%20resp_avg%5Cn%7C%20take%205%22%7D)
**Combine multiple percentiles into a single chart**
```kusto
['sample-http-logs']
| summarize percentiles_array(req_duration_ms, 50, 75, 90) by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20summarize%20percentiles_array\(req_duration_ms%2C%2050%2C%2075%2C%2090\)%20by%20bin_auto\(_time\)%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Combine mathematical functions**
```kusto
['sample-http-logs']
| extend tangent = tan( req_duration_ms ), cosine = cos( resp_header_size_bytes ), absolute_input = abs( req_duration_ms ), sine = sin( resp_header_size_bytes ), power_factor = pow( req_duration_ms, 4)
| extend angle_pi = degrees( resp_body_size_bytes ), pie = pi()
| project tangent, cosine, absolute_input, angle_pi, pie, sine, power_factor
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20extend%20tangent%20%3D%20tan%28%20req_duration_ms%20%29%2C%20cosine%20%3D%20cos%28%20resp_header_size_bytes%20%29%2C%20absolute_input%20%3D%20abs%28%20req_duration_ms%20%29%2C%20sine%20%3D%20sin%28%20resp_header_size_bytes%20%29%2C%20power_factor%20%3D%20pow%28%20req_duration_ms%2C%204%29%5Cn%7C%20extend%20angle_pi%20%3D%20degrees%28%20resp_body_size_bytes%20%29%2C%20pie%20%3D%20pi%28%29%5Cn%7C%20project%20tangent%2C%20cosine%2C%20absolute_input%2C%20angle_pi%2C%20pie%2C%20sine%2C%20power_factor%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
```kusto
['github-issues-event']
| where actor !endswith "[bot]"
| where repo startswith "kubernetes/"
| where action == "opened"
| summarize count() by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27github-issues-event%27%5D%5Cn%7C%20where%20actor%20%21endswith%20%5C%22%5Bbot%5D%5C%22%5Cn%7C%20where%20repo%20startswith%20%5C%22kubernetes%2F%5C%22%5Cn%7C%20where%20action%20%3D%3D%20%5C%22opened%5C%22%5Cn%7C%20summarize%20count%28%29%20by%20bin_auto%28_time%29%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Change global configuration attributes**
```kusto
['sample-http-logs']
| extend status = coalesce(status, "info")
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20extend%20status%20%3D%20coalesce\(status%2C%20%5C%22info%5C%22\)%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Set defualt value on event field**
```kusto
['sample-http-logs']
| project status = case(
isnotnull(status) and status != "", content_type, // use the contenttype if it’s not null and not an empty string
"info" // default value
)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20project%20status%20%3D%20case\(isnotnull\(status\)%20and%20status%20!%3D%20%5C%22%5C%22%2C%20content_type%2C%20%5C%22info%5C%22\)%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
**Extract nested payment amount from custom attributes map field**
```kusto
['otel-demo-traces']
| extend amount = ['attributes.custom']['app.payment.amount']
| where isnotnull( amount)
| project _time, trace_id, name, amount, ['attributes.custom']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20extend%20amount%20%3D%20%5B'attributes.custom'%5D%5B'app.payment.amount'%5D%20%7C%20where%20isnotnull\(%20amount\)%20%7C%20project%20_time%2C%20trace_id%2C%20name%2C%20amount%2C%20%5B'attributes.custom'%5D%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2290d%22%7D%7D)
**Filtering GitHub issues by label identifier**
```kusto
['github-issues-event']
| extend data = tostring(labels)
| where labels contains "d73a4a"
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'github-issues-event'%5D%20%7C%20extend%20data%20%3D%20tostring\(labels\)%20%7C%20where%20labels%20contains%20'd73a4a'%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2290d%22%7D%7D)
**Aggregate trace counts by HTTP method attribute in custom map**
```kusto
['otel-demo-traces']
| extend httpFlavor = tostring(['attributes.custom'])
| summarize Count=count() by ['attributes.http.method']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20extend%20httpFlavor%20%3D%20tostring\(%5B'attributes.custom'%5D\)%20%7C%20summarize%20Count%3Dcount\(\)%20by%20%5B'attributes.http.method'%5D%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2290d%22%7D%7D)
---
# Create annotation
Source: https://axiom.co/docs/restapi/endpoints/createAnnotation
```http
POST https://api.axiom.co/v2/annotations
```
Creates an annotation on one or more existing datasets. If you omit `time`, Axiom uses the time of the request. `time` can't be in the future.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
Content type: `application/json` (required)
- `datasets` (array of string; required): array of dataset names for which the annotation appears on charts
- `description` (string; length ≤ 512): Explanation of the event the annotation marks on the charts
- `endTime` (string (date-time)): End time of the annotation
- `time` (string (date-time)): Time the annotation marks on the charts. If you don't include this field, Axiom assigns the time of the API request to the annotation.
- `title` (string; length ≤ 256): Summary of the annotation that appears on the charts
- `type` (string; length ≤ 256; pattern `^[a-z0-9-]+$`; required): Type of the event marked by the annotation. Use only alphanumeric characters or hyphens. For example, "production-deployment".
- `url` (string; length ≤ 512): URL relevant for the event marked by the annotation. For example, link to GitHub pull request.
## Responses
### 201: Created annotation.
Content type: `application/json`
- `datasets` (array of string; length ≥ 1; items ≥ 1; required): array of dataset names for which the annotation appears on charts
- `description` (string; length ≤ 512): Explanation of the event the annotation marks on the charts
- `endTime` (string (date-time); nullable): End time of the annotation
- `id` (string; required)
- `time` (string (date-time); required): Time the annotation marks on the charts. If you don't include this field, Axiom assigns the time of the API request to the annotation.
- `title` (string; length ≤ 256): Summary of the annotation that appears on the charts
- `type` (string; length ≤ 256; pattern `^[a-z0-9-]+$`; required): Type of the event marked by the annotation. Use only alphanumeric characters or hyphens. For example, "production-deployment".
- `url` (string; length ≤ 512): URL relevant for the event marked by the annotation. For example, link to GitHub pull request.
### 400: Invalid annotation, for example an unknown dataset, a `time` in the future, or an `endTime` before `time`.
---
# Create dashboard
Source: https://axiom.co/docs/restapi/endpoints/createDashboard
```http
POST https://api.axiom.co/v2/dashboards
```
Creates a dashboard and generates a `uid` if you don't set one. If a dashboard with the `uid` already exists, updates it and returns `200`, which requires the current `version` or `overwrite: true`.
For the structure of the `dashboard` field, see [Dashboard JSON](/restapi/dashboard-json). To validate a dashboard document before you send it, use the JSON Schema at `https://axiom.co/docs/schemas/dashboard.json`.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
Content type: `application/json` (required)
- `dashboard` (`DashboardDocument`; required)
- `labelIds` (array of string; items ≤ 500): Existing label IDs; replaces assignments when supplied, clears with [], and preserves them when omitted or null.
- `message` (string)
- `overwrite` (boolean; default `false`)
- `uid` (string): Stable external dashboard identifier (org-scoped unique).
- `version` (integer (int64)): Required for updates when overwrite is false.
## Responses
### 200: Updated dashboard
Content type: `application/json`
- `dashboard` (`DashboardResource`; required)
- `overwritten` (boolean)
- `status` (string; one of `"created"`, `"updated"`; required)
### 201: Created dashboard
Content type: `application/json`
- `dashboard` (`DashboardResource`; required)
- `overwritten` (boolean)
- `status` (string; one of `"created"`, `"updated"`; required)
### 400: Invalid dashboard payload
Content type: `application/json`
- `code` (string; required)
- `currentVersion` (integer (int64))
- `message` (string; required)
- `reason` (string)
- `uid` (string)
### 409: Dashboard already exists
Content type: `application/json`
- `code` (string; required)
- `currentVersion` (integer (int64))
- `message` (string; required)
- `reason` (string)
- `uid` (string)
### 412: Version conflict
Content type: `application/json`
- `code` (string; required)
- `currentVersion` (integer (int64))
- `message` (string; required)
- `reason` (string)
- `uid` (string)
## Schemas
### DashboardDocument
Same as `Dashboard`.
### DashboardResource
Object.
- `createdAt` (string (date-time); nullable): Creation time, present only for managed dashboards.
- `createdBy` (string; nullable): Creator, present only for managed dashboards.
- `dashboard` (`DashboardDocument`; required)
- `id` (string; required)
- `labelIds` (array of string; required)
- `labelNames` (array of string): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`)
- `type` (string; one of `"managed"`, `"integration"`; required): Managed dashboards are saved documents; integration dashboards are read-only and generated for matching datasets.
- `uid` (string; required): Managed dashboard UID, or stable integration dashboard ID for read requests.
- `updatedAt` (string (date-time); nullable): Last save time, present only for managed dashboards.
- `updatedBy` (string; nullable): Last editor, present only for managed dashboards.
- `updatedByAgent` (boolean): true when the last save came from the MCP server
- `version` (integer (int64); nullable): Save version, present only for managed dashboards.
### Dashboard
Object. Other fields aren't allowed.
- `name` (string; length 1–100; required)
- `owner` (string; required): User ID of the dashboard owner. Use `X-AXIOM-EVERYONE` to make the dashboard accessible to all users in the organization.
- `description` (string; length ≤ 1000)
- `charts` (array of `Chart`; items ≤ 200; required)
- `layout` (array of `LayoutItem`; items ≤ 200; required)
- `sections` (array of `Section`; items ≤ 1000)
- `refreshTime` (integer; one of `0`, `15`, `60`, `300`; required)
- `schemaVersion` (integer; one of `2`; required)
- `against` (string; one of `"-1h"`, `"-3h"`, `"-6h"`, `"-12h"`, `"-1d"`, `"-3d"`, `"-7d"`, `"-1w"`, `"-2w"`, `"-3w"`, `"-30d"`, `"-60d"`, `"-90d"`): Relative time comparison offset. Compares the current time window against a previous period offset by this duration. Mutually exclusive with `againstTimestamp` — setting one clears the other. Use an empty string or omit to disable comparison.
- `againstTimestamp` (string; length ≤ 100): Absolute or relative timestamp to compare against. Mutually exclusive with `against` — setting one clears the other. Accepts ISO 8601, `now-{duration}` (e.g. `now-1h`), or epoch milliseconds as a string.
- `timeWindowStart` (string; length 1–100; required): Start of the dashboard time range. Use `qr-now-{duration}` for a quick range relative to now, where duration is a number followed by `s` (seconds), `m` (minutes), `h` (hours), `d` (days), or `w` (weeks). Examples: `qr-now-5m`, `qr-now-1h`, `qr-now-7d`. Alternatively, use a Unix epoch millisecond timestamp as a string (e.g. `1704067200000`).
- `timeWindowEnd` (string; length 1–100; required): End of the dashboard time range. Use `qr-now` for a rolling window that tracks the current time (pair with a `qr-now-{duration}` start), or a Unix epoch millisecond timestamp as a string (e.g. `1704153600000`).
- `uid` (string; pattern `^[A-Za-z0-9_-]{1,128}$`): Optional dashboard UID. Must contain only letters, numbers, underscores, or hyphens, with length 1-128 when provided.
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### Chart
One of the following, selected by `type`:
- `TimeSeriesChart` (`type`: `"TimeSeries"`)
- `HeatmapChart` (`type`: `"Heatmap"`)
- `LogStreamChart` (`type`: `"LogStream"`)
- `PieChart` (`type`: `"Pie"`)
- `ScatterChart` (`type`: `"Scatter"`)
- `TableChart` (`type`: `"Table"`)
- `TopKChart` (`type`: `"TopK"`)
- `StatisticChart` (`type`: `"Statistic"`)
- `GaugeChart` (`type`: `"Gauge"`)
- `NoteChart` (`type`: `"Note"`)
- `MonitorListChart` (`type`: `"MonitorList"`)
- `SmartFilterChart` (`type`: `"SmartFilter"`)
- `SpacerChart` (`type`: `"Spacer"`)
- `VisualizeChart` (`type`: `"Visualize"`)
### LayoutItem
Object. Other fields aren't allowed.
- `i` (string; length 1–200; required)
- `x` (integer; value 0–11; required)
- `y` (number; value ≥ 0; nullable; required)
- `w` (integer; value 1–12; required)
- `h` (number; value 0.5–100; required)
- `minW` (integer; value 1–12)
- `minH` (number; value 0.5–100)
- `maxW` (integer; value 1–12)
- `maxH` (integer; value 1–100)
- `static` (boolean)
### Section
Object. Other fields aren't allowed.
- `id` (string (uuid); required)
- `title` (string; length 1–200; required)
- `defaultCollapsed` (boolean)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
### TimeSeriesChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"TimeSeries"`; required)
- `name` (string; length 1–500)
- `query` (`TimeSeriesChartQuery`; required)
### HeatmapChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Heatmap"`; required)
- `name` (string; length 1–500)
- `query` (`HeatmapChartQuery`; required)
- `colorScheme` (string; one of `"Blue"`, `"Orange"`, `"Red"`, `"Purple"`, `"Teal"`, `"Yellow"`, `"Green"`, `"Pink"`, `"Grey"`, `"Brown"`)
### LogStreamChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"LogStream"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `tableSettings` (`TableSettings`)
### PieChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Pie"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### ScatterChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Scatter"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### TableChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Table"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `tableSettings` (`TableSettings`)
### TopKChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"TopK"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### StatisticChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Statistic"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `colorScheme` (string; one of `"Blue"`, `"Orange"`, `"Red"`, `"Purple"`, `"Teal"`, `"Yellow"`, `"Green"`, `"Pink"`, `"Grey"`, `"Brown"`)
- `customUnits` (string; length ≤ 200)
- `showChart` (one of boolean, string)
- `hideValue` (boolean)
- `chartHeight` (one of string; length ≤ 100, number)
- `errorThreshold` (string; one of `"Above"`, `"AboveOrEqual"`, `"Below"`, `"BelowOrEqual"`, `"AboveOrBelow"`)
- `errorThresholdValue` (string; length ≤ 100)
- `warningThreshold` (string; one of `"Above"`, `"AboveOrEqual"`, `"Below"`, `"BelowOrEqual"`, `"AboveOrBelow"`)
- `warningThresholdValue` (string; length ≤ 100)
- `roundTo` (integer; value 0–10)
- `invertTheme` (boolean)
- `background` (string; length ≤ 200)
- `textColor` (string; length ≤ 200)
- `labelColor` (string; length ≤ 200)
- `chartFillColor` (string; length ≤ 200)
- `okColorProps` (`StatisticChartColorProps`)
- `warningColorProps` (`StatisticChartColorProps`)
- `errorColorProps` (`StatisticChartColorProps`)
### GaugeChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Gauge"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `segments` (array of `GaugeChartSegment`; items 1–100; required)
- `colorScale` (string; one of `"green-to-red"`, `"red-to-green"`)
- `showRing` (boolean)
- `labelMode` (string; one of `"none"`, `"boundaries"`, `"intervals"`)
- `showSparkline` (boolean)
- `scaleToTimeRange` (boolean)
- `scaleBaseDurationMs` (number; value > 0)
- `customUnits` (string; length ≤ 200)
### NoteChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Note"`; required)
- `text` (string; length 1–100000; required)
- `variant` (string; one of `""`, `"default"`, `"plain"`; nullable)
### MonitorListChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"MonitorList"`; required)
- `name` (string; length 1–500)
- `selectedMonitors` (array of string; length 1–200; items 1–200; required)
- `columns` (`MonitorListColumns`; required)
### SmartFilterChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"SmartFilter"`; required)
- `name` (string; length 1–500)
- `filters` (array of `SmartFilterConfig`; items 1–50; required)
- `logo` (string; length ≤ 2000)
- `logoDark` (string; length ≤ 2000)
### SpacerChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Spacer"`; required)
- `name` (string; length 1–500)
- `variant` (string; one of `"transparent"`, `"dashed"`, `"solid"`)
### VisualizeChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Visualize"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `visualization` (`VisualizeConfiguration`; required)
### TimeSeriesChartQuery
One of the following:
- `TimeSeriesNonMetricsAplQuery`
- `TimeSeriesNativeMplQuery`
### HeatmapChartQuery
One of the following:
- `HeatmapNonMetricsAplQuery`
- `HeatmapNativeMplQuery`
### SimpleChartQuery
One of the following:
- `SimpleNonMetricsAplQuery`
- `SimpleNativeMplQuery`
### TableSettings
Object. Other fields aren't allowed.
- `columns` (array of `ColumnSetting`; items ≤ 500)
- `settings` (`DatasetStreamSettings`)
### StatisticChartColorProps
Object. Other fields aren't allowed.
- `background` (string; length ≤ 200)
- `chartFillColor` (string; length ≤ 200)
- `labelColor` (string; length ≤ 200)
- `textColor` (string; length ≤ 200)
### GaugeChartSegment
Object. Other fields aren't allowed.
- `from` (number; required)
- `to` (number; required)
### MonitorListColumns
Object. Other fields aren't allowed.
- `status` (boolean; required)
- `history` (boolean; required)
- `dataset` (boolean; required)
- `type` (boolean; required)
- `notifiers` (boolean; required)
### SmartFilterConfig
One of the following:
- `SmartFilterSearch`
- `SmartFilterSelect`
### VisualizeConfiguration
One of the following, selected by `type`:
- `ScatterVisualization` (`type`: `"scatter"`)
- `BarVisualization` (`type`: `"bar"`)
- `HorizontalBarVisualization` (`type`: `"horizontalBar"`)
- `HistogramVisualization` (`type`: `"histogram"`)
- `FrequencyBarVisualization` (`type`: `"frequencyBar"`)
- `VisualizeHeatmap` (`type`: `"heatmap"`)
### TimeSeriesNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
- `queryOptions` (`TimeSeriesQueryOptions`)
### TimeSeriesNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
- `queryOptions` (`TimeSeriesQueryOptions`)
### HeatmapNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
- `queryOptions` (`HeatmapQueryOptions`)
### HeatmapNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
- `queryOptions` (`HeatmapQueryOptions`)
### SimpleNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
### SimpleNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
### ColumnSetting
One of the following:
- string; length ≤ 500
- `AdvancedColumnSetting`
### DatasetStreamSettings
Object. Other fields aren't allowed.
- `fontSize` (string; length ≤ 20; pattern `^\d+px$`)
- `highlightSeverity` (boolean)
- `showRaw` (boolean)
- `showEvent` (boolean)
- `showTimestamp` (boolean)
- `wrapLines` (boolean)
- `hideNulls` (boolean)
- `fitColumns` (boolean)
### SmartFilterSearch
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `type` (string; one of `"search"`; required)
### SmartFilterSelect
One of the following, selected by `selectType`:
- `SmartFilterSelectList` (`selectType`: `"list"`)
- `SmartFilterSelectQuery` (`selectType`: `"query"`)
### ScatterVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"scatter"`; required)
- `bindings` (`ScatterVisualizationBindings`; required)
- `settings` (`ScatterVisualizationSettings`; required)
### BarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"bar"`; required)
- `bindings` (`BarVisualizationBindings`; required)
- `settings` (`VisualizeBarSettings`; required)
### HorizontalBarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"horizontalBar"`; required)
- `bindings` (`HorizontalBarVisualizationBindings`; required)
- `settings` (`VisualizeBarSettings`; required)
### HistogramVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"histogram"`; required)
- `bindings` (`HistogramVisualizationBindings`; required)
- `settings` (`HistogramVisualizationSettings`; required)
### FrequencyBarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"frequencyBar"`; required)
- `bindings` (`FrequencyBarVisualizationBindings`; required)
- `settings` (`FrequencyBarVisualizationSettings`; required)
### VisualizeHeatmap
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"heatmap"`; required)
- `bindings` (`VisualizeHeatmapBindings`; required)
- `settings` (`VisualizeHeatmapSettings`; required)
### TimeSeriesQueryOptions
Object. Other fields aren't allowed.
- `displayNull` (string; one of `"auto"`, `"null"`, `"span"`, `"zero"`, `""`): Controls how empty intervals are rendered in time series charts. `auto` infers from the query, `null` leaves gaps, `span` connects adjacent points, `zero` fills with zero.
- `overlayCharts` (string; one of `"true"`, `"false"`, `""`): When enabled, charts are overlaid on a single chart instead of stacked separately.
- `shownColumns` (string; length ≤ 10000)
- `timeSeriesVariant` (string; one of `"area"`, `"bars"`, `"line"`, `"lines"`, `""`)
- `timeSeriesView` (string; one of `"charts"`, `"resultsTable"`, `"charts|resultsTable"`, `""`)
### HeatmapQueryOptions
Object. Other fields aren't allowed.
- `timeSeriesView` (string; one of `"charts"`, `"resultsTable"`, `"charts|resultsTable"`, `""`)
### AdvancedColumnSetting
Object. Other fields aren't allowed.
- `name` (string; length ≤ 500; required)
- `width` (integer; value > 0, ≤ 9007199254740991)
### SmartFilterSelectList
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `options` (`SmartFilterOptions`)
- `type` (string; one of `"select"`; required)
- `selectType` (string; one of `"list"`; required)
### SmartFilterSelectQuery
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `options` (all of one of array of `SmartFilterOption`; items ≤ 200, string; one of `null`; nullable, string; one of `""`): Pre-defined options merged with the dynamic options returned by `query` at runtime. Typically used to seed a default option (for example an "All" entry with `unset: true`) so the filter has a sensible initial selection before — or independent of — query results.
- `type` (string; one of `"select"`; required)
- `selectType` (string; one of `"query"`; required)
- `query` (`SmartFilterQuery`)
### ScatterVisualizationBindings
Object. Other fields aren't allowed.
- `x` (`VisualizeAxisColumnRef`; required)
- `y` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### ScatterVisualizationSettings
Object. Other fields aren't allowed.
- `colors` (`VisualizeColorSettings`)
- `xAxis` (`VisualizeAxisSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### BarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
- `value` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### VisualizeBarSettings
One of the following:
- `VisualizeStandardAggregationSettings`
- `VisualizePercentileAggregationSettings`
### HorizontalBarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
- `value` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### HistogramVisualizationBindings
Object. Other fields aren't allowed.
- `value` (`VisualizeNumericColumnRef`; required)
### HistogramVisualizationSettings
Object. Other fields aren't allowed.
- `binCount` (integer; value 1–200; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
### FrequencyBarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
### FrequencyBarVisualizationSettings
Object. Other fields aren't allowed.
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
### VisualizeHeatmapBindings
Object. Other fields aren't allowed.
- `x` (`VisualizeCategoricalColumnRef`; required)
- `y` (`VisualizeCategoricalColumnRef`; required)
### VisualizeHeatmapSettings
Object. Other fields aren't allowed.
- `categoryLimit` (integer; value 1–100; required)
### SmartFilterOptions
One of the following:
- array of `SmartFilterOption`; items ≤ 200
- string; one of `null`; nullable
- string; one of `""`
### SmartFilterOption
Object. Other fields aren't allowed.
- `key` (string; length ≤ 500; required)
- `value` (string; length ≤ 10000; required)
- `default` (boolean)
- `unset` (boolean)
### SmartFilterQuery
One of the following:
- `SmartFilterAplQuery`
- `SmartFilterNativeMplQuery`
### VisualizeAxisColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"datetime"`, `"integer"`, `"float"`; required)
### VisualizeNumericColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"integer"`, `"float"`; required)
### VisualizeCategoricalColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"string"`, `"boolean"`; required)
### VisualizeColorSettings
Object. Other fields aren't allowed.
- `palette` (string; one of `"axiom"`, `"polychrome"`; required)
- `assignment` (string; one of `"series-name"`, `"series-order"`; required)
### VisualizeAxisSettings
Object. Other fields aren't allowed.
- `scale` (string; one of `"linear"`, `"log"`; required)
- `range` (string; one of `"fit"`, `"includeZero"`; required)
### VisualizeLegendSettings
Object. Other fields aren't allowed.
- `position` (string; one of `"none"`, `"bottom"`, `"right"`; required)
### VisualizeStandardAggregationSettings
Object. Other fields aren't allowed.
- `aggregation` (string; one of `"avg"`, `"sum"`, `"count"`, `"min"`, `"max"`; required)
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### VisualizePercentileAggregationSettings
Object. Other fields aren't allowed.
- `aggregation` (string; one of `"percentile"`; required)
- `percentile` (number; value 0–100; required)
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### SmartFilterAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required): APL query that returns the list of options for the filter dropdown. The result must contain a `key` column and a `value` column — Axiom interprets each row as a `{ key, value }` pair for an option. Use `distinct` to collapse the source field to unique values, then `project` to expose the `key` and `value` columns.
Example:
```
['dataset-name'] | distinct field_name | project key=field_name, value=field_name
```
### SmartFilterNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required): MPL query that returns the list of options for the filter dropdown. The query must group by exactly one tag — Axiom uses each distinct value of that tag as both the key and the value of an option. Use `align using last` to simplify the query.
Example:
```
dataset:metric | align using last | group by tag using count
```
---
# Create dataset
Source: https://axiom.co/docs/restapi/endpoints/createDataset
```http
POST https://api.axiom.co/v2/datasets
```
Creates a dataset. The `name` must be unique in your organization, and `retentionDays` can't exceed the retention window of your plan. `labelIds` replaces assignments when supplied; [] clears them. Omitted or null `labelIds` preserves assignments on updates and creates an unlabeled resource on creation. IDs must belong to existing labels in your organization and are validated before saving.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `referrer` (query; string): Referrer slug
## Request body
Content type: `application/json` (required)
- `description` (string; default `""`): Dataset description
- `edgeDeployment` (string): Edge deployment of the dataset
- `kind` (string; one of `"otel:metrics:v1"`, `"otel:traces:v1"`, `"otel:logs:v1"`, `"axiom:events:v1"`; default `"axiom:events:v1"`): The kind of the dataset
- `labelIds` (array of string; items ≤ 500): Existing label IDs; replaces assignments when supplied, clears with [], and preserves them when omitted or null.
- `name` (string; required): Dataset unique name
- `retentionDays` (integer): Number of days to retain data in the dataset
- `useRetentionPeriod` (boolean): Ignored. Axiom derives this value from `retentionDays`.
## Responses
### 200: Created dataset.
Content type: `application/json`
- `canWrite` (boolean): Whether this dataset has write access
- `created` (string (date-time); required): The RFC3339-formatted time when the dataset was created.
- `createdByAgent` (boolean): true when the MCP server created this dataset
- `description` (string; required): Dataset description
- `edgeDeployment` (string): Edge deployment of the dataset
- `edgeDeploymentUrl` (string): URL of the edge deployment
- `id` (string; required): Dataset ID
- `kind` (string; one of `"otel:metrics:v1"`, `"otel:traces:v1"`, `"otel:logs:v1"`, `"axiom:events:v1"`; default `"axiom:events:v1"`; required): The kind of the dataset
- `labelIds` (array of string; required): IDs of labels assigned to this dataset.
- `labelNames` (array of string; required): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`): Resolved labels assigned to this dataset.
- `mapFields` (array of string)
- `name` (string; required): Unique dataset name
- `reclaimableFields` (integer (int64)): Number of unused fields a vacuum can reclaim, when the dataset is a vacuum candidate
- `retentionDays` (integer): Number of days to retain data in the dataset
- `sharedByOrg` (string): ID of the org that shared this resource, if it's shared
- `updatedAt` (string (date-time); required): The RFC3339-formatted time when the dataset was last updated.
- `useRetentionPeriod` (boolean): Whether to use the retention period
- `vacuumCandidate` (boolean): Whether the dataset has unused fields that a vacuum can reclaim
- `who` (string; required): Name of the dataset creator
### 400: Invalid or reserved `name`, invalid `kind`, `retentionDays` longer than your plan allows, unsupported `edgeDeployment`, or dataset limit reached.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 409: A dataset with this name already exists.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
## Schemas
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
---
# Create group
Source: https://axiom.co/docs/restapi/endpoints/createGroup
```http
POST https://api.axiom.co/v2/rbac/groups
```
Creates a group whose members get the group's roles. Requires an Enterprise plan or the RBAC add-on. The name must be unique, every role ID must exist, and you can't add yourself as a member.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
The group's name, description, roles, and members
Content type: `application/json` (required)
Defines a group of users for organizational purposes
- `description` (string): Detailed description of the group's purpose and scope
- `isManaged` (boolean; read-only): Whether the group is synced from your identity provider. You can't delete a managed group or change its members.
- `members` (array of string): List of user IDs that are assigned to this group
- `name` (string; required): Unique name identifier for the group
- `roles` (array of string): IDs of the roles assigned to the group. Use a custom role ID or a built-in role ID: `axiom-owner`, `axiom-admin`, `axiom-user`, `axiom-read-only`, or `axiom-none`.
## Responses
### 200: The created group.
Content type: `application/json`
Type: `GroupWithID`
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### GroupWithID
Extends the base Group type to include a unique identifier
All of the following:
- `Group`
- Object with:
- `id` (string; required): Unique identifier for the group
### Group
Defines a group of users for organizational purposes
Object.
- `description` (string): Detailed description of the group's purpose and scope
- `isManaged` (boolean; read-only): Whether the group is synced from your identity provider. You can't delete a managed group or change its members.
- `members` (array of string): List of user IDs that are assigned to this group
- `name` (string; required): Unique name identifier for the group
- `roles` (array of string): IDs of the roles assigned to the group. Use a custom role ID or a built-in role ID: `axiom-owner`, `axiom-admin`, `axiom-user`, `axiom-read-only`, or `axiom-none`.
---
# Create label
Source: https://axiom.co/docs/restapi/endpoints/createLabel
```http
POST https://api.axiom.co/v2/labels
```
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
Content type: `application/json` (required)
- `color` (`LabelColor`)
- `description` (string; length ≤ 512; nullable)
- `name` (string; length 1–128; required)
## Responses
### 201: Created label
Content type: `application/json`
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
- `resources_count` (`LabelResourcesCount`; required)
### 400: Invalid label payload
### 409: A label with this name already exists
## Schemas
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
### LabelResourcesCount
Object.
- `dashboards` (integer (int64); required)
- `datasets` (integer (int64); required)
- `monitors` (integer (int64); required)
- `notifiers` (integer (int64); required)
- `total` (integer (int64); required)
---
# Create map field
Source: https://axiom.co/docs/restapi/endpoints/createMapField
```http
POST https://api.axiom.co/v2/datasets/{dataset_id}/mapfields
```
Configures a field as a map field. Events you ingest afterward store the field's nested keys inside the map, while previously ingested events keep their structure. Not supported for metrics datasets.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_id` (path; string; required)
## Request body
Content type: `application/json` (required)
A map field, described by a name
- `name` (string; required)
## Responses
### 200: Created map field.
Content type: `application/json`
A map field, described by a name
- `name` (string; required)
### 400: Empty or invalid field name, or a metrics dataset.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
### 409: The field is already a map field.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
---
# Create monitor
Source: https://axiom.co/docs/restapi/endpoints/createMonitor
```http
POST https://api.axiom.co/v2/monitors
```
Creates a monitor. Axiom runs the monitor's query once before saving it and rejects the request if the query fails, for example because it's invalid or references a dataset that doesn't exist. `labelIds` replaces assignments when supplied; [] clears them. Omitted or null `labelIds` preserves assignments on updates and creates an unlabeled resource on creation. IDs must belong to existing labels in your organization and are validated before saving.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
Content type: `application/json` (required)
Type: `MonitorUpsertRequest`
## Responses
### 200: Created monitor.
Content type: `application/json`
Type: `MonitorWithId`
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### MonitorUpsertRequest
All of the following:
- `Monitor`
- Object with:
- `labelIds` (array of string; items ≤ 500): Existing label IDs; replaces assignments when supplied, clears with [], and preserves them when omitted or null.
### MonitorWithId
Monitor configuration with its unique identifier
All of the following:
- `Monitor`
- Object with:
- `createdAt` (string (date-time)): Timestamp when the monitor was created
- `createdBy` (string): ID of the user who created the monitor
- `createdByAgent` (boolean): true when the MCP server created this monitor
- `datasets` (array of string): Dataset names referenced by the monitor query.
- `id` (string; required): Unique identifier for the monitor
- `labelIds` (array of string; required): IDs of labels assigned to this monitor.
- `labelNames` (array of string; required): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`): Resolved labels assigned to this monitor.
- `lastError` (string): Most recent error encountered while evaluating the monitor.
- `updatedAt` (string (date-time)): Timestamp when the monitor was last updated
### Monitor
Configuration for a monitoring rule. Monitors can be configured to:
- Check threshold values (e.g., CPU usage > 90%)
- Match specific events in logs
- Detect anomalies based on historical patterns
Each monitor runs on a specified interval and can trigger notifications through configured notifiers.
Object.
- `alertOnNoData` (boolean): Whether to alert when no data is received
- `aplQuery` (string): APL (Axiom Processing Language) query string used for monitoring.
This query defines what data to analyze and how to process it.
At least one of aplQuery or mplQuery must be provided.
- `backfillDays` (integer (int64)): NewValues monitors only. Before the first evaluation, the values the query returns over this many days are recorded as seen, so they do not alert. Must not exceed lookbackDays. 0 disables the backfill.
- `columnName` (string): Name of the column to monitor
- `compareDays` (number (int64); value ≤ 7): Number of days to compare for anomaly detection
- `description` (string): Detailed description of the monitor's purpose
- `disabled` (boolean): Whether the monitor is currently disabled
- `disabledUntil` (string (date-time); nullable): Timestamp until when the monitor should remain disabled
- `includeChart` (boolean): Whether to include a query chart in triggered notifications
- `intervalMinutes` (integer (int64); value ≥ 1): How frequently the monitor should run, in minutes.
Minimum value is 1 minute.
- `lookbackDays` (integer (int64); value ≥ 1): NewValues monitors only. A value counts as new when it was not seen in this many days.
- `mplQuery` (string): MPL (Metrics Processing Language) query string for metrics-based monitoring.
Use this as an alternative to aplQuery for metrics datasets.
At least one of aplQuery or mplQuery must be provided.
- `name` (string; required): Name of the monitor
- `notifierIds` (array of string): List of notifier IDs that will receive alerts.
Notifiers can be email, Slack, webhook endpoints, etc.
- `notifyByGroup` (boolean): Whether to group notifications
- `notifyEveryRun` (boolean): Whether to send notifications on every check
- `operator` (string; one of `"Below"`, `"BelowOrEqual"`, `"Above"`, `"AboveOrEqual"`, `"AboveOrBelow"`): Comparison operator for threshold checks:
- Below: Trigger when value < threshold
- BelowOrEqual: Trigger when value <= threshold
- Above: Trigger when value > threshold
- AboveOrEqual: Trigger when value >= threshold
- AboveOrBelow: Trigger when value is outside a range
- `rangeMinutes` (integer (int64); value ≥ 1): Time window to evaluate in each check, in minutes.
For example, "last 5 minutes of data"
- `resolvable` (boolean): Whether the alert can be manually resolved
- `secondDelay` (number (int64); value ≤ 86400): Number of seconds to move each run's query window into the past, so data that arrives late is included.
For example, with a value of 300, a run at 10:05 queries up to 10:00.
- `skipResolved` (boolean): Whether to skip resolved alerts
- `threshold` (number (double)): Threshold value for triggering the alert
- `tolerance` (number; value ≤ 100): Tolerance percentage for anomaly detection
- `trackedValue` (string): NewValues monitors only, and required for them. The column of the query result whose values are checked for new ones.
- `triggerAfterNPositiveResults` (number (int64)): Number of runs among the last `triggerFromNRuns` runs, including the current one, that must meet the trigger condition for the monitor to trigger.
The current run must always meet it.
For example, set both fields to 3 to trigger only after 3 consecutive runs meet the condition.
If unset or 0, the first run that meets the condition triggers.
Values above `triggerFromNRuns` are lowered to it when the monitor is saved.
Applies to Threshold and AnomalyDetection monitors.
- `triggerFromNRuns` (number (int64)): Number of most recent runs, including the current one, that the monitor looks at when deciding whether to trigger.
Has no effect unless `triggerAfterNPositiveResults` is also set.
Applies to Threshold and AnomalyDetection monitors.
- `type` (string; one of `"Threshold"`, `"MatchEvent"`, `"AnomalyDetection"`, `"NewValues"`; required): Type of monitoring check to perform:
- Threshold: Compares a numeric value against a threshold
- MatchEvent: Looks for specific events or patterns
- AnomalyDetection: Identifies unusual patterns based on historical data
- NewValues: Alerts when the trackedValue column of the query result holds a value not seen within lookbackDays. Each run queries the last rangeMinutes, which defaults to intervalMinutes and cannot be less. Sends one notification per new value.
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
---
# Create notifier
Source: https://axiom.co/docs/restapi/endpoints/createNotifier
```http
POST https://api.axiom.co/v2/notifiers
```
Creates a notifier. Set exactly one channel under `properties`, such as `slack`, `email`, or `webhook`. Returns `400` if the channel type isn't enabled for your organization. `labelIds` replaces assignments when supplied; [] clears them. Omitted or null `labelIds` preserves assignments on updates and creates an unlabeled resource on creation. IDs must belong to existing labels in your organization and are validated before saving.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
Notifier configuration details
Content type: `application/json` (required)
Type: `NotifierUpsertRequest`
## Responses
### 200: Created notifier.
Content type: `application/json`
Type: `NotifierWithId`
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### NotifierUpsertRequest
All of the following:
- `Notifier`
- Object with:
- `labelIds` (array of string; items ≤ 500): Existing label IDs; replaces assignments when supplied, clears with [], and preserves them when omitted or null.
### NotifierWithId
Notifier configuration with its unique identifier
All of the following:
- `Notifier`
- Object with:
- `id` (string): Unique identifier for the notifier
- `labelIds` (array of string; required): IDs of labels assigned to this notifier.
- `labelNames` (array of string; required): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`): Resolved labels assigned to this notifier.
### Notifier
Configuration for a notification channel. Notifiers can be configured for various services like:
- Slack
- Email
- PagerDuty
- OpsGenie
- Discord
- Microsoft Teams
- Custom Webhooks
- Cursor
- Claude Code
- Jira Service Management
Object.
- `createdAt` (string (date-time); read-only): Timestamp when the notifier was created
- `createdBy` (string; read-only): Email or ID of the user who created the notifier
- `createdByAgent` (boolean): true when the MCP server created this notifier
- `disabled` (boolean): Whether repeated delivery failures disabled the notifier. False when a user snoozed it with disabledUntil. Ignored on requests
- `disabledUntil` (string): ISO timestamp until which the notifier is disabled (null if enabled)
- `lastError` (string): The delivery error that disabled the notifier. Empty for email notifiers and when disabled is false. Ignored on requests
- `name` (string; required): Human-readable name for the notifier
- `properties` (`NotifierProperties`; required)
- `updatedAt` (string (date-time); read-only): Timestamp when the notifier was last updated
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### NotifierProperties
Configuration options for different notification channels. Only one channel should be configured per notifier.
Object.
- `amp` (`AmpConfig`)
- `chatgptWorkspaceAgent` (`ChatGPTWorkspaceAgentConfig`)
- `claudeCode` (`ClaudeCodeConfig`)
- `cursor` (`CursorConfig`)
- `customWebhook` (`CustomNotifierConfig`)
- `discord` (`DiscordConfig`)
- `discordWebhook` (`DiscordWebhookConfig`)
- `email` (`EmailConfig`)
- `jiraServiceManagement` (`JiraServiceManagementConfig`)
- `microsoftTeams` (`MicrosoftTeamsConfig`)
- `opsgenie` (`OpsGenieConfig`)
- `pagerduty` (`PagerDutyConfig`)
- `slack` (`SlackConfig`)
- `webhook` (`WebhookConfig`)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
### AmpConfig
Amp Orb webhook. The receiving plugin must accept {"text": ""}.
Object.
- `webhookUrl` (string; required): Secret HTTPS URL from the Amp plugin createWebhook registration. Returned encrypted on reads; submit it unchanged to retain it on updates.
### ChatGPTWorkspaceAgentConfig
Published ChatGPT Workspace Agent API channel. Axiom sends {"input": ""}.
Object.
- `token` (string; required): ChatGPT access token with the Workspace Agents scope
- `triggerId` (string; required): API channel trigger ID beginning with agtch_
### ClaudeCodeConfig
Claude Code routine. Axiom sends a fixed text body when the monitor fires.
Object.
- `routineId` (string; required): Routine ID from a Claude Code API trigger
- `token` (string; required): Bearer token for the routine
### CursorConfig
Cursor automation webhook. Axiom sends a fixed context body when the monitor fires.
Object.
- `token` (string; required): Bearer token for the automation webhook
- `webhookUrl` (string; required): Automation webhook URL from a Cursor automation
### CustomNotifierConfig
Configuration for custom webhook notifications with flexible headers and body template.
Supports variable substitution in the body template using {{.Variable}} syntax.
Object.
- `body` (string; required): Template for the webhook body, supports variable substitution
- `headers` (map of string to string): HTTP headers to include in the request
- `secretHeaders` (map of string to string): Sensitive HTTP headers (tokens, keys) that should be masked in logs
- `url` (string; required): Custom webhook endpoint URL
### DiscordConfig
Configuration for Discord notifications using bot token
Object.
- `discordChannel` (string): Discord channel ID to send notifications
- `discordToken` (string): Discord bot token for authentication
- `messageTemplate` (`MessageTemplate`)
### DiscordWebhookConfig
Configuration for Discord notifications using webhooks
Object.
- `discordWebhookUrl` (string): Discord webhook URL
- `messageTemplate` (`MessageTemplate`)
### EmailConfig
Configuration for email notifications
Object.
- `emails` (array of string): List of email addresses to receive notifications
- `messageTemplate` (`MessageTemplate`)
### JiraServiceManagementConfig
Configuration for Jira Service Management Ops alerts using an API integration
Object.
- `apiKey` (string; required): API key of the Jira Service Management API integration
### MicrosoftTeamsConfig
Configuration for Microsoft Teams notifications
Object.
- `messageTemplate` (`MessageTemplate`)
- `microsoftTeamsUrl` (string): Microsoft Teams webhook URL
### OpsGenieConfig
Configuration for OpsGenie integration
Object.
- `apiKey` (string): OpsGenie API key for authentication
- `isEU` (boolean): Whether to use EU region endpoints
### PagerDutyConfig
Configuration for PagerDuty integration
Object.
- `routingKey` (string): PagerDuty integration key for routing alerts
- `token` (string): PagerDuty API token for additional functionality
### SlackConfig
Configuration for Slack notifications using incoming webhooks
Object.
- `messageTemplate` (`MessageTemplate`)
- `slackUrl` (string): Slack incoming webhook URL
### WebhookConfig
Configuration for simple webhook notifications
Object.
- `url` (string): Webhook endpoint URL
### MessageTemplate
Go templates that replace the title and body of the notifier's default message. An empty field keeps the default.
Variables include {{.Title}}, {{.Body}}, {{.Name}}, {{.Action}}, {{.Value}}, {{.Threshold}}, {{.Labels}}, {{.Groups}} and {{.MatchedEvent}}.
If a template fails when a notification is sent, the default message is sent and the delivery records the error.
Object.
- `body` (string): Template for the message body
- `title` (string): Template for the message title
---
# Create org
Source: https://axiom.co/docs/restapi/endpoints/createOrg
```http
POST https://api.axiom.co/v2/orgs
```
Creates an organization on the Personal plan with the authenticated user as its owner. Requires a personal access token (PAT).
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
Content type: `application/json` (required)
- `edgeDeployment` (string): The default edge deployment of the organization.
- `name` (string; required)
## Responses
### 200: Created organization.
Content type: `application/json`
- `defaultEdgeDeployment` (string)
- `firstFailedPayment` (string)
- `id` (string; required)
- `lastUsageSync` (string; required)
- `license` (`License`; required)
- `metaCreated` (string)
- `metaModified` (string)
- `metaVersion` (string)
- `name` (string; required)
- `paymentStatus` (string; one of `"na"`, `"failed"`, `"success"`, `"blocked"`; required)
- `plan` (string; one of `"personal"`, `"teamMonthlyAws"`, `"axiomCloud"`, `"teamPlus"`, `"enterprise"`, `"comped"`, `"accelerator"`; required)
- `planCreated` (string; required)
- `primaryEmail` (string; required)
- `role` (string)
### 400: Invalid name or edge deployment, or the user has reached the maximum number of organizations.
## Schemas
### License
Object.
- `apiRateLimitPerSecond` (integer (uint64); required)
- `billingPeriodEnd` (string (date-time); required)
- `billingPeriodStart` (string (date-time); required)
- `defaultEdgeDeployment` (string; required)
- `edgeDeployments` (array of string; required)
- `expiresAt` (string (date-time); nullable)
- `features` (map of string to boolean; required)
- `id` (string; required)
- `issuedAt` (string (date-time); required)
- `issuedTo` (string; required)
- `issuer` (string; required)
- `maxAuditWindowSeconds` (integer (uint64); required)
- `maxDatasets` (integer (uint64); required)
- `maxEndpoints` (integer (uint64); required)
- `maxFields` (integer (uint64); required)
- `maxMonitors` (integer (uint64); required)
- `maxQueryWindowSeconds` (integer (uint64); required)
- `maxUsers` (integer (uint64); required)
- `monthlyIngestGb` (integer (uint64); required)
- `monthlyQueryGbHours` (integer (uint64); required)
- `storageAllowanceGB` (integer (uint64))
- `tier` (string; one of `"personal"`, `"teamMonthlyAws"`, `"axiomCloud"`, `"teamPlus"`, `"enterprise"`, `"comped"`, `"accelerator"`; required)
- `validFrom` (string (date-time); required)
- `withAuths` (array of string; required)
---
# Create role
Source: https://axiom.co/docs/restapi/endpoints/createRole
```http
POST https://api.axiom.co/v2/rbac/roles
```
Creates a custom role. Requires an Enterprise plan or the RBAC add-on. The name must be unique and can't start with `axiom-`. The `members` field is ignored; assign users with the Update user role endpoint.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
The role's name, description, and capabilities
Content type: `application/json` (required)
Defines a role and its associated permissions within the system
- `datasetCapabilities` (`roleDatasetCapabilities`)
- `description` (string): Detailed description of the role's purpose and scope
- `members` (array of string): IDs of users assigned this role directly. Returned in responses and ignored in requests. To assign a role to a user, use the Update user role endpoint.
- `name` (string; required): Unique name identifier for the role
- `orgCapabilities` (`roleOrgCapabilities`)
- `viewCapabilities` (`roleViewCapabilities`)
## Responses
### 200: The created role.
Content type: `application/json`
Type: `RoleWithID`
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### roleDatasetCapabilities
Defines the available permissions for dataset operations
Type: map of string to object
### roleOrgCapabilities
Defines organization-wide permissions and capabilities
Object.
- `annotations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of annotations across the organization
- `apiTokens` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of API tokens for authentication
- `auditLog` (array of string; one of `"read"`): Controls access to organization audit logs
- `billing` (array of string; one of `"read"`, `"update"`): Controls access to billing information and settings
- `dashboards` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of organization dashboards
- `datasets` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of organization datasets
- `endpoints` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of API endpoints
- `integrations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of third-party integrations
- `labels` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of labels
- `monitors` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of monitoring
- `notifiers` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of notification settings
- `rbac` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls access to role-based access control settings
- `sharedAccessKeys` (array of string; one of `"read"`, `"update"`): Controls the management of shared access keys
- `users` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls user management within the organization
- `views` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of data views
### roleViewCapabilities
Defines the available permissions for view operations
Type: map of string to object
### RoleWithID
Extends the base Role type to include a unique identifier
All of the following:
- `Role`
- Object with:
- `id` (string; required): Unique identifier for the role
### Role
Defines a role and its associated permissions within the system
Object.
- `datasetCapabilities` (`roleDatasetCapabilities`)
- `description` (string): Detailed description of the role's purpose and scope
- `members` (array of string): IDs of users assigned this role directly. Returned in responses and ignored in requests. To assign a role to a user, use the Update user role endpoint.
- `name` (string; required): Unique name identifier for the role
- `orgCapabilities` (`roleOrgCapabilities`)
- `viewCapabilities` (`roleViewCapabilities`)
---
# Create saved query
Source: https://axiom.co/docs/restapi/endpoints/createStarred
```http
POST https://api.axiom.co/v2/apl-starred-queries
```
Saves an APL query for the authenticated user. Axiom sets `who` to the caller and `kind` to `apl`. If you omit `dataset`, Axiom uses the alphabetically first dataset that `query.apl` references.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
Content type: `application/json` (required)
- `dataset` (string)
- `kind` (string; one of `"apl"`; required)
- `metadata` (map of string to string; required)
- `name` (string; required)
- `query` (`APLRequestWithOptions`; required)
- `who` (string; required)
## Responses
### 200: Created saved query.
Content type: `application/json`
Type: `StarredQueryWithId`
### 400: Missing `name`, or no `dataset` given and none found in `query.apl`.
### 403: You don't have permission to create saved queries on the dataset.
## Schemas
### APLRequestWithOptions
Object.
- `apl` (string; required)
- `cursor` (string)
- `defaultLimit` (integer (int64))
- `defaultOrder` (array of `APLRequestWithOptionsDefaultOrder`)
- `endTime` (string)
- `includeCursor` (boolean)
- `includeCursorField` (boolean)
- `libraries` (array of string)
- `queryOptions` (`QueryOptions`)
- `startTime` (string)
- `variables` (object)
### StarredQueryWithId
All of the following:
- `StarredQuery`
- Object with:
- `id` (string; required)
### APLRequestWithOptionsDefaultOrder
Object.
- `desc` (boolean)
- `field` (string)
### QueryOptions
Object. Other fields aren't allowed.
- `disableCache` (boolean)
- `disableStats` (boolean)
- `disableTrace` (boolean)
- `maxDataPoints` (integer (int64))
- `maxSeries` (integer (int64))
- `noAggregation` (boolean)
- `noFill` (boolean)
- `noInterpolation` (boolean)
- `priority` (string; one of `"low"`, `"medium"`, `"high"`)
- `resolution` (string)
- `displayNull` (string; one of `"auto"`, `"null"`, `"span"`, `"zero"`, `""`): Controls how empty intervals are rendered in time series charts. `auto` infers from the query, `null` leaves gaps, `span` connects adjacent points, `zero` fills with zero.
- `overlayCharts` (string; one of `"true"`, `"false"`, `""`): When enabled, charts are overlaid on a single chart instead of stacked separately.
- `shownColumns` (string; length ≤ 10000)
- `timeSeriesVariant` (string; one of `"area"`, `"bars"`, `"line"`, `"lines"`, `""`)
- `timeSeriesView` (string; one of `"charts"`, `"resultsTable"`, `"charts|resultsTable"`, `""`)
### StarredQuery
Object.
- `dataset` (string)
- `kind` (string; one of `"apl"`; required)
- `metadata` (map of string to string; required)
- `name` (string; required)
- `query` (`APLRequestWithOptions`; required)
- `who` (string; required)
---
# Create API token
Source: https://axiom.co/docs/restapi/endpoints/createToken
```http
POST https://api.axiom.co/v2/tokens
```
Creates an API token and returns its secret `token` value, which you can't retrieve again. You can only grant capabilities you have yourself. If you omit `expiresAt`, the token doesn't expire.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
Content type: `application/json` (required)
- `datasetCapabilities` (`datasetCapabilities`)
- `description` (string): Description of the token
- `expiresAt` (string (date-time); nullable): Expiration date of the token (ISO 8601 format)
- `name` (string; required): Name of the token
- `orgCapabilities` (`orgCapabilities`)
- `viewCapabilities` (`viewCapabilities`)
## Responses
### 200: Created API token, including its secret `token` value.
Content type: `application/json`
Type: `CreateAPITokenResponse`
### 400: No capability set, an invalid capability, or a capability the caller doesn't have.
## Schemas
### datasetCapabilities
Type: map of string to object
### orgCapabilities
Object.
- `annotations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Annotations capability
- `apiTokens` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): API tokens capability
- `auditLog` (array of string; one of `"read"`): Audit Log capability
- `billing` (array of string; one of `"read"`, `"update"`): Billing capability
- `dashboards` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Dashboards capability
- `datasets` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Datasets capability
- `endpoints` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Endpoints capability
- `integrations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Integrations capability
- `labels` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Labels capability
- `monitors` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Monitors capability
- `notifiers` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Notifiers capability
- `rbac` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Access control capability
- `sharedAccessKeys` (array of string; one of `"read"`, `"update"`): Shared access keys capability
- `users` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Users capability
- `views` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Views capability
### viewCapabilities
Type: map of string to object
### CreateAPITokenResponse
All of the following:
- `APIToken`
- Object with:
- `token` (string)
### APIToken
Object.
- `apiLastUsed` (string (date-time); nullable; read-only): When the token was last used on an API other than ingest
- `auditIdentity` (string; read-only): Audit identity of the token
- `datasetCapabilities` (`datasetCapabilities`; required)
- `description` (string): Description of the token
- `expiresAt` (string (date-time); nullable; read-only): Expiration date of the token (ISO 8601 format)
- `id` (string; required): ID of the token
- `ingestLastUsed` (string (date-time); nullable; read-only): When the token was last used to ingest
- `name` (string; required): Name of the token
- `orgCapabilities` (`orgCapabilities`; required)
- `samlAuthenticated` (boolean)
- `viewCapabilities` (`viewCapabilities`)
---
# Create user
Source: https://axiom.co/docs/restapi/endpoints/createUser
```http
POST https://api.axiom.co/v2/users
```
Adds a user to the organization with the given role and sends them an invite email. If the email address already belongs to an Axiom account, Axiom keeps its existing name. API tokens can't assign the `owner` role.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
Content type: `application/json` (required)
Object representing a new user creation request
- `email` (string; required): Email address of the new user
- `name` (string; required): Full name of the new user
- `role` (string; required): Role to assign to the new user
## Responses
### 200: Added user.
Content type: `application/json`
Represents a user in the system
- `email` (string; required): User's email address
- `id` (string; required): Unique identifier for the user
- `name` (string; required): User's full name
- `role` (`UserDetailsRole`; required)
### 400: Invalid email address, the user is already a member, or the organization has reached its user limit.
### 403: Insufficient permissions, or the caller isn't allowed to assign the `owner` role.
### 404: Role not found.
## Schemas
### UserDetailsRole
Detailed information about a user's role
Object.
- `id` (string; required): Unique identifier for the role
- `name` (string; required): Human-readable name of the role
---
# Create view
Source: https://axiom.co/docs/restapi/endpoints/createView
```http
POST https://api.axiom.co/v2/views
```
Creates a view, a named APL query that you can query like a dataset. Axiom derives `datasets` from `aplQuery`. The name can't match an existing dataset or view, and the query can't reference views or use wildcards.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
Content type: `application/json` (required)
- `aplQuery` (string; required): APL query that defines the view
- `datasets` (array of string): Datasets the view queries. Axiom derives this from `aplQuery` and ignores it in requests.
- `description` (string)
- `edgeDeployment` (string): Region of the source datasets; ignored in requests
- `edgeDeploymentUrl` (string): URL of the edge deployment; ignored in requests
- `name` (string; required): Name of the view. Use it as the view ID and to query the view like a dataset.
- `sharedByOrg` (string): ID of the org that shared this resource, if it's shared
- `sharedByOrgName` (string): The name of the org that shared this resource, if it's shared
## Responses
### 200: Created view.
Content type: `application/json`
- `aplQuery` (string; required): APL query that defines the view
- `datasets` (array of string): Datasets the view queries. Axiom derives this from `aplQuery` and ignores it in requests.
- `description` (string)
- `edgeDeployment` (string): Region of the source datasets; ignored in requests
- `edgeDeploymentUrl` (string): URL of the edge deployment; ignored in requests
- `name` (string; required): Name of the view. Use it as the view ID and to query the view like a dataset.
- `sharedByOrg` (string): ID of the org that shared this resource, if it's shared
- `sharedByOrgName` (string): The name of the org that shared this resource, if it's shared
### 400: Invalid view, for example an APL parse error, a name that's already in use, or a query that references a view or datasets in different regions.
### 403: You don't have query access to a dataset that `aplQuery` references.
---
# Create virtual field
Source: https://axiom.co/docs/restapi/endpoints/createVirtualField
```http
POST https://api.axiom.co/v2/vfields
```
Creates a virtual field on a dataset. Axiom sets its ID to `.`, so the name must be unique within the dataset. `expression` must be a valid APL expression.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
Content type: `application/json` (required)
- `dataset` (string; required)
- `description` (string)
- `expression` (string; required)
- `name` (string; required): Name of the virtual field. Use letters, digits, underscores, and hyphens, starting and ending with a letter or digit.
- `type` (string)
- `unit` (string)
## Responses
### 200: Created virtual field.
Content type: `application/json`
Type: `VirtualFieldWithId`
### 400: Missing `dataset`, `name`, or `expression`, an invalid `name`, or an expression that doesn't parse.
### 403: You don't have permission to create virtual fields on the dataset.
### 404: You can't read the dataset.
### 409: A virtual field with this name already exists on the dataset.
## Schemas
### VirtualFieldWithId
All of the following:
- `VirtualField`
- Object with:
- `id` (string; required)
### VirtualField
Object.
- `dataset` (string; required)
- `description` (string)
- `expression` (string; required)
- `name` (string; required): Name of the virtual field. Use letters, digits, underscores, and hyphens, starting and ending with a letter or digit.
- `type` (string)
- `unit` (string)
---
# Delete annotation
Source: https://axiom.co/docs/restapi/endpoints/deleteAnnotation
```http
DELETE https://api.axiom.co/v2/annotations/{id}
```
Deletes an annotation by its ID.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; pattern `^ann_`; required): Unique ID of the annotation
## Responses
### 204: Annotation deleted.
### 400: Invalid annotation ID.
### 404: Annotation not found.
---
# Delete dashboard
Source: https://axiom.co/docs/restapi/endpoints/deleteDashboard
```http
DELETE https://api.axiom.co/v2/dashboards/uid/{uid}
```
Permanently deletes a dashboard by UID and removes its label assignments. Returns `404` if the dashboard doesn't exist or the caller can't manage it.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `uid` (path; string; required)
## Responses
### 204: Dashboard deleted
### 404: Dashboard not found
Content type: `application/json`
- `code` (string; required)
- `currentVersion` (integer (int64))
- `message` (string; required)
- `reason` (string)
- `uid` (string)
---
# Delete dataset
Source: https://axiom.co/docs/restapi/endpoints/deleteDataset
```http
DELETE https://api.axiom.co/v2/datasets/{dataset_id}
```
Deletes a dataset and queues the permanent deletion of its data. For a dataset shared with your organization, removes it from your organization only. Returns the ID of the deletion job.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_id` (path; string; required)
## Responses
### 200: Dataset deleted and data deletion job created.
Content type: `application/json`
- `jobID` (string; required)
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
---
# Delete fields
Source: https://axiom.co/docs/restapi/endpoints/deleteDatasetFields
```http
POST https://api.axiom.co/v2/datasets/{dataset_id}/delete-fields
```
Queues the deletion of the listed fields from the dataset schema. Deleted values stay in storage but can't be queried, and ingesting a deleted field again recreates it. You can delete fields once every 5 minutes per dataset.
When the endpoint returns the status code 202, it means that the deletion request is queued. The deletion itself might take several hours to complete. For more information, see [Delete fields](/reference/datasets#delete-fields).
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_id` (path; string; required)
## Request body
Content type: `application/json` (required)
- `fields` (array of string; required)
## Responses
### 202: Field deletion queued.
Content type: `application/json`
- `fields` (array of string)
- `jobId` (string)
### 400: Empty `fields`, a field that isn't in the schema, a system field or map field, a locked schema, or a metrics dataset.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
### 429: Fields were deleted from this dataset less than 5 minutes ago. Retry after the time in `Retry-After`.
---
# Delete field
Source: https://axiom.co/docs/restapi/endpoints/deleteFieldForDataset
```http
DELETE https://api.axiom.co/v2/datasets/{dataset_id}/fields/{field_id}
```
Queues the deletion of a field from the dataset schema. Deleted values stay in storage but can't be queried, and ingesting the field again recreates it. You can delete fields once every 5 minutes per dataset.
When the endpoint returns the status code 202, it means that the deletion request is queued. The deletion itself might take several hours to complete. For more information, see [Delete fields](/reference/datasets#delete-fields).
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_id` (path; string; required)
- `field_id` (path; string; required)
## Responses
### 202: Field deletion queued.
Content type: `application/json`
- `fields` (array of string)
- `jobId` (string)
### 400: A system field or map field, a locked schema, or a metrics dataset.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: The dataset doesn't exist or the field isn't in its schema.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
### 429: Fields were deleted from this dataset less than 5 minutes ago. Retry after the time in `Retry-After`.
---
# Delete group
Source: https://axiom.co/docs/restapi/endpoints/deleteGroup
```http
DELETE https://api.axiom.co/v2/rbac/groups/{id}
```
Permanently deletes a group. Members lose the roles the group granted but keep their own role, and dashboards the group owned are shared with everyone. Managed groups can't be deleted. Requires an Enterprise plan or the RBAC add-on.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Unique identifier of the group to delete
## Responses
### 204: The group was deleted.
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
---
# Delete label
Source: https://axiom.co/docs/restapi/endpoints/deleteLabel
```http
DELETE https://api.axiom.co/v2/labels/{id}
```
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; pattern `^lbl_`; required)
## Responses
### 204: Label deleted
### 400: Invalid label ID
### 404: Label not found
---
# Delete map fields
Source: https://axiom.co/docs/restapi/endpoints/deleteMapField
```http
DELETE https://api.axiom.co/v2/datasets/{dataset_id}/mapfields/{map_field_name}
```
Removes a field from the map fields of a dataset. The field itself and its ingested data aren't deleted. Not supported for metrics datasets.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_id` (path; string; required)
- `map_field_name` (path; string; required)
## Responses
### 204: Map field removed. No response body.
### 400: The dataset is a metrics dataset.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: The dataset doesn't exist or the field isn't a map field.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
---
# Delete monitor
Source: https://axiom.co/docs/restapi/endpoints/deleteMonitor
```http
DELETE https://api.axiom.co/v2/monitors/{id}
```
Permanently deletes a monitor and removes its label assignments. The caller needs query access to the monitor's datasets.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Monitor ID.
## Responses
### 204: Monitor deleted.
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
---
# Delete notifier
Source: https://axiom.co/docs/restapi/endpoints/deleteNotifier
```http
DELETE https://api.axiom.co/v2/notifiers/{id}
```
Permanently deletes a notifier and removes its label assignments. Returns `400` if any monitor still uses the notifier.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Notifier ID.
## Responses
### 204: Notifier deleted.
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
---
# Delete role
Source: https://axiom.co/docs/restapi/endpoints/deleteRole
```http
DELETE https://api.axiom.co/v2/rbac/roles/{id}
```
Permanently deletes a custom role. Users assigned the role get the `none` role, and the role is removed from all groups. Requires an Enterprise plan or the RBAC add-on.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Unique identifier of the role to delete
## Responses
### 204: The role was deleted.
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
---
# Delete saved query
Source: https://axiom.co/docs/restapi/endpoints/deleteStarred
```http
DELETE https://api.axiom.co/v2/apl-starred-queries/{id}
```
Deletes a saved query by its ID. With a personal access token, you can only delete queries you saved.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required)
## Responses
### 204: Saved query deleted.
### 401: The saved query belongs to another user.
### 403: You don't have permission to delete saved queries on the query's dataset.
### 404: Saved query not found.
---
# Delete API token
Source: https://axiom.co/docs/restapi/endpoints/deleteToken
```http
DELETE https://api.axiom.co/v2/tokens/{id}
```
Permanently deletes an API token so it can no longer authenticate requests.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required)
## Responses
### 204: API token deleted.
### 404: API token not found or expired.
---
# Delete view
Source: https://axiom.co/docs/restapi/endpoints/deleteView
```http
DELETE https://api.axiom.co/v2/views/{id}
```
Deletes a view by its name.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Name of the view
## Responses
### 204: View deleted.
### 403: You don't have query access to the view's dataset.
### 404: View not found.
---
# Delete virtual field
Source: https://axiom.co/docs/restapi/endpoints/deleteVirtualField
```http
DELETE https://api.axiom.co/v2/vfields/{id}
```
Deletes a virtual field by its ID.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): ID of the virtual field in the form `.`
## Responses
### 204: Virtual field deleted.
### 403: You don't have permission to delete virtual fields on the dataset.
### 404: Virtual field not found, or you can't read its dataset.
---
# Retrieve annotation
Source: https://axiom.co/docs/restapi/endpoints/getAnnotation
```http
GET https://api.axiom.co/v2/annotations/{id}
```
Retrieves an annotation by its ID.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; pattern `^ann_`; required): Unique ID of the annotation
## Responses
### 200: Annotation.
Content type: `application/json`
- `datasets` (array of string; length ≥ 1; items ≥ 1; required): array of dataset names for which the annotation appears on charts
- `description` (string; length ≤ 512): Explanation of the event the annotation marks on the charts
- `endTime` (string (date-time); nullable): End time of the annotation
- `id` (string; required)
- `time` (string (date-time); required): Time the annotation marks on the charts. If you don't include this field, Axiom assigns the time of the API request to the annotation.
- `title` (string; length ≤ 256): Summary of the annotation that appears on the charts
- `type` (string; length ≤ 256; pattern `^[a-z0-9-]+$`; required): Type of the event marked by the annotation. Use only alphanumeric characters or hyphens. For example, "production-deployment".
- `url` (string; length ≤ 512): URL relevant for the event marked by the annotation. For example, link to GitHub pull request.
### 400: Invalid annotation ID.
### 404: Annotation not found.
---
# List all annotations
Source: https://axiom.co/docs/restapi/endpoints/getAnnotations
```http
GET https://api.axiom.co/v2/annotations
```
Lists annotations in the organization. Filter by `datasets`, or by a time range with both `start` and `end` at most 100 days apart. Without filters, returns all annotations.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `datasets` (query; array of string): Optional: Filter for dataset names.
- `start` (query; string): Optional: Filter for events after this date. Use RFC3339 time format.
- `end` (query; string): Optional: Filter for events before this date. Use RFC3339 time format.
## Responses
### 200: Annotations.
Content type: `application/json`
Type: array of `Annotation`
### 400: Invalid `start` or `end`, only one of them set, `end` before `start`, or a range longer than 100 days.
## Schemas
### Annotation
Object.
- `datasets` (array of string; length ≥ 1; items ≥ 1; required): array of dataset names for which the annotation appears on charts
- `description` (string; length ≤ 512): Explanation of the event the annotation marks on the charts
- `endTime` (string (date-time); nullable): End time of the annotation
- `id` (string; required)
- `time` (string (date-time); required): Time the annotation marks on the charts. If you don't include this field, Axiom assigns the time of the API request to the annotation.
- `title` (string; length ≤ 256): Summary of the annotation that appears on the charts
- `type` (string; length ≤ 256; pattern `^[a-z0-9-]+$`; required): Type of the event marked by the annotation. Use only alphanumeric characters or hyphens. For example, "production-deployment".
- `url` (string; length ≤ 512): URL relevant for the event marked by the annotation. For example, link to GitHub pull request.
---
# Retrieve current user
Source: https://axiom.co/docs/restapi/endpoints/getCurrentUser
```http
GET https://api.axiom.co/v2/user
```
Retrieves the user who owns the personal access token (PAT) used to authenticate. API tokens aren't supported. The response includes `role` only when the `X-AXIOM-ORG-ID` header is set.
Using this endpoint, you can retrieve your own user. Authorize the request with a [personal access token (PAT)](/reference/tokens).
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Responses
### 200: Current user.
Content type: `application/json`
Represents a user in the system
- `email` (string; required): User's email address
- `id` (string; required): Unique identifier for the user
- `name` (string; required): User's full name
- `role` (`UserDetailsRole`; required)
### 403: The request was authenticated with an API token, or the user isn't a member of the organization in `X-AXIOM-ORG-ID`.
## Schemas
### UserDetailsRole
Detailed information about a user's role
Object.
- `id` (string; required): Unique identifier for the role
- `name` (string; required): Human-readable name of the role
---
# Retrieve dashboard
Source: https://axiom.co/docs/restapi/endpoints/getDashboard
```http
GET https://api.axiom.co/v2/dashboards/uid/{uid}
```
Retrieves a managed dashboard by UID, or a visible integration dashboard by its stable ID. Managed dashboards include their current `version`; integration dashboards are read-only. Labels are resolved unless `exclude=labels`.
If you authenticate with an API token, you can only retrieve a dashboard shared with everyone in your organization or with a group. You can't retrieve private dashboards.
For the structure of the returned `dashboard` field, see [Dashboard JSON](/restapi/dashboard-json).
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `uid` (path; string; required)
- `exclude` (query; string; one of `"labels"`): Exclude resolved label objects from the dashboard response. The labelIds field is still returned.
## Responses
### 200: Dashboard
Content type: `application/json`
- `createdAt` (string (date-time); nullable): Creation time, present only for managed dashboards.
- `createdBy` (string; nullable): Creator, present only for managed dashboards.
- `dashboard` (`DashboardDocument`; required)
- `id` (string; required)
- `labelIds` (array of string; required)
- `labelNames` (array of string): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`)
- `type` (string; one of `"managed"`, `"integration"`; required): Managed dashboards are saved documents; integration dashboards are read-only and generated for matching datasets.
- `uid` (string; required): Managed dashboard UID, or stable integration dashboard ID for read requests.
- `updatedAt` (string (date-time); nullable): Last save time, present only for managed dashboards.
- `updatedBy` (string; nullable): Last editor, present only for managed dashboards.
- `updatedByAgent` (boolean): true when the last save came from the MCP server
- `version` (integer (int64); nullable): Save version, present only for managed dashboards.
### 404: Dashboard not found
Content type: `application/json`
- `code` (string; required)
- `currentVersion` (integer (int64))
- `message` (string; required)
- `reason` (string)
- `uid` (string)
## Schemas
### DashboardDocument
Same as `Dashboard`.
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### Dashboard
Object. Other fields aren't allowed.
- `name` (string; length 1–100; required)
- `owner` (string; required): User ID of the dashboard owner. Use `X-AXIOM-EVERYONE` to make the dashboard accessible to all users in the organization.
- `description` (string; length ≤ 1000)
- `charts` (array of `Chart`; items ≤ 200; required)
- `layout` (array of `LayoutItem`; items ≤ 200; required)
- `sections` (array of `Section`; items ≤ 1000)
- `refreshTime` (integer; one of `0`, `15`, `60`, `300`; required)
- `schemaVersion` (integer; one of `2`; required)
- `against` (string; one of `"-1h"`, `"-3h"`, `"-6h"`, `"-12h"`, `"-1d"`, `"-3d"`, `"-7d"`, `"-1w"`, `"-2w"`, `"-3w"`, `"-30d"`, `"-60d"`, `"-90d"`): Relative time comparison offset. Compares the current time window against a previous period offset by this duration. Mutually exclusive with `againstTimestamp` — setting one clears the other. Use an empty string or omit to disable comparison.
- `againstTimestamp` (string; length ≤ 100): Absolute or relative timestamp to compare against. Mutually exclusive with `against` — setting one clears the other. Accepts ISO 8601, `now-{duration}` (e.g. `now-1h`), or epoch milliseconds as a string.
- `timeWindowStart` (string; length 1–100; required): Start of the dashboard time range. Use `qr-now-{duration}` for a quick range relative to now, where duration is a number followed by `s` (seconds), `m` (minutes), `h` (hours), `d` (days), or `w` (weeks). Examples: `qr-now-5m`, `qr-now-1h`, `qr-now-7d`. Alternatively, use a Unix epoch millisecond timestamp as a string (e.g. `1704067200000`).
- `timeWindowEnd` (string; length 1–100; required): End of the dashboard time range. Use `qr-now` for a rolling window that tracks the current time (pair with a `qr-now-{duration}` start), or a Unix epoch millisecond timestamp as a string (e.g. `1704153600000`).
- `uid` (string; pattern `^[A-Za-z0-9_-]{1,128}$`): Optional dashboard UID. Must contain only letters, numbers, underscores, or hyphens, with length 1-128 when provided.
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
### Chart
One of the following, selected by `type`:
- `TimeSeriesChart` (`type`: `"TimeSeries"`)
- `HeatmapChart` (`type`: `"Heatmap"`)
- `LogStreamChart` (`type`: `"LogStream"`)
- `PieChart` (`type`: `"Pie"`)
- `ScatterChart` (`type`: `"Scatter"`)
- `TableChart` (`type`: `"Table"`)
- `TopKChart` (`type`: `"TopK"`)
- `StatisticChart` (`type`: `"Statistic"`)
- `GaugeChart` (`type`: `"Gauge"`)
- `NoteChart` (`type`: `"Note"`)
- `MonitorListChart` (`type`: `"MonitorList"`)
- `SmartFilterChart` (`type`: `"SmartFilter"`)
- `SpacerChart` (`type`: `"Spacer"`)
- `VisualizeChart` (`type`: `"Visualize"`)
### LayoutItem
Object. Other fields aren't allowed.
- `i` (string; length 1–200; required)
- `x` (integer; value 0–11; required)
- `y` (number; value ≥ 0; nullable; required)
- `w` (integer; value 1–12; required)
- `h` (number; value 0.5–100; required)
- `minW` (integer; value 1–12)
- `minH` (number; value 0.5–100)
- `maxW` (integer; value 1–12)
- `maxH` (integer; value 1–100)
- `static` (boolean)
### Section
Object. Other fields aren't allowed.
- `id` (string (uuid); required)
- `title` (string; length 1–200; required)
- `defaultCollapsed` (boolean)
### TimeSeriesChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"TimeSeries"`; required)
- `name` (string; length 1–500)
- `query` (`TimeSeriesChartQuery`; required)
### HeatmapChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Heatmap"`; required)
- `name` (string; length 1–500)
- `query` (`HeatmapChartQuery`; required)
- `colorScheme` (string; one of `"Blue"`, `"Orange"`, `"Red"`, `"Purple"`, `"Teal"`, `"Yellow"`, `"Green"`, `"Pink"`, `"Grey"`, `"Brown"`)
### LogStreamChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"LogStream"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `tableSettings` (`TableSettings`)
### PieChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Pie"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### ScatterChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Scatter"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### TableChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Table"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `tableSettings` (`TableSettings`)
### TopKChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"TopK"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### StatisticChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Statistic"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `colorScheme` (string; one of `"Blue"`, `"Orange"`, `"Red"`, `"Purple"`, `"Teal"`, `"Yellow"`, `"Green"`, `"Pink"`, `"Grey"`, `"Brown"`)
- `customUnits` (string; length ≤ 200)
- `showChart` (one of boolean, string)
- `hideValue` (boolean)
- `chartHeight` (one of string; length ≤ 100, number)
- `errorThreshold` (string; one of `"Above"`, `"AboveOrEqual"`, `"Below"`, `"BelowOrEqual"`, `"AboveOrBelow"`)
- `errorThresholdValue` (string; length ≤ 100)
- `warningThreshold` (string; one of `"Above"`, `"AboveOrEqual"`, `"Below"`, `"BelowOrEqual"`, `"AboveOrBelow"`)
- `warningThresholdValue` (string; length ≤ 100)
- `roundTo` (integer; value 0–10)
- `invertTheme` (boolean)
- `background` (string; length ≤ 200)
- `textColor` (string; length ≤ 200)
- `labelColor` (string; length ≤ 200)
- `chartFillColor` (string; length ≤ 200)
- `okColorProps` (`StatisticChartColorProps`)
- `warningColorProps` (`StatisticChartColorProps`)
- `errorColorProps` (`StatisticChartColorProps`)
### GaugeChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Gauge"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `segments` (array of `GaugeChartSegment`; items 1–100; required)
- `colorScale` (string; one of `"green-to-red"`, `"red-to-green"`)
- `showRing` (boolean)
- `labelMode` (string; one of `"none"`, `"boundaries"`, `"intervals"`)
- `showSparkline` (boolean)
- `scaleToTimeRange` (boolean)
- `scaleBaseDurationMs` (number; value > 0)
- `customUnits` (string; length ≤ 200)
### NoteChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Note"`; required)
- `text` (string; length 1–100000; required)
- `variant` (string; one of `""`, `"default"`, `"plain"`; nullable)
### MonitorListChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"MonitorList"`; required)
- `name` (string; length 1–500)
- `selectedMonitors` (array of string; length 1–200; items 1–200; required)
- `columns` (`MonitorListColumns`; required)
### SmartFilterChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"SmartFilter"`; required)
- `name` (string; length 1–500)
- `filters` (array of `SmartFilterConfig`; items 1–50; required)
- `logo` (string; length ≤ 2000)
- `logoDark` (string; length ≤ 2000)
### SpacerChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Spacer"`; required)
- `name` (string; length 1–500)
- `variant` (string; one of `"transparent"`, `"dashed"`, `"solid"`)
### VisualizeChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Visualize"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `visualization` (`VisualizeConfiguration`; required)
### TimeSeriesChartQuery
One of the following:
- `TimeSeriesNonMetricsAplQuery`
- `TimeSeriesNativeMplQuery`
### HeatmapChartQuery
One of the following:
- `HeatmapNonMetricsAplQuery`
- `HeatmapNativeMplQuery`
### SimpleChartQuery
One of the following:
- `SimpleNonMetricsAplQuery`
- `SimpleNativeMplQuery`
### TableSettings
Object. Other fields aren't allowed.
- `columns` (array of `ColumnSetting`; items ≤ 500)
- `settings` (`DatasetStreamSettings`)
### StatisticChartColorProps
Object. Other fields aren't allowed.
- `background` (string; length ≤ 200)
- `chartFillColor` (string; length ≤ 200)
- `labelColor` (string; length ≤ 200)
- `textColor` (string; length ≤ 200)
### GaugeChartSegment
Object. Other fields aren't allowed.
- `from` (number; required)
- `to` (number; required)
### MonitorListColumns
Object. Other fields aren't allowed.
- `status` (boolean; required)
- `history` (boolean; required)
- `dataset` (boolean; required)
- `type` (boolean; required)
- `notifiers` (boolean; required)
### SmartFilterConfig
One of the following:
- `SmartFilterSearch`
- `SmartFilterSelect`
### VisualizeConfiguration
One of the following, selected by `type`:
- `ScatterVisualization` (`type`: `"scatter"`)
- `BarVisualization` (`type`: `"bar"`)
- `HorizontalBarVisualization` (`type`: `"horizontalBar"`)
- `HistogramVisualization` (`type`: `"histogram"`)
- `FrequencyBarVisualization` (`type`: `"frequencyBar"`)
- `VisualizeHeatmap` (`type`: `"heatmap"`)
### TimeSeriesNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
- `queryOptions` (`TimeSeriesQueryOptions`)
### TimeSeriesNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
- `queryOptions` (`TimeSeriesQueryOptions`)
### HeatmapNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
- `queryOptions` (`HeatmapQueryOptions`)
### HeatmapNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
- `queryOptions` (`HeatmapQueryOptions`)
### SimpleNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
### SimpleNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
### ColumnSetting
One of the following:
- string; length ≤ 500
- `AdvancedColumnSetting`
### DatasetStreamSettings
Object. Other fields aren't allowed.
- `fontSize` (string; length ≤ 20; pattern `^\d+px$`)
- `highlightSeverity` (boolean)
- `showRaw` (boolean)
- `showEvent` (boolean)
- `showTimestamp` (boolean)
- `wrapLines` (boolean)
- `hideNulls` (boolean)
- `fitColumns` (boolean)
### SmartFilterSearch
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `type` (string; one of `"search"`; required)
### SmartFilterSelect
One of the following, selected by `selectType`:
- `SmartFilterSelectList` (`selectType`: `"list"`)
- `SmartFilterSelectQuery` (`selectType`: `"query"`)
### ScatterVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"scatter"`; required)
- `bindings` (`ScatterVisualizationBindings`; required)
- `settings` (`ScatterVisualizationSettings`; required)
### BarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"bar"`; required)
- `bindings` (`BarVisualizationBindings`; required)
- `settings` (`VisualizeBarSettings`; required)
### HorizontalBarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"horizontalBar"`; required)
- `bindings` (`HorizontalBarVisualizationBindings`; required)
- `settings` (`VisualizeBarSettings`; required)
### HistogramVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"histogram"`; required)
- `bindings` (`HistogramVisualizationBindings`; required)
- `settings` (`HistogramVisualizationSettings`; required)
### FrequencyBarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"frequencyBar"`; required)
- `bindings` (`FrequencyBarVisualizationBindings`; required)
- `settings` (`FrequencyBarVisualizationSettings`; required)
### VisualizeHeatmap
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"heatmap"`; required)
- `bindings` (`VisualizeHeatmapBindings`; required)
- `settings` (`VisualizeHeatmapSettings`; required)
### TimeSeriesQueryOptions
Object. Other fields aren't allowed.
- `displayNull` (string; one of `"auto"`, `"null"`, `"span"`, `"zero"`, `""`): Controls how empty intervals are rendered in time series charts. `auto` infers from the query, `null` leaves gaps, `span` connects adjacent points, `zero` fills with zero.
- `overlayCharts` (string; one of `"true"`, `"false"`, `""`): When enabled, charts are overlaid on a single chart instead of stacked separately.
- `shownColumns` (string; length ≤ 10000)
- `timeSeriesVariant` (string; one of `"area"`, `"bars"`, `"line"`, `"lines"`, `""`)
- `timeSeriesView` (string; one of `"charts"`, `"resultsTable"`, `"charts|resultsTable"`, `""`)
### HeatmapQueryOptions
Object. Other fields aren't allowed.
- `timeSeriesView` (string; one of `"charts"`, `"resultsTable"`, `"charts|resultsTable"`, `""`)
### AdvancedColumnSetting
Object. Other fields aren't allowed.
- `name` (string; length ≤ 500; required)
- `width` (integer; value > 0, ≤ 9007199254740991)
### SmartFilterSelectList
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `options` (`SmartFilterOptions`)
- `type` (string; one of `"select"`; required)
- `selectType` (string; one of `"list"`; required)
### SmartFilterSelectQuery
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `options` (all of one of array of `SmartFilterOption`; items ≤ 200, string; one of `null`; nullable, string; one of `""`): Pre-defined options merged with the dynamic options returned by `query` at runtime. Typically used to seed a default option (for example an "All" entry with `unset: true`) so the filter has a sensible initial selection before — or independent of — query results.
- `type` (string; one of `"select"`; required)
- `selectType` (string; one of `"query"`; required)
- `query` (`SmartFilterQuery`)
### ScatterVisualizationBindings
Object. Other fields aren't allowed.
- `x` (`VisualizeAxisColumnRef`; required)
- `y` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### ScatterVisualizationSettings
Object. Other fields aren't allowed.
- `colors` (`VisualizeColorSettings`)
- `xAxis` (`VisualizeAxisSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### BarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
- `value` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### VisualizeBarSettings
One of the following:
- `VisualizeStandardAggregationSettings`
- `VisualizePercentileAggregationSettings`
### HorizontalBarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
- `value` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### HistogramVisualizationBindings
Object. Other fields aren't allowed.
- `value` (`VisualizeNumericColumnRef`; required)
### HistogramVisualizationSettings
Object. Other fields aren't allowed.
- `binCount` (integer; value 1–200; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
### FrequencyBarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
### FrequencyBarVisualizationSettings
Object. Other fields aren't allowed.
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
### VisualizeHeatmapBindings
Object. Other fields aren't allowed.
- `x` (`VisualizeCategoricalColumnRef`; required)
- `y` (`VisualizeCategoricalColumnRef`; required)
### VisualizeHeatmapSettings
Object. Other fields aren't allowed.
- `categoryLimit` (integer; value 1–100; required)
### SmartFilterOptions
One of the following:
- array of `SmartFilterOption`; items ≤ 200
- string; one of `null`; nullable
- string; one of `""`
### SmartFilterOption
Object. Other fields aren't allowed.
- `key` (string; length ≤ 500; required)
- `value` (string; length ≤ 10000; required)
- `default` (boolean)
- `unset` (boolean)
### SmartFilterQuery
One of the following:
- `SmartFilterAplQuery`
- `SmartFilterNativeMplQuery`
### VisualizeAxisColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"datetime"`, `"integer"`, `"float"`; required)
### VisualizeNumericColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"integer"`, `"float"`; required)
### VisualizeCategoricalColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"string"`, `"boolean"`; required)
### VisualizeColorSettings
Object. Other fields aren't allowed.
- `palette` (string; one of `"axiom"`, `"polychrome"`; required)
- `assignment` (string; one of `"series-name"`, `"series-order"`; required)
### VisualizeAxisSettings
Object. Other fields aren't allowed.
- `scale` (string; one of `"linear"`, `"log"`; required)
- `range` (string; one of `"fit"`, `"includeZero"`; required)
### VisualizeLegendSettings
Object. Other fields aren't allowed.
- `position` (string; one of `"none"`, `"bottom"`, `"right"`; required)
### VisualizeStandardAggregationSettings
Object. Other fields aren't allowed.
- `aggregation` (string; one of `"avg"`, `"sum"`, `"count"`, `"min"`, `"max"`; required)
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### VisualizePercentileAggregationSettings
Object. Other fields aren't allowed.
- `aggregation` (string; one of `"percentile"`; required)
- `percentile` (number; value 0–100; required)
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### SmartFilterAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required): APL query that returns the list of options for the filter dropdown. The result must contain a `key` column and a `value` column — Axiom interprets each row as a `{ key, value }` pair for an option. Use `distinct` to collapse the source field to unique values, then `project` to expose the `key` and `value` columns.
Example:
```
['dataset-name'] | distinct field_name | project key=field_name, value=field_name
```
### SmartFilterNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required): MPL query that returns the list of options for the filter dropdown. The query must group by exactly one tag — Axiom uses each distinct value of that tag as both the key and the value of an option. Use `align using last` to simplify the query.
Example:
```
dataset:metric | align using last | group by tag using count
```
---
# List all dashboards
Source: https://axiom.co/docs/restapi/endpoints/getDashboards
```http
GET https://api.axiom.co/v2/dashboards
```
Lists managed and integration dashboards visible to the caller, sorted by name and paginated together with `limit` and `offset`. Integration dashboards are read-only and have no save version or audit metadata. Labels are resolved unless `exclude=labels`.
If you authenticate with an API token, this endpoint doesn't return private dashboards. It only returns dashboards shared with everyone in your organization or with a group.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `limit` (query; integer (int64); value 1–1000; default `100`)
- `offset` (query; integer (int64); value ≥ 0; default `0`)
- `exclude` (query; string; one of `"labels"`): Exclude resolved label objects from each dashboard response. The labelIds field is still returned.
- `labelIds` (query; array of string; items 1–500): Return dashboards assigned every specified label ID.
## Responses
### 200: Dashboards visible to the caller.
Content type: `application/json`
Type: array of `DashboardResource`
### 400: Invalid label filter
Content type: `application/json`
- `code` (string; required)
- `currentVersion` (integer (int64))
- `message` (string; required)
- `reason` (string)
- `uid` (string)
## Schemas
### DashboardResource
Object.
- `createdAt` (string (date-time); nullable): Creation time, present only for managed dashboards.
- `createdBy` (string; nullable): Creator, present only for managed dashboards.
- `dashboard` (`DashboardDocument`; required)
- `id` (string; required)
- `labelIds` (array of string; required)
- `labelNames` (array of string): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`)
- `type` (string; one of `"managed"`, `"integration"`; required): Managed dashboards are saved documents; integration dashboards are read-only and generated for matching datasets.
- `uid` (string; required): Managed dashboard UID, or stable integration dashboard ID for read requests.
- `updatedAt` (string (date-time); nullable): Last save time, present only for managed dashboards.
- `updatedBy` (string; nullable): Last editor, present only for managed dashboards.
- `updatedByAgent` (boolean): true when the last save came from the MCP server
- `version` (integer (int64); nullable): Save version, present only for managed dashboards.
### DashboardDocument
Same as `Dashboard`.
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### Dashboard
Object. Other fields aren't allowed.
- `name` (string; length 1–100; required)
- `owner` (string; required): User ID of the dashboard owner. Use `X-AXIOM-EVERYONE` to make the dashboard accessible to all users in the organization.
- `description` (string; length ≤ 1000)
- `charts` (array of `Chart`; items ≤ 200; required)
- `layout` (array of `LayoutItem`; items ≤ 200; required)
- `sections` (array of `Section`; items ≤ 1000)
- `refreshTime` (integer; one of `0`, `15`, `60`, `300`; required)
- `schemaVersion` (integer; one of `2`; required)
- `against` (string; one of `"-1h"`, `"-3h"`, `"-6h"`, `"-12h"`, `"-1d"`, `"-3d"`, `"-7d"`, `"-1w"`, `"-2w"`, `"-3w"`, `"-30d"`, `"-60d"`, `"-90d"`): Relative time comparison offset. Compares the current time window against a previous period offset by this duration. Mutually exclusive with `againstTimestamp` — setting one clears the other. Use an empty string or omit to disable comparison.
- `againstTimestamp` (string; length ≤ 100): Absolute or relative timestamp to compare against. Mutually exclusive with `against` — setting one clears the other. Accepts ISO 8601, `now-{duration}` (e.g. `now-1h`), or epoch milliseconds as a string.
- `timeWindowStart` (string; length 1–100; required): Start of the dashboard time range. Use `qr-now-{duration}` for a quick range relative to now, where duration is a number followed by `s` (seconds), `m` (minutes), `h` (hours), `d` (days), or `w` (weeks). Examples: `qr-now-5m`, `qr-now-1h`, `qr-now-7d`. Alternatively, use a Unix epoch millisecond timestamp as a string (e.g. `1704067200000`).
- `timeWindowEnd` (string; length 1–100; required): End of the dashboard time range. Use `qr-now` for a rolling window that tracks the current time (pair with a `qr-now-{duration}` start), or a Unix epoch millisecond timestamp as a string (e.g. `1704153600000`).
- `uid` (string; pattern `^[A-Za-z0-9_-]{1,128}$`): Optional dashboard UID. Must contain only letters, numbers, underscores, or hyphens, with length 1-128 when provided.
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
### Chart
One of the following, selected by `type`:
- `TimeSeriesChart` (`type`: `"TimeSeries"`)
- `HeatmapChart` (`type`: `"Heatmap"`)
- `LogStreamChart` (`type`: `"LogStream"`)
- `PieChart` (`type`: `"Pie"`)
- `ScatterChart` (`type`: `"Scatter"`)
- `TableChart` (`type`: `"Table"`)
- `TopKChart` (`type`: `"TopK"`)
- `StatisticChart` (`type`: `"Statistic"`)
- `GaugeChart` (`type`: `"Gauge"`)
- `NoteChart` (`type`: `"Note"`)
- `MonitorListChart` (`type`: `"MonitorList"`)
- `SmartFilterChart` (`type`: `"SmartFilter"`)
- `SpacerChart` (`type`: `"Spacer"`)
- `VisualizeChart` (`type`: `"Visualize"`)
### LayoutItem
Object. Other fields aren't allowed.
- `i` (string; length 1–200; required)
- `x` (integer; value 0–11; required)
- `y` (number; value ≥ 0; nullable; required)
- `w` (integer; value 1–12; required)
- `h` (number; value 0.5–100; required)
- `minW` (integer; value 1–12)
- `minH` (number; value 0.5–100)
- `maxW` (integer; value 1–12)
- `maxH` (integer; value 1–100)
- `static` (boolean)
### Section
Object. Other fields aren't allowed.
- `id` (string (uuid); required)
- `title` (string; length 1–200; required)
- `defaultCollapsed` (boolean)
### TimeSeriesChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"TimeSeries"`; required)
- `name` (string; length 1–500)
- `query` (`TimeSeriesChartQuery`; required)
### HeatmapChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Heatmap"`; required)
- `name` (string; length 1–500)
- `query` (`HeatmapChartQuery`; required)
- `colorScheme` (string; one of `"Blue"`, `"Orange"`, `"Red"`, `"Purple"`, `"Teal"`, `"Yellow"`, `"Green"`, `"Pink"`, `"Grey"`, `"Brown"`)
### LogStreamChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"LogStream"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `tableSettings` (`TableSettings`)
### PieChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Pie"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### ScatterChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Scatter"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### TableChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Table"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `tableSettings` (`TableSettings`)
### TopKChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"TopK"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### StatisticChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Statistic"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `colorScheme` (string; one of `"Blue"`, `"Orange"`, `"Red"`, `"Purple"`, `"Teal"`, `"Yellow"`, `"Green"`, `"Pink"`, `"Grey"`, `"Brown"`)
- `customUnits` (string; length ≤ 200)
- `showChart` (one of boolean, string)
- `hideValue` (boolean)
- `chartHeight` (one of string; length ≤ 100, number)
- `errorThreshold` (string; one of `"Above"`, `"AboveOrEqual"`, `"Below"`, `"BelowOrEqual"`, `"AboveOrBelow"`)
- `errorThresholdValue` (string; length ≤ 100)
- `warningThreshold` (string; one of `"Above"`, `"AboveOrEqual"`, `"Below"`, `"BelowOrEqual"`, `"AboveOrBelow"`)
- `warningThresholdValue` (string; length ≤ 100)
- `roundTo` (integer; value 0–10)
- `invertTheme` (boolean)
- `background` (string; length ≤ 200)
- `textColor` (string; length ≤ 200)
- `labelColor` (string; length ≤ 200)
- `chartFillColor` (string; length ≤ 200)
- `okColorProps` (`StatisticChartColorProps`)
- `warningColorProps` (`StatisticChartColorProps`)
- `errorColorProps` (`StatisticChartColorProps`)
### GaugeChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Gauge"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `segments` (array of `GaugeChartSegment`; items 1–100; required)
- `colorScale` (string; one of `"green-to-red"`, `"red-to-green"`)
- `showRing` (boolean)
- `labelMode` (string; one of `"none"`, `"boundaries"`, `"intervals"`)
- `showSparkline` (boolean)
- `scaleToTimeRange` (boolean)
- `scaleBaseDurationMs` (number; value > 0)
- `customUnits` (string; length ≤ 200)
### NoteChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Note"`; required)
- `text` (string; length 1–100000; required)
- `variant` (string; one of `""`, `"default"`, `"plain"`; nullable)
### MonitorListChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"MonitorList"`; required)
- `name` (string; length 1–500)
- `selectedMonitors` (array of string; length 1–200; items 1–200; required)
- `columns` (`MonitorListColumns`; required)
### SmartFilterChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"SmartFilter"`; required)
- `name` (string; length 1–500)
- `filters` (array of `SmartFilterConfig`; items 1–50; required)
- `logo` (string; length ≤ 2000)
- `logoDark` (string; length ≤ 2000)
### SpacerChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Spacer"`; required)
- `name` (string; length 1–500)
- `variant` (string; one of `"transparent"`, `"dashed"`, `"solid"`)
### VisualizeChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Visualize"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `visualization` (`VisualizeConfiguration`; required)
### TimeSeriesChartQuery
One of the following:
- `TimeSeriesNonMetricsAplQuery`
- `TimeSeriesNativeMplQuery`
### HeatmapChartQuery
One of the following:
- `HeatmapNonMetricsAplQuery`
- `HeatmapNativeMplQuery`
### SimpleChartQuery
One of the following:
- `SimpleNonMetricsAplQuery`
- `SimpleNativeMplQuery`
### TableSettings
Object. Other fields aren't allowed.
- `columns` (array of `ColumnSetting`; items ≤ 500)
- `settings` (`DatasetStreamSettings`)
### StatisticChartColorProps
Object. Other fields aren't allowed.
- `background` (string; length ≤ 200)
- `chartFillColor` (string; length ≤ 200)
- `labelColor` (string; length ≤ 200)
- `textColor` (string; length ≤ 200)
### GaugeChartSegment
Object. Other fields aren't allowed.
- `from` (number; required)
- `to` (number; required)
### MonitorListColumns
Object. Other fields aren't allowed.
- `status` (boolean; required)
- `history` (boolean; required)
- `dataset` (boolean; required)
- `type` (boolean; required)
- `notifiers` (boolean; required)
### SmartFilterConfig
One of the following:
- `SmartFilterSearch`
- `SmartFilterSelect`
### VisualizeConfiguration
One of the following, selected by `type`:
- `ScatterVisualization` (`type`: `"scatter"`)
- `BarVisualization` (`type`: `"bar"`)
- `HorizontalBarVisualization` (`type`: `"horizontalBar"`)
- `HistogramVisualization` (`type`: `"histogram"`)
- `FrequencyBarVisualization` (`type`: `"frequencyBar"`)
- `VisualizeHeatmap` (`type`: `"heatmap"`)
### TimeSeriesNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
- `queryOptions` (`TimeSeriesQueryOptions`)
### TimeSeriesNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
- `queryOptions` (`TimeSeriesQueryOptions`)
### HeatmapNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
- `queryOptions` (`HeatmapQueryOptions`)
### HeatmapNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
- `queryOptions` (`HeatmapQueryOptions`)
### SimpleNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
### SimpleNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
### ColumnSetting
One of the following:
- string; length ≤ 500
- `AdvancedColumnSetting`
### DatasetStreamSettings
Object. Other fields aren't allowed.
- `fontSize` (string; length ≤ 20; pattern `^\d+px$`)
- `highlightSeverity` (boolean)
- `showRaw` (boolean)
- `showEvent` (boolean)
- `showTimestamp` (boolean)
- `wrapLines` (boolean)
- `hideNulls` (boolean)
- `fitColumns` (boolean)
### SmartFilterSearch
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `type` (string; one of `"search"`; required)
### SmartFilterSelect
One of the following, selected by `selectType`:
- `SmartFilterSelectList` (`selectType`: `"list"`)
- `SmartFilterSelectQuery` (`selectType`: `"query"`)
### ScatterVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"scatter"`; required)
- `bindings` (`ScatterVisualizationBindings`; required)
- `settings` (`ScatterVisualizationSettings`; required)
### BarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"bar"`; required)
- `bindings` (`BarVisualizationBindings`; required)
- `settings` (`VisualizeBarSettings`; required)
### HorizontalBarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"horizontalBar"`; required)
- `bindings` (`HorizontalBarVisualizationBindings`; required)
- `settings` (`VisualizeBarSettings`; required)
### HistogramVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"histogram"`; required)
- `bindings` (`HistogramVisualizationBindings`; required)
- `settings` (`HistogramVisualizationSettings`; required)
### FrequencyBarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"frequencyBar"`; required)
- `bindings` (`FrequencyBarVisualizationBindings`; required)
- `settings` (`FrequencyBarVisualizationSettings`; required)
### VisualizeHeatmap
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"heatmap"`; required)
- `bindings` (`VisualizeHeatmapBindings`; required)
- `settings` (`VisualizeHeatmapSettings`; required)
### TimeSeriesQueryOptions
Object. Other fields aren't allowed.
- `displayNull` (string; one of `"auto"`, `"null"`, `"span"`, `"zero"`, `""`): Controls how empty intervals are rendered in time series charts. `auto` infers from the query, `null` leaves gaps, `span` connects adjacent points, `zero` fills with zero.
- `overlayCharts` (string; one of `"true"`, `"false"`, `""`): When enabled, charts are overlaid on a single chart instead of stacked separately.
- `shownColumns` (string; length ≤ 10000)
- `timeSeriesVariant` (string; one of `"area"`, `"bars"`, `"line"`, `"lines"`, `""`)
- `timeSeriesView` (string; one of `"charts"`, `"resultsTable"`, `"charts|resultsTable"`, `""`)
### HeatmapQueryOptions
Object. Other fields aren't allowed.
- `timeSeriesView` (string; one of `"charts"`, `"resultsTable"`, `"charts|resultsTable"`, `""`)
### AdvancedColumnSetting
Object. Other fields aren't allowed.
- `name` (string; length ≤ 500; required)
- `width` (integer; value > 0, ≤ 9007199254740991)
### SmartFilterSelectList
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `options` (`SmartFilterOptions`)
- `type` (string; one of `"select"`; required)
- `selectType` (string; one of `"list"`; required)
### SmartFilterSelectQuery
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `options` (all of one of array of `SmartFilterOption`; items ≤ 200, string; one of `null`; nullable, string; one of `""`): Pre-defined options merged with the dynamic options returned by `query` at runtime. Typically used to seed a default option (for example an "All" entry with `unset: true`) so the filter has a sensible initial selection before — or independent of — query results.
- `type` (string; one of `"select"`; required)
- `selectType` (string; one of `"query"`; required)
- `query` (`SmartFilterQuery`)
### ScatterVisualizationBindings
Object. Other fields aren't allowed.
- `x` (`VisualizeAxisColumnRef`; required)
- `y` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### ScatterVisualizationSettings
Object. Other fields aren't allowed.
- `colors` (`VisualizeColorSettings`)
- `xAxis` (`VisualizeAxisSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### BarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
- `value` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### VisualizeBarSettings
One of the following:
- `VisualizeStandardAggregationSettings`
- `VisualizePercentileAggregationSettings`
### HorizontalBarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
- `value` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### HistogramVisualizationBindings
Object. Other fields aren't allowed.
- `value` (`VisualizeNumericColumnRef`; required)
### HistogramVisualizationSettings
Object. Other fields aren't allowed.
- `binCount` (integer; value 1–200; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
### FrequencyBarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
### FrequencyBarVisualizationSettings
Object. Other fields aren't allowed.
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
### VisualizeHeatmapBindings
Object. Other fields aren't allowed.
- `x` (`VisualizeCategoricalColumnRef`; required)
- `y` (`VisualizeCategoricalColumnRef`; required)
### VisualizeHeatmapSettings
Object. Other fields aren't allowed.
- `categoryLimit` (integer; value 1–100; required)
### SmartFilterOptions
One of the following:
- array of `SmartFilterOption`; items ≤ 200
- string; one of `null`; nullable
- string; one of `""`
### SmartFilterOption
Object. Other fields aren't allowed.
- `key` (string; length ≤ 500; required)
- `value` (string; length ≤ 10000; required)
- `default` (boolean)
- `unset` (boolean)
### SmartFilterQuery
One of the following:
- `SmartFilterAplQuery`
- `SmartFilterNativeMplQuery`
### VisualizeAxisColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"datetime"`, `"integer"`, `"float"`; required)
### VisualizeNumericColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"integer"`, `"float"`; required)
### VisualizeCategoricalColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"string"`, `"boolean"`; required)
### VisualizeColorSettings
Object. Other fields aren't allowed.
- `palette` (string; one of `"axiom"`, `"polychrome"`; required)
- `assignment` (string; one of `"series-name"`, `"series-order"`; required)
### VisualizeAxisSettings
Object. Other fields aren't allowed.
- `scale` (string; one of `"linear"`, `"log"`; required)
- `range` (string; one of `"fit"`, `"includeZero"`; required)
### VisualizeLegendSettings
Object. Other fields aren't allowed.
- `position` (string; one of `"none"`, `"bottom"`, `"right"`; required)
### VisualizeStandardAggregationSettings
Object. Other fields aren't allowed.
- `aggregation` (string; one of `"avg"`, `"sum"`, `"count"`, `"min"`, `"max"`; required)
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### VisualizePercentileAggregationSettings
Object. Other fields aren't allowed.
- `aggregation` (string; one of `"percentile"`; required)
- `percentile` (number; value 0–100; required)
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### SmartFilterAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required): APL query that returns the list of options for the filter dropdown. The result must contain a `key` column and a `value` column — Axiom interprets each row as a `{ key, value }` pair for an option. Use `distinct` to collapse the source field to unique values, then `project` to expose the `key` and `value` columns.
Example:
```
['dataset-name'] | distinct field_name | project key=field_name, value=field_name
```
### SmartFilterNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required): MPL query that returns the list of options for the filter dropdown. The query must group by exactly one tag — Axiom uses each distinct value of that tag as both the key and the value of an option. Use `align using last` to simplify the query.
Example:
```
dataset:metric | align using last | group by tag using count
```
---
# Retrieve dataset
Source: https://axiom.co/docs/restapi/endpoints/getDataset
```http
GET https://api.axiom.co/v2/datasets/{dataset_id}
```
Retrieves a dataset by its name.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_id` (path; string; required)
- `exclude` (query; string; one of `"labels"`): Exclude resolved label objects from the dataset response. The labelIds and labelNames fields are still returned.
## Responses
### 200: Dataset.
Content type: `application/json`
- `canWrite` (boolean): Whether this dataset has write access
- `created` (string (date-time); required): The RFC3339-formatted time when the dataset was created.
- `createdByAgent` (boolean): true when the MCP server created this dataset
- `description` (string; required): Dataset description
- `edgeDeployment` (string): Edge deployment of the dataset
- `edgeDeploymentUrl` (string): URL of the edge deployment
- `id` (string; required): Dataset ID
- `kind` (string; one of `"otel:metrics:v1"`, `"otel:traces:v1"`, `"otel:logs:v1"`, `"axiom:events:v1"`; default `"axiom:events:v1"`; required): The kind of the dataset
- `labelIds` (array of string; required): IDs of labels assigned to this dataset.
- `labelNames` (array of string; required): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`): Resolved labels assigned to this dataset.
- `mapFields` (array of string)
- `name` (string; required): Unique dataset name
- `reclaimableFields` (integer (int64)): Number of unused fields a vacuum can reclaim, when the dataset is a vacuum candidate
- `retentionDays` (integer): Number of days to retain data in the dataset
- `sharedByOrg` (string): ID of the org that shared this resource, if it's shared
- `updatedAt` (string (date-time); required): The RFC3339-formatted time when the dataset was last updated.
- `useRetentionPeriod` (boolean): Whether to use the retention period
- `vacuumCandidate` (boolean): Whether the dataset has unused fields that a vacuum can reclaim
- `who` (string; required): Name of the dataset creator
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
---
# Get metric tag values for a dataset
Source: https://axiom.co/docs/restapi/endpoints/getDatasetMetricTagValues
```http
GET https://{axiom-domain}/v1/query/metrics/info/datasets/{dataset}/metrics/{metric}/tags/{tag}/values
```
Lists the values of a tag on one metric in a metrics dataset between `start` and `end`. Values keep their original type, so the array can mix strings and numbers. Unknown metrics or tags return an empty array.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset` (path; string; required): The dataset to retrieve metric tag values from
- `metric` (path; string; required): The metric name to retrieve tag values for
- `tag` (path; string; required): The tag name to retrieve values for
- `start` (query; string; required): Start time for timeframe to return (RFC3339 format)
- `end` (query; string; required): End time for timeframe to return (RFC3339 format)
## Responses
### 200: Tag values. Each value is a string, number, or boolean.
Content type: `application/json`
Type: array of any
Content type: `application/vnd.metrics-info.v2+json`
Type: array of any
### 404: Dataset not found.
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
Content type: `application/vnd.metrics-info.v2+json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
### default: User or system error
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
Content type: `application/vnd.metrics-info.v2+json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
---
# Get metric tags for a dataset
Source: https://axiom.co/docs/restapi/endpoints/getDatasetMetricTags
```http
GET https://{axiom-domain}/v1/query/metrics/info/datasets/{dataset}/metrics/{metric}/tags
```
Lists the tag names used by a metric in a metrics dataset between `start` and `end`. Returns an empty array when the metric has no data in the range.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset` (path; string; required): The dataset to retrieve metric tags from
- `metric` (path; string; required): The metric name to retrieve tags for
- `start` (query; string; required): Start time for timeframe to return (RFC3339 format)
- `end` (query; string; required): End time for timeframe to return (RFC3339 format)
## Responses
### 200: Tag names.
Content type: `application/json`
Type: array of string
Content type: `application/vnd.metrics-info.v2+json`
Type: array of string
### 404: Dataset not found.
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
Content type: `application/vnd.metrics-info.v2+json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
### default: User or system error
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
Content type: `application/vnd.metrics-info.v2+json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
---
# Get metrics for a dataset
Source: https://axiom.co/docs/restapi/endpoints/getDatasetMetrics
```http
GET https://{axiom-domain}/v1/query/metrics/info/datasets/{dataset}/metrics
```
Lists the metric names in a metrics dataset between `start` and `end`. With `Accept: application/vnd.metrics-info.v2+json`, returns an object keyed by metric name with each metric's `type`, `temporality`, and `unit` instead.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset` (path; string; required): The dataset to retrieve metrics from
- `start` (query; string; required): Start time for timeframe to return (RFC3339 format)
- `end` (query; string; required): End time for timeframe to return (RFC3339 format)
## Responses
### 200: Metric names. With `Accept: application/vnd.metrics-info.v2+json`, an object keyed by metric name whose values have `type` (for example `Gauge`), `temporality` (for example `Cumulative`, or null), and `unit` (empty string when not defined).
Content type: `application/json`
Type: array of string
Content type: `application/vnd.metrics-info.v2+json`
Type: array of string
### 404: Dataset not found.
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
Content type: `application/vnd.metrics-info.v2+json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
### default: User or system error
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
Content type: `application/vnd.metrics-info.v2+json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
---
# Get tag values for a dataset
Source: https://axiom.co/docs/restapi/endpoints/getDatasetTagValues
```http
GET https://{axiom-domain}/v1/query/metrics/info/datasets/{dataset}/tags/{tag}/values
```
Lists the values of a tag across all metrics in a metrics dataset between `start` and `end`. Values keep their original type, so the array can mix strings and numbers. Unknown tags return an empty array.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset` (path; string; required): The dataset to retrieve tag values from
- `tag` (path; string; required): The tag name to retrieve values for
- `start` (query; string; required): Start time for timeframe to return (RFC3339 format)
- `end` (query; string; required): End time for timeframe to return (RFC3339 format)
## Responses
### 200: Tag values. Each value is a string, number, or boolean.
Content type: `application/json`
Type: array of any
Content type: `application/vnd.metrics-info.v2+json`
Type: array of any
### 404: Dataset not found.
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
Content type: `application/vnd.metrics-info.v2+json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
### default: User or system error
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
Content type: `application/vnd.metrics-info.v2+json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
---
# Get tags for a dataset
Source: https://axiom.co/docs/restapi/endpoints/getDatasetTags
```http
GET https://{axiom-domain}/v1/query/metrics/info/datasets/{dataset}/tags
```
Lists the tag names that occur in a metrics dataset between `start` and `end`. Both times are required and use RFC 3339 format.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset` (path; string; required): The dataset to retrieve tags from
- `start` (query; string; required): Start time for timeframe to return (RFC3339 format)
- `end` (query; string; required): End time for timeframe to return (RFC3339 format)
## Responses
### 200: Tag names.
Content type: `application/json`
Type: array of string
Content type: `application/vnd.metrics-info.v2+json`
Type: array of string
### 404: Dataset not found.
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
Content type: `application/vnd.metrics-info.v2+json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
### default: User or system error
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
Content type: `application/vnd.metrics-info.v2+json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
---
# List all datasets
Source: https://axiom.co/docs/restapi/endpoints/getDatasets
```http
GET https://api.axiom.co/v2/datasets
```
Lists the datasets you can read, including datasets shared with your organization, sorted by name. Returns all matching datasets in one response without pagination.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `exclude` (query; string; one of `"labels"`): Exclude resolved label objects from each dataset response. The labelIds and labelNames fields are still returned.
- `label` (query; array of string; items 1–500): Filter by label names in your organization. Repeat the parameter for multiple names, for example ?label=prod&label=team-a. Names match case-insensitively after whitespace normalization; duplicates count once. Commas are part of a name, not separators. Reading resources never creates missing labels.
- `labelMatch` (query; string; one of `"any"`, `"all"`; default `"any"`): How to combine label names: any (the default) requires at least one requested label on a resource; all requires every requested label on that same resource. For example, ?label=prod&label=team-a matches either label, while ?label=prod&label=team-a&labelMatch=all requires both. Unknown names have no matches with any and make all return no resources. Without label parameters, labelMatch has no effect.
- `labelIds` (query; array of string; items 1–500): Return datasets assigned every specified label ID. When combined with label names, both filters must match; labelMatch applies only to names.
## Responses
### 200: Datasets you can read.
Content type: `application/json`
Type: array of `Dataset`
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### Dataset
Object.
- `canWrite` (boolean): Whether this dataset has write access
- `created` (string (date-time); required): The RFC3339-formatted time when the dataset was created.
- `createdByAgent` (boolean): true when the MCP server created this dataset
- `description` (string; required): Dataset description
- `edgeDeployment` (string): Edge deployment of the dataset
- `edgeDeploymentUrl` (string): URL of the edge deployment
- `id` (string; required): Dataset ID
- `kind` (string; one of `"otel:metrics:v1"`, `"otel:traces:v1"`, `"otel:logs:v1"`, `"axiom:events:v1"`; default `"axiom:events:v1"`; required): The kind of the dataset
- `labelIds` (array of string; required): IDs of labels assigned to this dataset.
- `labelNames` (array of string; required): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`): Resolved labels assigned to this dataset.
- `mapFields` (array of string)
- `name` (string; required): Unique dataset name
- `reclaimableFields` (integer (int64)): Number of unused fields a vacuum can reclaim, when the dataset is a vacuum candidate
- `retentionDays` (integer): Number of days to retain data in the dataset
- `sharedByOrg` (string): ID of the org that shared this resource, if it's shared
- `updatedAt` (string (date-time); required): The RFC3339-formatted time when the dataset was last updated.
- `useRetentionPeriod` (boolean): Whether to use the retention period
- `vacuumCandidate` (boolean): Whether the dataset has unused fields that a vacuum can reclaim
- `who` (string; required): Name of the dataset creator
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
---
# Retrieve field in dataset
Source: https://axiom.co/docs/restapi/endpoints/getFieldForDataset
```http
GET https://api.axiom.co/v2/datasets/{dataset_id}/fields/{field_id}
```
Retrieves a field in the schema of a dataset by its name. Not supported for metrics datasets.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_id` (path; string; required)
- `field_id` (path; string; required)
## Responses
### 200: Field.
Content type: `application/json`
- `description` (string): Description of the field
- `hidden` (boolean): Whether the field is hidden
- `name` (string; required): Name of the field
- `type` (string; required): Type of the field
- `unit` (string): Unit of the field
### 400: The dataset is a metrics dataset.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: The dataset doesn't exist or the field isn't in its schema.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
---
# List all fields in dataset
Source: https://axiom.co/docs/restapi/endpoints/getFieldsForDataset
```http
GET https://api.axiom.co/v2/datasets/{dataset_id}/fields
```
Lists the fields in the schema of a dataset with their type, unit, description, and hidden setting. Not supported for metrics datasets.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_id` (path; string; required)
## Responses
### 200: Fields in the dataset.
Content type: `application/json`
Type: array of `DatasetField`
### 400: The dataset is a metrics dataset.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### DatasetField
Object.
- `description` (string): Description of the field
- `hidden` (boolean): Whether the field is hidden
- `name` (string; required): Name of the field
- `type` (string; required): Type of the field
- `unit` (string): Unit of the field
---
# Retrieve group
Source: https://axiom.co/docs/restapi/endpoints/getGroupById
```http
GET https://api.axiom.co/v2/rbac/groups/{id}
```
Retrieves a group by ID with its role IDs, member user IDs, and whether it's managed by your identity provider (`isManaged`).
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Unique identifier of the group to retrieve
## Responses
### 200: The group.
Content type: `application/json`
Type: `GroupWithID`
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### GroupWithID
Extends the base Group type to include a unique identifier
All of the following:
- `Group`
- Object with:
- `id` (string; required): Unique identifier for the group
### Group
Defines a group of users for organizational purposes
Object.
- `description` (string): Detailed description of the group's purpose and scope
- `isManaged` (boolean; read-only): Whether the group is synced from your identity provider. You can't delete a managed group or change its members.
- `members` (array of string): List of user IDs that are assigned to this group
- `name` (string; required): Unique name identifier for the group
- `roles` (array of string): IDs of the roles assigned to the group. Use a custom role ID or a built-in role ID: `axiom-owner`, `axiom-admin`, `axiom-user`, `axiom-read-only`, or `axiom-none`.
---
# Check Splunk HEC health
Source: https://axiom.co/docs/restapi/endpoints/getHecHealth
```http
GET https://hec.{axiom-domain}/services/collector/health
```
Reports whether the HEC endpoint is accepting data. Requires no authentication and returns HEC code `17` when healthy.
Use this endpoint to check whether the Splunk HTTP Event Collector (HEC) compatible API is available. No authentication is required. For more information, see [Send data using the Splunk HEC API](/send-data/splunk-hec).
The base domain for this endpoint is `hec.` prefixed to the base domain of your edge deployment. For example, if your edge deployment’s base domain is `us-east-1.aws.edge.axiom.co`, the HEC endpoint is `https://hec.us-east-1.aws.edge.axiom.co`.
## Authentication
No authentication required.
## Responses
### 200: The collector is healthy.
Content type: `application/json`
The Splunk HEC status envelope.
- `text` (string; required): A human-readable status message.
- `code` (integer; required): The Splunk status code. `0` indicates success, `17` indicates a healthy collector, and `5`, `6`, and `7` indicate no data, invalid data format, and incorrect index respectively.
---
# Retrieve label
Source: https://axiom.co/docs/restapi/endpoints/getLabel
```http
GET https://api.axiom.co/v2/labels/{id}
```
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; pattern `^lbl_`; required)
## Responses
### 200: Label details, including assigned resources.
Content type: `application/json`
- `assigned_resources` (array of `LabelAssignedResource`; required)
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
- `resources_count` (`LabelResourcesCount`; required)
### 400: Invalid label ID
### 404: Label not found
## Schemas
### LabelAssignedResource
Object.
- `dataset` (string): Set only for frontend-generated integration dashboards.
- `id` (string): Uses the same public identifier as LabelAssignmentTarget.id.
- `templateId` (string): Set only for frontend-generated integration dashboards.
- `type` (string; one of `"dashboard"`, `"integration_dashboard"`, `"dataset"`, `"monitor"`, `"notifier"`; required)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
### LabelResourcesCount
Object.
- `dashboards` (integer (int64); required)
- `datasets` (integer (int64); required)
- `monitors` (integer (int64); required)
- `notifiers` (integer (int64); required)
- `total` (integer (int64); required)
---
# List all labels
Source: https://axiom.co/docs/restapi/endpoints/getLabels
```http
GET https://api.axiom.co/v2/labels
```
Returns labels as JSON, or the labels Agent Skill when the request negotiates text/markdown.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `name` (query; string): Filter labels by name.
## Responses
### 200: Labels
Content type: `application/json`
Type: array of `LabelSummary`
Content type: `text/markdown`
Type: array of `LabelSummary`
## Schemas
### LabelSummary
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
- `resources_count` (`LabelResourcesCount`; required)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
### LabelResourcesCount
Object.
- `dashboards` (integer (int64); required)
- `datasets` (integer (int64); required)
- `monitors` (integer (int64); required)
- `notifiers` (integer (int64); required)
- `total` (integer (int64); required)
---
# List all map fields
Source: https://axiom.co/docs/restapi/endpoints/getMapFields
```http
GET https://api.axiom.co/v2/datasets/{dataset_id}/mapfields
```
Lists the names of the fields configured as map fields in a dataset.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_id` (path; string; required)
## Responses
### 200: Map field names.
Content type: `application/json`
Type: `MapFields`
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### MapFields
A list of map field names
Type: array of string
---
# Retrieve monitor
Source: https://axiom.co/docs/restapi/endpoints/getMonitor
```http
GET https://api.axiom.co/v2/monitors/{id}
```
Retrieves a monitor by ID. Returns `404` if the monitor doesn't exist or the caller can't query its datasets. Labels are resolved unless `exclude=labels`.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Monitor ID.
- `exclude` (query; string; one of `"labels"`): Exclude resolved label objects from the monitor response. The labelIds and labelNames fields are still returned.
## Responses
### 200: Monitor.
Content type: `application/json`
Type: `MonitorWithId`
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### MonitorWithId
Monitor configuration with its unique identifier
All of the following:
- `Monitor`
- Object with:
- `createdAt` (string (date-time)): Timestamp when the monitor was created
- `createdBy` (string): ID of the user who created the monitor
- `createdByAgent` (boolean): true when the MCP server created this monitor
- `datasets` (array of string): Dataset names referenced by the monitor query.
- `id` (string; required): Unique identifier for the monitor
- `labelIds` (array of string; required): IDs of labels assigned to this monitor.
- `labelNames` (array of string; required): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`): Resolved labels assigned to this monitor.
- `lastError` (string): Most recent error encountered while evaluating the monitor.
- `updatedAt` (string (date-time)): Timestamp when the monitor was last updated
### Monitor
Configuration for a monitoring rule. Monitors can be configured to:
- Check threshold values (e.g., CPU usage > 90%)
- Match specific events in logs
- Detect anomalies based on historical patterns
Each monitor runs on a specified interval and can trigger notifications through configured notifiers.
Object.
- `alertOnNoData` (boolean): Whether to alert when no data is received
- `aplQuery` (string): APL (Axiom Processing Language) query string used for monitoring.
This query defines what data to analyze and how to process it.
At least one of aplQuery or mplQuery must be provided.
- `backfillDays` (integer (int64)): NewValues monitors only. Before the first evaluation, the values the query returns over this many days are recorded as seen, so they do not alert. Must not exceed lookbackDays. 0 disables the backfill.
- `columnName` (string): Name of the column to monitor
- `compareDays` (number (int64); value ≤ 7): Number of days to compare for anomaly detection
- `description` (string): Detailed description of the monitor's purpose
- `disabled` (boolean): Whether the monitor is currently disabled
- `disabledUntil` (string (date-time); nullable): Timestamp until when the monitor should remain disabled
- `includeChart` (boolean): Whether to include a query chart in triggered notifications
- `intervalMinutes` (integer (int64); value ≥ 1): How frequently the monitor should run, in minutes.
Minimum value is 1 minute.
- `lookbackDays` (integer (int64); value ≥ 1): NewValues monitors only. A value counts as new when it was not seen in this many days.
- `mplQuery` (string): MPL (Metrics Processing Language) query string for metrics-based monitoring.
Use this as an alternative to aplQuery for metrics datasets.
At least one of aplQuery or mplQuery must be provided.
- `name` (string; required): Name of the monitor
- `notifierIds` (array of string): List of notifier IDs that will receive alerts.
Notifiers can be email, Slack, webhook endpoints, etc.
- `notifyByGroup` (boolean): Whether to group notifications
- `notifyEveryRun` (boolean): Whether to send notifications on every check
- `operator` (string; one of `"Below"`, `"BelowOrEqual"`, `"Above"`, `"AboveOrEqual"`, `"AboveOrBelow"`): Comparison operator for threshold checks:
- Below: Trigger when value < threshold
- BelowOrEqual: Trigger when value <= threshold
- Above: Trigger when value > threshold
- AboveOrEqual: Trigger when value >= threshold
- AboveOrBelow: Trigger when value is outside a range
- `rangeMinutes` (integer (int64); value ≥ 1): Time window to evaluate in each check, in minutes.
For example, "last 5 minutes of data"
- `resolvable` (boolean): Whether the alert can be manually resolved
- `secondDelay` (number (int64); value ≤ 86400): Number of seconds to move each run's query window into the past, so data that arrives late is included.
For example, with a value of 300, a run at 10:05 queries up to 10:00.
- `skipResolved` (boolean): Whether to skip resolved alerts
- `threshold` (number (double)): Threshold value for triggering the alert
- `tolerance` (number; value ≤ 100): Tolerance percentage for anomaly detection
- `trackedValue` (string): NewValues monitors only, and required for them. The column of the query result whose values are checked for new ones.
- `triggerAfterNPositiveResults` (number (int64)): Number of runs among the last `triggerFromNRuns` runs, including the current one, that must meet the trigger condition for the monitor to trigger.
The current run must always meet it.
For example, set both fields to 3 to trigger only after 3 consecutive runs meet the condition.
If unset or 0, the first run that meets the condition triggers.
Values above `triggerFromNRuns` are lowered to it when the monitor is saved.
Applies to Threshold and AnomalyDetection monitors.
- `triggerFromNRuns` (number (int64)): Number of most recent runs, including the current one, that the monitor looks at when deciding whether to trigger.
Has no effect unless `triggerAfterNPositiveResults` is also set.
Applies to Threshold and AnomalyDetection monitors.
- `type` (string; one of `"Threshold"`, `"MatchEvent"`, `"AnomalyDetection"`, `"NewValues"`; required): Type of monitoring check to perform:
- Threshold: Compares a numeric value against a threshold
- MatchEvent: Looks for specific events or patterns
- AnomalyDetection: Identifies unusual patterns based on historical data
- NewValues: Alerts when the trackedValue column of the query result holds a value not seen within lookbackDays. Each run queries the last rangeMinutes, which defaults to intervalMinutes and cannot be less. Sends one notification per new value.
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
---
# Retrieve monitor notification history
Source: https://axiom.co/docs/restapi/endpoints/getMonitorHistory
```http
GET https://api.axiom.co/v2/monitors/{id}/history
```
Lists the notifications sent for the monitor between `startTime` and `endTime`. Each delivery is a separate item: one per notifier, and one per recipient for email notifiers. Failed deliveries are included. State changes that sent no notification, for example while the monitor had no notifiers, aren't listed. The caller needs query access to the monitor's datasets.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Monitor ID.
- `startTime` (query; string (date-time); required): Start of the time range (RFC 3339).
- `endTime` (query; string (date-time); required): End of the time range (RFC 3339). Must not be before `startTime`.
## Responses
### 200: Notifications sent in the time range.
Content type: `application/json`
Type: array of `AlertHistory`
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### AlertHistory
A notification sent for a monitor.
Object.
- `checkId` (string; required): ID of the monitor
- `name` (string; required): Title of the notification: `Triggered: ` or `Resolved: ` followed by the monitor name
- `state` (string; one of `"open"`, `"closed"`; required): `open` if the notification reported that the monitor triggered, `closed` if it reported that the monitor resolved
- `timestamp` (string (date-time); required): Time the delivery was recorded, after any retries
---
# List all monitors
Source: https://axiom.co/docs/restapi/endpoints/getMonitors
```http
GET https://api.axiom.co/v2/monitors
```
Lists monitors in the organization, sorted by name. Only returns monitors that query at least one dataset visible to the caller. Labels are resolved unless `exclude=labels`.
The API endpoint `/v2/monitors` only returns monitors for datasets that your API token has query access to. If the API returns an empty list, ensure your token has query permissions for the datasets used by your monitors.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `exclude` (query; string; one of `"labels"`): Exclude resolved label objects from each monitor response. The labelIds and labelNames fields are still returned.
- `label` (query; array of string; items 1–500): Filter by label names in your organization. Repeat the parameter for multiple names, for example ?label=prod&label=team-a. Names match case-insensitively after whitespace normalization; duplicates count once. Commas are part of a name, not separators. Reading resources never creates missing labels.
- `labelMatch` (query; string; one of `"any"`, `"all"`; default `"any"`): How to combine label names: any (the default) requires at least one requested label on a resource; all requires every requested label on that same resource. For example, ?label=prod&label=team-a matches either label, while ?label=prod&label=team-a&labelMatch=all requires both. Unknown names have no matches with any and make all return no resources. Without label parameters, labelMatch has no effect.
- `labelIds` (query; array of string; items 1–500): Return monitors assigned every specified label ID. When combined with label names, both filters must match; labelMatch applies only to names.
## Responses
### 200: Monitors visible to the caller.
Content type: `application/json`
Type: array of `MonitorWithId`
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### MonitorWithId
Monitor configuration with its unique identifier
All of the following:
- `Monitor`
- Object with:
- `createdAt` (string (date-time)): Timestamp when the monitor was created
- `createdBy` (string): ID of the user who created the monitor
- `createdByAgent` (boolean): true when the MCP server created this monitor
- `datasets` (array of string): Dataset names referenced by the monitor query.
- `id` (string; required): Unique identifier for the monitor
- `labelIds` (array of string; required): IDs of labels assigned to this monitor.
- `labelNames` (array of string; required): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`): Resolved labels assigned to this monitor.
- `lastError` (string): Most recent error encountered while evaluating the monitor.
- `updatedAt` (string (date-time)): Timestamp when the monitor was last updated
### Monitor
Configuration for a monitoring rule. Monitors can be configured to:
- Check threshold values (e.g., CPU usage > 90%)
- Match specific events in logs
- Detect anomalies based on historical patterns
Each monitor runs on a specified interval and can trigger notifications through configured notifiers.
Object.
- `alertOnNoData` (boolean): Whether to alert when no data is received
- `aplQuery` (string): APL (Axiom Processing Language) query string used for monitoring.
This query defines what data to analyze and how to process it.
At least one of aplQuery or mplQuery must be provided.
- `backfillDays` (integer (int64)): NewValues monitors only. Before the first evaluation, the values the query returns over this many days are recorded as seen, so they do not alert. Must not exceed lookbackDays. 0 disables the backfill.
- `columnName` (string): Name of the column to monitor
- `compareDays` (number (int64); value ≤ 7): Number of days to compare for anomaly detection
- `description` (string): Detailed description of the monitor's purpose
- `disabled` (boolean): Whether the monitor is currently disabled
- `disabledUntil` (string (date-time); nullable): Timestamp until when the monitor should remain disabled
- `includeChart` (boolean): Whether to include a query chart in triggered notifications
- `intervalMinutes` (integer (int64); value ≥ 1): How frequently the monitor should run, in minutes.
Minimum value is 1 minute.
- `lookbackDays` (integer (int64); value ≥ 1): NewValues monitors only. A value counts as new when it was not seen in this many days.
- `mplQuery` (string): MPL (Metrics Processing Language) query string for metrics-based monitoring.
Use this as an alternative to aplQuery for metrics datasets.
At least one of aplQuery or mplQuery must be provided.
- `name` (string; required): Name of the monitor
- `notifierIds` (array of string): List of notifier IDs that will receive alerts.
Notifiers can be email, Slack, webhook endpoints, etc.
- `notifyByGroup` (boolean): Whether to group notifications
- `notifyEveryRun` (boolean): Whether to send notifications on every check
- `operator` (string; one of `"Below"`, `"BelowOrEqual"`, `"Above"`, `"AboveOrEqual"`, `"AboveOrBelow"`): Comparison operator for threshold checks:
- Below: Trigger when value < threshold
- BelowOrEqual: Trigger when value <= threshold
- Above: Trigger when value > threshold
- AboveOrEqual: Trigger when value >= threshold
- AboveOrBelow: Trigger when value is outside a range
- `rangeMinutes` (integer (int64); value ≥ 1): Time window to evaluate in each check, in minutes.
For example, "last 5 minutes of data"
- `resolvable` (boolean): Whether the alert can be manually resolved
- `secondDelay` (number (int64); value ≤ 86400): Number of seconds to move each run's query window into the past, so data that arrives late is included.
For example, with a value of 300, a run at 10:05 queries up to 10:00.
- `skipResolved` (boolean): Whether to skip resolved alerts
- `threshold` (number (double)): Threshold value for triggering the alert
- `tolerance` (number; value ≤ 100): Tolerance percentage for anomaly detection
- `trackedValue` (string): NewValues monitors only, and required for them. The column of the query result whose values are checked for new ones.
- `triggerAfterNPositiveResults` (number (int64)): Number of runs among the last `triggerFromNRuns` runs, including the current one, that must meet the trigger condition for the monitor to trigger.
The current run must always meet it.
For example, set both fields to 3 to trigger only after 3 consecutive runs meet the condition.
If unset or 0, the first run that meets the condition triggers.
Values above `triggerFromNRuns` are lowered to it when the monitor is saved.
Applies to Threshold and AnomalyDetection monitors.
- `triggerFromNRuns` (number (int64)): Number of most recent runs, including the current one, that the monitor looks at when deciding whether to trigger.
Has no effect unless `triggerAfterNPositiveResults` is also set.
Applies to Threshold and AnomalyDetection monitors.
- `type` (string; one of `"Threshold"`, `"MatchEvent"`, `"AnomalyDetection"`, `"NewValues"`; required): Type of monitoring check to perform:
- Threshold: Compares a numeric value against a threshold
- MatchEvent: Looks for specific events or patterns
- AnomalyDetection: Identifies unusual patterns based on historical data
- NewValues: Alerts when the trackedValue column of the query result holds a value not seen within lookbackDays. Each run queries the last rangeMinutes, which defaults to intervalMinutes and cannot be less. Sends one notification per new value.
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
---
# Retrieve notifier
Source: https://axiom.co/docs/restapi/endpoints/getNotifier
```http
GET https://api.axiom.co/v2/notifiers/{id}
```
Retrieves a notifier by ID. Labels are resolved unless `exclude=labels`.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Notifier ID.
- `exclude` (query; string; one of `"labels"`): Exclude resolved label objects from the notifier response. The labelIds and labelNames fields are still returned.
## Responses
### 200: Notifier.
Content type: `application/json`
Type: `NotifierWithId`
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### NotifierWithId
Notifier configuration with its unique identifier
All of the following:
- `Notifier`
- Object with:
- `id` (string): Unique identifier for the notifier
- `labelIds` (array of string; required): IDs of labels assigned to this notifier.
- `labelNames` (array of string; required): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`): Resolved labels assigned to this notifier.
### Notifier
Configuration for a notification channel. Notifiers can be configured for various services like:
- Slack
- Email
- PagerDuty
- OpsGenie
- Discord
- Microsoft Teams
- Custom Webhooks
- Cursor
- Claude Code
- Jira Service Management
Object.
- `createdAt` (string (date-time); read-only): Timestamp when the notifier was created
- `createdBy` (string; read-only): Email or ID of the user who created the notifier
- `createdByAgent` (boolean): true when the MCP server created this notifier
- `disabled` (boolean): Whether repeated delivery failures disabled the notifier. False when a user snoozed it with disabledUntil. Ignored on requests
- `disabledUntil` (string): ISO timestamp until which the notifier is disabled (null if enabled)
- `lastError` (string): The delivery error that disabled the notifier. Empty for email notifiers and when disabled is false. Ignored on requests
- `name` (string; required): Human-readable name for the notifier
- `properties` (`NotifierProperties`; required)
- `updatedAt` (string (date-time); read-only): Timestamp when the notifier was last updated
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### NotifierProperties
Configuration options for different notification channels. Only one channel should be configured per notifier.
Object.
- `amp` (`AmpConfig`)
- `chatgptWorkspaceAgent` (`ChatGPTWorkspaceAgentConfig`)
- `claudeCode` (`ClaudeCodeConfig`)
- `cursor` (`CursorConfig`)
- `customWebhook` (`CustomNotifierConfig`)
- `discord` (`DiscordConfig`)
- `discordWebhook` (`DiscordWebhookConfig`)
- `email` (`EmailConfig`)
- `jiraServiceManagement` (`JiraServiceManagementConfig`)
- `microsoftTeams` (`MicrosoftTeamsConfig`)
- `opsgenie` (`OpsGenieConfig`)
- `pagerduty` (`PagerDutyConfig`)
- `slack` (`SlackConfig`)
- `webhook` (`WebhookConfig`)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
### AmpConfig
Amp Orb webhook. The receiving plugin must accept {"text": ""}.
Object.
- `webhookUrl` (string; required): Secret HTTPS URL from the Amp plugin createWebhook registration. Returned encrypted on reads; submit it unchanged to retain it on updates.
### ChatGPTWorkspaceAgentConfig
Published ChatGPT Workspace Agent API channel. Axiom sends {"input": ""}.
Object.
- `token` (string; required): ChatGPT access token with the Workspace Agents scope
- `triggerId` (string; required): API channel trigger ID beginning with agtch_
### ClaudeCodeConfig
Claude Code routine. Axiom sends a fixed text body when the monitor fires.
Object.
- `routineId` (string; required): Routine ID from a Claude Code API trigger
- `token` (string; required): Bearer token for the routine
### CursorConfig
Cursor automation webhook. Axiom sends a fixed context body when the monitor fires.
Object.
- `token` (string; required): Bearer token for the automation webhook
- `webhookUrl` (string; required): Automation webhook URL from a Cursor automation
### CustomNotifierConfig
Configuration for custom webhook notifications with flexible headers and body template.
Supports variable substitution in the body template using {{.Variable}} syntax.
Object.
- `body` (string; required): Template for the webhook body, supports variable substitution
- `headers` (map of string to string): HTTP headers to include in the request
- `secretHeaders` (map of string to string): Sensitive HTTP headers (tokens, keys) that should be masked in logs
- `url` (string; required): Custom webhook endpoint URL
### DiscordConfig
Configuration for Discord notifications using bot token
Object.
- `discordChannel` (string): Discord channel ID to send notifications
- `discordToken` (string): Discord bot token for authentication
- `messageTemplate` (`MessageTemplate`)
### DiscordWebhookConfig
Configuration for Discord notifications using webhooks
Object.
- `discordWebhookUrl` (string): Discord webhook URL
- `messageTemplate` (`MessageTemplate`)
### EmailConfig
Configuration for email notifications
Object.
- `emails` (array of string): List of email addresses to receive notifications
- `messageTemplate` (`MessageTemplate`)
### JiraServiceManagementConfig
Configuration for Jira Service Management Ops alerts using an API integration
Object.
- `apiKey` (string; required): API key of the Jira Service Management API integration
### MicrosoftTeamsConfig
Configuration for Microsoft Teams notifications
Object.
- `messageTemplate` (`MessageTemplate`)
- `microsoftTeamsUrl` (string): Microsoft Teams webhook URL
### OpsGenieConfig
Configuration for OpsGenie integration
Object.
- `apiKey` (string): OpsGenie API key for authentication
- `isEU` (boolean): Whether to use EU region endpoints
### PagerDutyConfig
Configuration for PagerDuty integration
Object.
- `routingKey` (string): PagerDuty integration key for routing alerts
- `token` (string): PagerDuty API token for additional functionality
### SlackConfig
Configuration for Slack notifications using incoming webhooks
Object.
- `messageTemplate` (`MessageTemplate`)
- `slackUrl` (string): Slack incoming webhook URL
### WebhookConfig
Configuration for simple webhook notifications
Object.
- `url` (string): Webhook endpoint URL
### MessageTemplate
Go templates that replace the title and body of the notifier's default message. An empty field keeps the default.
Variables include {{.Title}}, {{.Body}}, {{.Name}}, {{.Action}}, {{.Value}}, {{.Threshold}}, {{.Labels}}, {{.Groups}} and {{.MatchedEvent}}.
If a template fails when a notification is sent, the default message is sent and the delivery records the error.
Object.
- `body` (string): Template for the message body
- `title` (string): Template for the message title
---
# List all notifiers
Source: https://axiom.co/docs/restapi/endpoints/getNotifiers
```http
GET https://api.axiom.co/v2/notifiers
```
Lists all notifiers in the organization, sorted by name. Labels are resolved unless `exclude=labels`.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `exclude` (query; string; one of `"labels"`): Exclude resolved label objects from each notifier response. The labelIds and labelNames fields are still returned.
- `label` (query; array of string; items 1–500): Filter by label names in your organization. Repeat the parameter for multiple names, for example ?label=prod&label=team-a. Names match case-insensitively after whitespace normalization; duplicates count once. Commas are part of a name, not separators. Reading resources never creates missing labels.
- `labelMatch` (query; string; one of `"any"`, `"all"`; default `"any"`): How to combine label names: any (the default) requires at least one requested label on a resource; all requires every requested label on that same resource. For example, ?label=prod&label=team-a matches either label, while ?label=prod&label=team-a&labelMatch=all requires both. Unknown names have no matches with any and make all return no resources. Without label parameters, labelMatch has no effect.
## Responses
### 200: Notifiers in the organization.
Content type: `application/json`
Type: array of `NotifierWithId`
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### NotifierWithId
Notifier configuration with its unique identifier
All of the following:
- `Notifier`
- Object with:
- `id` (string): Unique identifier for the notifier
- `labelIds` (array of string; required): IDs of labels assigned to this notifier.
- `labelNames` (array of string; required): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`): Resolved labels assigned to this notifier.
### Notifier
Configuration for a notification channel. Notifiers can be configured for various services like:
- Slack
- Email
- PagerDuty
- OpsGenie
- Discord
- Microsoft Teams
- Custom Webhooks
- Cursor
- Claude Code
- Jira Service Management
Object.
- `createdAt` (string (date-time); read-only): Timestamp when the notifier was created
- `createdBy` (string; read-only): Email or ID of the user who created the notifier
- `createdByAgent` (boolean): true when the MCP server created this notifier
- `disabled` (boolean): Whether repeated delivery failures disabled the notifier. False when a user snoozed it with disabledUntil. Ignored on requests
- `disabledUntil` (string): ISO timestamp until which the notifier is disabled (null if enabled)
- `lastError` (string): The delivery error that disabled the notifier. Empty for email notifiers and when disabled is false. Ignored on requests
- `name` (string; required): Human-readable name for the notifier
- `properties` (`NotifierProperties`; required)
- `updatedAt` (string (date-time); read-only): Timestamp when the notifier was last updated
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### NotifierProperties
Configuration options for different notification channels. Only one channel should be configured per notifier.
Object.
- `amp` (`AmpConfig`)
- `chatgptWorkspaceAgent` (`ChatGPTWorkspaceAgentConfig`)
- `claudeCode` (`ClaudeCodeConfig`)
- `cursor` (`CursorConfig`)
- `customWebhook` (`CustomNotifierConfig`)
- `discord` (`DiscordConfig`)
- `discordWebhook` (`DiscordWebhookConfig`)
- `email` (`EmailConfig`)
- `jiraServiceManagement` (`JiraServiceManagementConfig`)
- `microsoftTeams` (`MicrosoftTeamsConfig`)
- `opsgenie` (`OpsGenieConfig`)
- `pagerduty` (`PagerDutyConfig`)
- `slack` (`SlackConfig`)
- `webhook` (`WebhookConfig`)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
### AmpConfig
Amp Orb webhook. The receiving plugin must accept {"text": ""}.
Object.
- `webhookUrl` (string; required): Secret HTTPS URL from the Amp plugin createWebhook registration. Returned encrypted on reads; submit it unchanged to retain it on updates.
### ChatGPTWorkspaceAgentConfig
Published ChatGPT Workspace Agent API channel. Axiom sends {"input": ""}.
Object.
- `token` (string; required): ChatGPT access token with the Workspace Agents scope
- `triggerId` (string; required): API channel trigger ID beginning with agtch_
### ClaudeCodeConfig
Claude Code routine. Axiom sends a fixed text body when the monitor fires.
Object.
- `routineId` (string; required): Routine ID from a Claude Code API trigger
- `token` (string; required): Bearer token for the routine
### CursorConfig
Cursor automation webhook. Axiom sends a fixed context body when the monitor fires.
Object.
- `token` (string; required): Bearer token for the automation webhook
- `webhookUrl` (string; required): Automation webhook URL from a Cursor automation
### CustomNotifierConfig
Configuration for custom webhook notifications with flexible headers and body template.
Supports variable substitution in the body template using {{.Variable}} syntax.
Object.
- `body` (string; required): Template for the webhook body, supports variable substitution
- `headers` (map of string to string): HTTP headers to include in the request
- `secretHeaders` (map of string to string): Sensitive HTTP headers (tokens, keys) that should be masked in logs
- `url` (string; required): Custom webhook endpoint URL
### DiscordConfig
Configuration for Discord notifications using bot token
Object.
- `discordChannel` (string): Discord channel ID to send notifications
- `discordToken` (string): Discord bot token for authentication
- `messageTemplate` (`MessageTemplate`)
### DiscordWebhookConfig
Configuration for Discord notifications using webhooks
Object.
- `discordWebhookUrl` (string): Discord webhook URL
- `messageTemplate` (`MessageTemplate`)
### EmailConfig
Configuration for email notifications
Object.
- `emails` (array of string): List of email addresses to receive notifications
- `messageTemplate` (`MessageTemplate`)
### JiraServiceManagementConfig
Configuration for Jira Service Management Ops alerts using an API integration
Object.
- `apiKey` (string; required): API key of the Jira Service Management API integration
### MicrosoftTeamsConfig
Configuration for Microsoft Teams notifications
Object.
- `messageTemplate` (`MessageTemplate`)
- `microsoftTeamsUrl` (string): Microsoft Teams webhook URL
### OpsGenieConfig
Configuration for OpsGenie integration
Object.
- `apiKey` (string): OpsGenie API key for authentication
- `isEU` (boolean): Whether to use EU region endpoints
### PagerDutyConfig
Configuration for PagerDuty integration
Object.
- `routingKey` (string): PagerDuty integration key for routing alerts
- `token` (string): PagerDuty API token for additional functionality
### SlackConfig
Configuration for Slack notifications using incoming webhooks
Object.
- `messageTemplate` (`MessageTemplate`)
- `slackUrl` (string): Slack incoming webhook URL
### WebhookConfig
Configuration for simple webhook notifications
Object.
- `url` (string): Webhook endpoint URL
### MessageTemplate
Go templates that replace the title and body of the notifier's default message. An empty field keeps the default.
Variables include {{.Title}}, {{.Body}}, {{.Name}}, {{.Action}}, {{.Value}}, {{.Threshold}}, {{.Labels}}, {{.Groups}} and {{.MatchedEvent}}.
If a template fails when a notification is sent, the default message is sent and the delivery records the error.
Object.
- `body` (string): Template for the message body
- `title` (string): Template for the message title
---
# Retrieve org
Source: https://axiom.co/docs/restapi/endpoints/getOrg
```http
GET https://api.axiom.co/v2/orgs/{id}
```
Retrieves an organization the authenticated user is a member of, including its plan and license limits. Requires a personal access token (PAT).
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required)
## Responses
### 200: Organization.
Content type: `application/json`
- `defaultEdgeDeployment` (string)
- `firstFailedPayment` (string)
- `id` (string; required)
- `lastUsageSync` (string; required)
- `license` (`License`; required)
- `metaCreated` (string)
- `metaModified` (string)
- `metaVersion` (string)
- `name` (string; required)
- `paymentStatus` (string; one of `"na"`, `"failed"`, `"success"`, `"blocked"`; required)
- `plan` (string; one of `"personal"`, `"teamMonthlyAws"`, `"axiomCloud"`, `"teamPlus"`, `"enterprise"`, `"comped"`, `"accelerator"`; required)
- `planCreated` (string; required)
- `primaryEmail` (string; required)
- `role` (string)
### 404: Organization not found, or the user isn't a member of it.
## Schemas
### License
Object.
- `apiRateLimitPerSecond` (integer (uint64); required)
- `billingPeriodEnd` (string (date-time); required)
- `billingPeriodStart` (string (date-time); required)
- `defaultEdgeDeployment` (string; required)
- `edgeDeployments` (array of string; required)
- `expiresAt` (string (date-time); nullable)
- `features` (map of string to boolean; required)
- `id` (string; required)
- `issuedAt` (string (date-time); required)
- `issuedTo` (string; required)
- `issuer` (string; required)
- `maxAuditWindowSeconds` (integer (uint64); required)
- `maxDatasets` (integer (uint64); required)
- `maxEndpoints` (integer (uint64); required)
- `maxFields` (integer (uint64); required)
- `maxMonitors` (integer (uint64); required)
- `maxQueryWindowSeconds` (integer (uint64); required)
- `maxUsers` (integer (uint64); required)
- `monthlyIngestGb` (integer (uint64); required)
- `monthlyQueryGbHours` (integer (uint64); required)
- `storageAllowanceGB` (integer (uint64))
- `tier` (string; one of `"personal"`, `"teamMonthlyAws"`, `"axiomCloud"`, `"teamPlus"`, `"enterprise"`, `"comped"`, `"accelerator"`; required)
- `validFrom` (string (date-time); required)
- `withAuths` (array of string; required)
---
# List all orgs
Source: https://axiom.co/docs/restapi/endpoints/getOrgs
```http
GET https://api.axiom.co/v2/orgs
```
Lists the organizations the authenticated user is a member of. Requires a personal access token (PAT). Organizations that enforce SAML sign-in are omitted unless the PAT is SAML-authenticated.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Responses
### 200: Organizations the user is a member of.
Content type: `application/json`
Type: array of `Org`
## Schemas
### Org
Object.
- `defaultEdgeDeployment` (string)
- `firstFailedPayment` (string)
- `id` (string; required)
- `lastUsageSync` (string; required)
- `license` (`License`; required)
- `metaCreated` (string)
- `metaModified` (string)
- `metaVersion` (string)
- `name` (string; required)
- `paymentStatus` (string; one of `"na"`, `"failed"`, `"success"`, `"blocked"`; required)
- `plan` (string; one of `"personal"`, `"teamMonthlyAws"`, `"axiomCloud"`, `"teamPlus"`, `"enterprise"`, `"comped"`, `"accelerator"`; required)
- `planCreated` (string; required)
- `primaryEmail` (string; required)
- `role` (string)
### License
Object.
- `apiRateLimitPerSecond` (integer (uint64); required)
- `billingPeriodEnd` (string (date-time); required)
- `billingPeriodStart` (string (date-time); required)
- `defaultEdgeDeployment` (string; required)
- `edgeDeployments` (array of string; required)
- `expiresAt` (string (date-time); nullable)
- `features` (map of string to boolean; required)
- `id` (string; required)
- `issuedAt` (string (date-time); required)
- `issuedTo` (string; required)
- `issuer` (string; required)
- `maxAuditWindowSeconds` (integer (uint64); required)
- `maxDatasets` (integer (uint64); required)
- `maxEndpoints` (integer (uint64); required)
- `maxFields` (integer (uint64); required)
- `maxMonitors` (integer (uint64); required)
- `maxQueryWindowSeconds` (integer (uint64); required)
- `maxUsers` (integer (uint64); required)
- `monthlyIngestGb` (integer (uint64); required)
- `monthlyQueryGbHours` (integer (uint64); required)
- `storageAllowanceGB` (integer (uint64))
- `tier` (string; one of `"personal"`, `"teamMonthlyAws"`, `"axiomCloud"`, `"teamPlus"`, `"enterprise"`, `"comped"`, `"accelerator"`; required)
- `validFrom` (string (date-time); required)
- `withAuths` (array of string; required)
---
# Retrieve role
Source: https://axiom.co/docs/restapi/endpoints/getRoleById
```http
GET https://api.axiom.co/v2/rbac/roles/{id}
```
Retrieves a custom role by ID with its capabilities and the IDs of users assigned the role directly. Built-in role IDs such as `axiom-admin` return `404`.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Unique identifier of the role to retrieve
## Responses
### 200: The role.
Content type: `application/json`
Type: `RoleWithID`
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### RoleWithID
Extends the base Role type to include a unique identifier
All of the following:
- `Role`
- Object with:
- `id` (string; required): Unique identifier for the role
### Role
Defines a role and its associated permissions within the system
Object.
- `datasetCapabilities` (`roleDatasetCapabilities`)
- `description` (string): Detailed description of the role's purpose and scope
- `members` (array of string): IDs of users assigned this role directly. Returned in responses and ignored in requests. To assign a role to a user, use the Update user role endpoint.
- `name` (string; required): Unique name identifier for the role
- `orgCapabilities` (`roleOrgCapabilities`)
- `viewCapabilities` (`roleViewCapabilities`)
### roleDatasetCapabilities
Defines the available permissions for dataset operations
Type: map of string to object
### roleOrgCapabilities
Defines organization-wide permissions and capabilities
Object.
- `annotations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of annotations across the organization
- `apiTokens` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of API tokens for authentication
- `auditLog` (array of string; one of `"read"`): Controls access to organization audit logs
- `billing` (array of string; one of `"read"`, `"update"`): Controls access to billing information and settings
- `dashboards` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of organization dashboards
- `datasets` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of organization datasets
- `endpoints` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of API endpoints
- `integrations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of third-party integrations
- `labels` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of labels
- `monitors` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of monitoring
- `notifiers` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of notification settings
- `rbac` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls access to role-based access control settings
- `sharedAccessKeys` (array of string; one of `"read"`, `"update"`): Controls the management of shared access keys
- `users` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls user management within the organization
- `views` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of data views
### roleViewCapabilities
Defines the available permissions for view operations
Type: map of string to object
---
# Retrieve saved query
Source: https://axiom.co/docs/restapi/endpoints/getStarred
```http
GET https://api.axiom.co/v2/apl-starred-queries/{id}
```
Retrieves a saved query by its ID.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required)
## Responses
### 200: Saved query.
Content type: `application/json`
Type: `StarredQueryWithId`
### 404: Saved query not found, or you can't read its dataset.
## Schemas
### StarredQueryWithId
All of the following:
- `StarredQuery`
- Object with:
- `id` (string; required)
### StarredQuery
Object.
- `dataset` (string)
- `kind` (string; one of `"apl"`; required)
- `metadata` (map of string to string; required)
- `name` (string; required)
- `query` (`APLRequestWithOptions`; required)
- `who` (string; required)
### APLRequestWithOptions
Object.
- `apl` (string; required)
- `cursor` (string)
- `defaultLimit` (integer (int64))
- `defaultOrder` (array of `APLRequestWithOptionsDefaultOrder`)
- `endTime` (string)
- `includeCursor` (boolean)
- `includeCursorField` (boolean)
- `libraries` (array of string)
- `queryOptions` (`QueryOptions`)
- `startTime` (string)
- `variables` (object)
### APLRequestWithOptionsDefaultOrder
Object.
- `desc` (boolean)
- `field` (string)
### QueryOptions
Object. Other fields aren't allowed.
- `disableCache` (boolean)
- `disableStats` (boolean)
- `disableTrace` (boolean)
- `maxDataPoints` (integer (int64))
- `maxSeries` (integer (int64))
- `noAggregation` (boolean)
- `noFill` (boolean)
- `noInterpolation` (boolean)
- `priority` (string; one of `"low"`, `"medium"`, `"high"`)
- `resolution` (string)
- `displayNull` (string; one of `"auto"`, `"null"`, `"span"`, `"zero"`, `""`): Controls how empty intervals are rendered in time series charts. `auto` infers from the query, `null` leaves gaps, `span` connects adjacent points, `zero` fills with zero.
- `overlayCharts` (string; one of `"true"`, `"false"`, `""`): When enabled, charts are overlaid on a single chart instead of stacked separately.
- `shownColumns` (string; length ≤ 10000)
- `timeSeriesVariant` (string; one of `"area"`, `"bars"`, `"line"`, `"lines"`, `""`)
- `timeSeriesView` (string; one of `"charts"`, `"resultsTable"`, `"charts|resultsTable"`, `""`)
---
# List all saved queries
Source: https://axiom.co/docs/restapi/endpoints/getStarredQueries
```http
GET https://api.axiom.co/v2/apl-starred-queries
```
Lists saved APL queries on datasets you can read, sorted by name. Use `who` to choose whose queries to return, and `limit` and `offset` to paginate.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `limit` (query; integer (int64); value 1–1000; default `100`)
- `offset` (query; integer (int64); value ≥ 0; default `0`)
- `dataset` (query; string): Return only queries saved on this dataset.
- `who` (query; string): - If the value of `who` is your own user ID, the request returns queries saved by the authenticated user.
- If the value of `who` is `team`, the request returns queries saved by other users in the organization. For example, `&who=team`.
- If the value of `who` is `all`, the request returns queries saved by all users in the organization, including the authenticated user. For example, `&who=all`.
- Any other value returns `400`. This includes another user's ID, and omitting `who` when you authenticate with a personal access token.
- `qs` (query; string): Return only queries whose name contains this string. Case-insensitive.
## Responses
### 200: Saved queries.
Content type: `application/json`
Type: array of `StarredQueryWithId`
### 400: Invalid `who`.
### 404: You can't read the dataset in `dataset`.
## Schemas
### StarredQueryWithId
All of the following:
- `StarredQuery`
- Object with:
- `id` (string; required)
### StarredQuery
Object.
- `dataset` (string)
- `kind` (string; one of `"apl"`; required)
- `metadata` (map of string to string; required)
- `name` (string; required)
- `query` (`APLRequestWithOptions`; required)
- `who` (string; required)
### APLRequestWithOptions
Object.
- `apl` (string; required)
- `cursor` (string)
- `defaultLimit` (integer (int64))
- `defaultOrder` (array of `APLRequestWithOptionsDefaultOrder`)
- `endTime` (string)
- `includeCursor` (boolean)
- `includeCursorField` (boolean)
- `libraries` (array of string)
- `queryOptions` (`QueryOptions`)
- `startTime` (string)
- `variables` (object)
### APLRequestWithOptionsDefaultOrder
Object.
- `desc` (boolean)
- `field` (string)
### QueryOptions
Object. Other fields aren't allowed.
- `disableCache` (boolean)
- `disableStats` (boolean)
- `disableTrace` (boolean)
- `maxDataPoints` (integer (int64))
- `maxSeries` (integer (int64))
- `noAggregation` (boolean)
- `noFill` (boolean)
- `noInterpolation` (boolean)
- `priority` (string; one of `"low"`, `"medium"`, `"high"`)
- `resolution` (string)
- `displayNull` (string; one of `"auto"`, `"null"`, `"span"`, `"zero"`, `""`): Controls how empty intervals are rendered in time series charts. `auto` infers from the query, `null` leaves gaps, `span` connects adjacent points, `zero` fills with zero.
- `overlayCharts` (string; one of `"true"`, `"false"`, `""`): When enabled, charts are overlaid on a single chart instead of stacked separately.
- `shownColumns` (string; length ≤ 10000)
- `timeSeriesVariant` (string; one of `"area"`, `"bars"`, `"line"`, `"lines"`, `""`)
- `timeSeriesView` (string; one of `"charts"`, `"resultsTable"`, `"charts|resultsTable"`, `""`)
---
# Retrieve API token
Source: https://axiom.co/docs/restapi/endpoints/getToken
```http
GET https://api.axiom.co/v2/tokens/{id}
```
Retrieves an active API token by ID. The response doesn't include the token's secret value.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required)
## Responses
### 200: API token.
Content type: `application/json`
- `apiLastUsed` (string (date-time); nullable; read-only): When the token was last used on an API other than ingest
- `auditIdentity` (string; read-only): Audit identity of the token
- `datasetCapabilities` (`datasetCapabilities`; required)
- `description` (string): Description of the token
- `expiresAt` (string (date-time); nullable; read-only): Expiration date of the token (ISO 8601 format)
- `id` (string; required): ID of the token
- `ingestLastUsed` (string (date-time); nullable; read-only): When the token was last used to ingest
- `name` (string; required): Name of the token
- `orgCapabilities` (`orgCapabilities`; required)
- `samlAuthenticated` (boolean)
- `viewCapabilities` (`viewCapabilities`)
### 404: API token not found or expired.
## Schemas
### datasetCapabilities
Type: map of string to object
### orgCapabilities
Object.
- `annotations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Annotations capability
- `apiTokens` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): API tokens capability
- `auditLog` (array of string; one of `"read"`): Audit Log capability
- `billing` (array of string; one of `"read"`, `"update"`): Billing capability
- `dashboards` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Dashboards capability
- `datasets` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Datasets capability
- `endpoints` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Endpoints capability
- `integrations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Integrations capability
- `labels` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Labels capability
- `monitors` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Monitors capability
- `notifiers` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Notifiers capability
- `rbac` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Access control capability
- `sharedAccessKeys` (array of string; one of `"read"`, `"update"`): Shared access keys capability
- `users` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Users capability
- `views` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Views capability
### viewCapabilities
Type: map of string to object
---
# List all API tokens
Source: https://axiom.co/docs/restapi/endpoints/getTokens
```http
GET https://api.axiom.co/v2/tokens
```
Lists the organization's active API tokens. Expired tokens, personal access tokens, and token secret values aren't included.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Responses
### 200: Active API tokens.
Content type: `application/json`
Type: array of `APIToken`
## Schemas
### APIToken
Object.
- `apiLastUsed` (string (date-time); nullable; read-only): When the token was last used on an API other than ingest
- `auditIdentity` (string; read-only): Audit identity of the token
- `datasetCapabilities` (`datasetCapabilities`; required)
- `description` (string): Description of the token
- `expiresAt` (string (date-time); nullable; read-only): Expiration date of the token (ISO 8601 format)
- `id` (string; required): ID of the token
- `ingestLastUsed` (string (date-time); nullable; read-only): When the token was last used to ingest
- `name` (string; required): Name of the token
- `orgCapabilities` (`orgCapabilities`; required)
- `samlAuthenticated` (boolean)
- `viewCapabilities` (`viewCapabilities`)
### datasetCapabilities
Type: map of string to object
### orgCapabilities
Object.
- `annotations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Annotations capability
- `apiTokens` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): API tokens capability
- `auditLog` (array of string; one of `"read"`): Audit Log capability
- `billing` (array of string; one of `"read"`, `"update"`): Billing capability
- `dashboards` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Dashboards capability
- `datasets` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Datasets capability
- `endpoints` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Endpoints capability
- `integrations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Integrations capability
- `labels` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Labels capability
- `monitors` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Monitors capability
- `notifiers` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Notifiers capability
- `rbac` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Access control capability
- `sharedAccessKeys` (array of string; one of `"read"`, `"update"`): Shared access keys capability
- `users` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Users capability
- `views` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Views capability
### viewCapabilities
Type: map of string to object
---
# Retrieve user
Source: https://axiom.co/docs/restapi/endpoints/getUser
```http
GET https://api.axiom.co/v2/users/{id}
```
Retrieves a member of the organization by user ID, including their role.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required)
## Responses
### 200: User.
Content type: `application/json`
Represents a user in the system
- `email` (string; required): User's email address
- `id` (string; required): Unique identifier for the user
- `name` (string; required): User's full name
- `role` (`UserDetailsRole`; required)
### 404: User not found.
## Schemas
### UserDetailsRole
Detailed information about a user's role
Object.
- `id` (string; required): Unique identifier for the role
- `name` (string; required): Human-readable name of the role
---
# List all users
Source: https://axiom.co/docs/restapi/endpoints/getUsers
```http
GET https://api.axiom.co/v2/users
```
Lists all members of the organization, including each member's role.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Responses
### 200: Organization members.
Content type: `application/json`
Type: array of `User`
## Schemas
### User
Represents a user in the system
Object.
- `email` (string; required): User's email address
- `id` (string; required): Unique identifier for the user
- `name` (string; required): User's full name
- `role` (`UserDetailsRole`; required)
### UserDetailsRole
Detailed information about a user's role
Object.
- `id` (string; required): Unique identifier for the role
- `name` (string; required): Human-readable name of the role
---
# Retrieve view
Source: https://axiom.co/docs/restapi/endpoints/getView
```http
GET https://api.axiom.co/v2/views/{id}
```
Retrieves a view by its name.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Name of the view
## Responses
### 200: View.
Content type: `application/json`
- `aplQuery` (string; required): APL query that defines the view
- `datasets` (array of string): Datasets the view queries. Axiom derives this from `aplQuery` and ignores it in requests.
- `description` (string)
- `edgeDeployment` (string): Region of the source datasets; ignored in requests
- `edgeDeploymentUrl` (string): URL of the edge deployment; ignored in requests
- `name` (string; required): Name of the view. Use it as the view ID and to query the view like a dataset.
- `sharedByOrg` (string): ID of the org that shared this resource, if it's shared
- `sharedByOrgName` (string): The name of the org that shared this resource, if it's shared
### 403: You don't have query access to the view's dataset.
### 404: View not found.
---
# List all views
Source: https://axiom.co/docs/restapi/endpoints/getViews
```http
GET https://api.axiom.co/v2/views
```
Lists the views in the organization, including views shared with it by other organizations.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Responses
### 200: Views.
Content type: `application/json`
Type: array of `View`
## Schemas
### View
Object.
- `aplQuery` (string; required): APL query that defines the view
- `datasets` (array of string): Datasets the view queries. Axiom derives this from `aplQuery` and ignores it in requests.
- `description` (string)
- `edgeDeployment` (string): Region of the source datasets; ignored in requests
- `edgeDeploymentUrl` (string): URL of the edge deployment; ignored in requests
- `name` (string; required): Name of the view. Use it as the view ID and to query the view like a dataset.
- `sharedByOrg` (string): ID of the org that shared this resource, if it's shared
- `sharedByOrgName` (string): The name of the org that shared this resource, if it's shared
---
# Retrieve virtual field
Source: https://axiom.co/docs/restapi/endpoints/getVirtualField
```http
GET https://api.axiom.co/v2/vfields/{id}
```
Retrieves a virtual field by its ID.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): ID of the virtual field in the form `.`
## Responses
### 200: Virtual field.
Content type: `application/json`
Type: `VirtualFieldWithId`
### 404: Virtual field not found, or you can't read its dataset.
## Schemas
### VirtualFieldWithId
All of the following:
- `VirtualField`
- Object with:
- `id` (string; required)
### VirtualField
Object.
- `dataset` (string; required)
- `description` (string)
- `expression` (string; required)
- `name` (string; required): Name of the virtual field. Use letters, digits, underscores, and hyphens, starting and ending with a letter or digit.
- `type` (string)
- `unit` (string)
---
# List all virtual fields
Source: https://axiom.co/docs/restapi/endpoints/getVirtualFields
```http
GET https://api.axiom.co/v2/vfields
```
Lists the virtual fields of a dataset, ordered by creation time.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset` (query; string; required): Name of the dataset
## Responses
### 200: Virtual fields.
Content type: `application/json`
Type: array of `VirtualFieldWithId`
### 404: You can't read the dataset.
## Schemas
### VirtualFieldWithId
All of the following:
- `VirtualField`
- Object with:
- `id` (string; required)
### VirtualField
Object.
- `dataset` (string; required)
- `description` (string)
- `expression` (string; required)
- `name` (string; required): Name of the virtual field. Use letters, digits, underscores, and hyphens, starting and ending with a letter or digit.
- `type` (string)
- `unit` (string)
---
# Ingest Splunk HEC events
Source: https://axiom.co/docs/restapi/endpoints/ingestHecEvent
```http
POST https://hec.{axiom-domain}/services/collector/event
```
Ingests one or more Splunk HEC event envelopes, concatenated or newline-delimited, into an events or logs dataset. The dataset comes from the `index` query parameter, then the first event's `index` field, then the token's only ingest dataset.
Use this endpoint to ingest events through the Splunk HTTP Event Collector (HEC) compatible API. For a walkthrough, see [Send data using the Splunk HEC API](/send-data/splunk-hec).
The base domain for this endpoint is `hec.` prefixed to the base domain of your edge deployment. For example, if your edge deployment’s base domain is `us-east-1.aws.edge.axiom.co`, the HEC endpoint is `https://hec.us-east-1.aws.edge.axiom.co`.
This endpoint only supports API tokens. Personal access tokens (PATs) aren't supported. For more information, see [Tokens](/reference/tokens).
## Authentication
Authenticate using an API token with ingest permission. HEC clients typically send the token in the Splunk scheme: `Authorization: Splunk `. The Bearer scheme (`Authorization: Bearer `) and HTTP Basic (`x:`) are also accepted. For more information, see [Tokens](/reference/tokens).
## Parameters
- `index` (query; string): The dataset (Splunk index) to ingest into. Overrides the `index` field in the event envelope.
## Request body
Content type: `application/json` (required)
A Splunk HEC event envelope.
- `event` (any): The event payload. When an object, its keys become top-level fields of the Axiom event. When a string, it is stored in the `_raw` field.
- `fields` (object): Additional fields merged into the event.
- `time` (any): The event timestamp, as epoch seconds, epoch milliseconds, or an RFC 3339 string. When omitted, Axiom assigns the ingest time.
- `index` (string): The dataset (Splunk index) to ingest into. The `index` query parameter takes precedence.
- `host` (string)
- `source` (string)
- `sourcetype` (string)
## Responses
### 200: The events were accepted.
Content type: `application/json`
The Splunk HEC status envelope.
- `text` (string; required): A human-readable status message.
- `code` (integer; required): The Splunk status code. `0` indicates success, `17` indicates a healthy collector, and `5`, `6`, and `7` indicate no data, invalid data format, and incorrect index respectively.
### 400: The request can't be processed. `code` is `5` (no data), `6` (invalid data format, or the dataset is in another edge deployment or isn't an events or logs dataset), or `7` (no dataset could be resolved).
Content type: `application/json`
The Splunk HEC status envelope.
- `text` (string; required): A human-readable status message.
- `code` (integer; required): The Splunk status code. `0` indicates success, `17` indicates a healthy collector, and `5`, `6`, and `7` indicate no data, invalid data format, and incorrect index respectively.
### 401: The token is missing (`code` `2`) or invalid (`code` `3`).
Content type: `application/json`
The Splunk HEC status envelope.
- `text` (string; required): A human-readable status message.
- `code` (integer; required): The Splunk status code. `0` indicates success, `17` indicates a healthy collector, and `5`, `6`, and `7` indicate no data, invalid data format, and incorrect index respectively.
### 403: The token can't ingest into the dataset, the dataset is shared, or the organization is suspended. `code` is `4`.
Content type: `application/json`
The Splunk HEC status envelope.
- `text` (string; required): A human-readable status message.
- `code` (integer; required): The Splunk status code. `0` indicates success, `17` indicates a healthy collector, and `5`, `6`, and `7` indicate no data, invalid data format, and incorrect index respectively.
### 404: Dataset not found. `code` is `7`.
Content type: `application/json`
The Splunk HEC status envelope.
- `text` (string; required): A human-readable status message.
- `code` (integer; required): The Splunk status code. `0` indicates success, `17` indicates a healthy collector, and `5`, `6`, and `7` indicate no data, invalid data format, and incorrect index respectively.
---
# Ingest raw Splunk HEC events
Source: https://axiom.co/docs/restapi/endpoints/ingestHecRaw
```http
POST https://hec.{axiom-domain}/services/collector/raw
```
Ingests a raw payload into an events or logs dataset. Each line of a plain-text body becomes one event. Event metadata comes from the `host`, `source`, and `sourcetype` query parameters instead of an envelope.
Use this endpoint to ingest raw payloads through the Splunk HTTP Event Collector (HEC) compatible API. For a walkthrough, see [Send data using the Splunk HEC API](/send-data/splunk-hec).
The base domain for this endpoint is `hec.` prefixed to the base domain of your edge deployment. For example, if your edge deployment’s base domain is `us-east-1.aws.edge.axiom.co`, the HEC endpoint is `https://hec.us-east-1.aws.edge.axiom.co`.
This endpoint only supports API tokens. Personal access tokens (PATs) aren't supported. For more information, see [Tokens](/reference/tokens).
## Authentication
Authenticate using an API token with ingest permission. HEC clients typically send the token in the Splunk scheme: `Authorization: Splunk `. The Bearer scheme (`Authorization: Bearer `) and HTTP Basic (`x:`) are also accepted. For more information, see [Tokens](/reference/tokens).
## Parameters
- `index` (query; string): The dataset (Splunk index) to ingest into.
- `sourcetype` (query; string): The sourcetype to attach to every event in the request.
- `source` (query; string): The source to attach to every event in the request.
- `host` (query; string): The host to attach to every event in the request.
## Request body
Content type: `text/plain` (required)
Type: string (binary)
Content type: `application/json` (required)
Type: string (binary)
## Responses
### 200: The events were accepted.
Content type: `application/json`
The Splunk HEC status envelope.
- `text` (string; required): A human-readable status message.
- `code` (integer; required): The Splunk status code. `0` indicates success, `17` indicates a healthy collector, and `5`, `6`, and `7` indicate no data, invalid data format, and incorrect index respectively.
### 400: The request can't be processed. `code` is `5` (no data), `6` (invalid data format, or the dataset is in another edge deployment or isn't an events or logs dataset), or `7` (no dataset could be resolved).
Content type: `application/json`
The Splunk HEC status envelope.
- `text` (string; required): A human-readable status message.
- `code` (integer; required): The Splunk status code. `0` indicates success, `17` indicates a healthy collector, and `5`, `6`, and `7` indicate no data, invalid data format, and incorrect index respectively.
### 401: The token is missing (`code` `2`) or invalid (`code` `3`).
Content type: `application/json`
The Splunk HEC status envelope.
- `text` (string; required): A human-readable status message.
- `code` (integer; required): The Splunk status code. `0` indicates success, `17` indicates a healthy collector, and `5`, `6`, and `7` indicate no data, invalid data format, and incorrect index respectively.
### 403: The token can't ingest into the dataset, the dataset is shared, or the organization is suspended. `code` is `4`.
Content type: `application/json`
The Splunk HEC status envelope.
- `text` (string; required): A human-readable status message.
- `code` (integer; required): The Splunk status code. `0` indicates success, `17` indicates a healthy collector, and `5`, `6`, and `7` indicate no data, invalid data format, and incorrect index respectively.
### 404: Dataset not found. `code` is `7`.
Content type: `application/json`
The Splunk HEC status envelope.
- `text` (string; required): A human-readable status message.
- `code` (integer; required): The Splunk status code. `0` indicates success, `17` indicates a healthy collector, and `5`, `6`, and `7` indicate no data, invalid data format, and incorrect index respectively.
---
# Ingest data (legacy)
Source: https://axiom.co/docs/restapi/endpoints/ingestIntoDataset
```http
POST https://api.axiom.co/v1/datasets/{dataset_name}/ingest
```
Ingests JSON, NDJSON, CSV, or Logplex events into an events or logs dataset through `api.axiom.co`. Prefer the edge ingest endpoint.
This is a legacy endpoint that ingests data into the US East 1 (AWS) edge deployment. To ingest data, use the [Ingest data to edge deployment](/restapi/endpoints/ingestToDataset) endpoint instead. For more information, see [Ingest data](/restapi/ingest) and [Edge deployments](/reference/edge-deployments).
The base domain for this endpoint is `https://api.axiom.co`, irrespective of your edge deployment.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_name` (path; string; required): Unique name of the dataset.
- `timestamp-field` (query; string): The name of the field to use as the timestamp. If not specified, the timestamp will be the time the event was received by Axiom.
- `timestamp-format` (query; string): The date-time format of the timestamp field. The reference time is `Mon Jan 2 15:04:05 -0700 MST 2006`, as specified in https://pkg.go.dev/time/?tab=doc#Parse
- `csv-delimiter` (query; string): The delimiter to use when parsing CSV data. If not specified, the default delimiter is `,`.
- `X-Axiom-CSV-Fields` (header; array of string): A list of optional comma separated fields to use for CSV ingestion. If not specified, the first line of the CSV will be used as the field names.
- `X-Axiom-Event-Labels` (header; string): An optional JSON encoded object with additional labels to add to all events in the request
## Request body
Content type: `application/json` (required)
Type: string (binary)
Content type: `text/csv` (required)
Type: string (binary)
Content type: `application/x-ndjson` (required)
Type: string (binary)
## Responses
### 200: ingest status
Content type: `application/json`
- `blocksCreated` (integer (uint32)): Number of blocks created
- `failed` (integer (uint64); required): Number of failures that occurred during ingest
- `failures` (array of `IngestFailure`): List of failures that occurred during ingest
- `ingested` (integer (uint64); required): Number of events ingested
- `processedBytes` (integer (uint64); required): Number of bytes processed
- `walLength` (integer (uint32)): Length of the WAL
### 400: The dataset name is invalid or reserved, the dataset isn't an events or logs dataset, or it belongs to a different edge deployment.
### 401: Unauthorized
Content type: `application/json`
- `code` (string)
- `message` (string)
### 403: The token can't ingest into this dataset, the dataset is shared, or the organization is suspended.
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Dataset not found.
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### IngestFailure
Object.
- `error` (string; required)
- `timestamp` (string (date-time); required)
---
# Ingest data to edge deployment
Source: https://axiom.co/docs/restapi/endpoints/ingestToDataset
```http
POST https://{axiom-domain}/v1/ingest/{dataset-id}
```
Ingests JSON, NDJSON, or CSV events into an events or logs dataset in this edge deployment. Events that fail are counted in `failed` and listed in `failures`. Events whose timestamp is more than 24 hours in the future or before the Unix epoch (1970-01-01T00:00:00Z) are rejected and not stored. Returns `400` when every event in the request is rejected and `430` when the organization has reached its ingest limit.
Use this endpoint to ingest data into a specific edge deployment. For more information, see [Ingest data](/restapi/ingest) and [Edge deployments](/reference/edge-deployments).
The base domain for this endpoint is the base domain of the edge deployment where you want to ingest data.
This endpoint only supports API tokens. Personal access tokens (PATs) aren't supported. For more information, see [Tokens](/reference/tokens).
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset-id` (path; string; required)
- `timestamp-field` (query; string): The name of the field to use as the timestamp. If not specified, the timestamp will be the time the event was received by Axiom.
- `timestamp-format` (query; string): The date-time format of the timestamp field. The reference time is `Mon Jan 2 15:04:05 -0700 MST 2006`, as specified in https://pkg.go.dev/time/?tab=doc#Parse
- `csv-delimiter` (query; string): The delimiter to use when parsing CSV data. If not specified, the default delimiter is `,`.
- `X-Axiom-CSV-Fields` (header; array of string): A list of optional comma separated fields to use for CSV ingestion. If not specified, the first line of the CSV will be used as the field names.
- `X-Axiom-Event-Labels` (header; string): An optional JSON encoded object with additional labels to add to all events in the request
## Request body
Content type: `application/json` (required)
Type: string (binary)
Content type: `application/nd-json` (required)
Type: string (binary)
Content type: `text/csv` (required)
Type: string (binary)
Content type: `application/x-ndjson` (required)
Type: string (binary)
## Responses
### 200: Ingest result, including any per-event failures.
Content type: `application/json`
- `blocksCreated` (integer (uint32); required)
- `failed` (integer (uint64); required)
- `failures` (array of `IngestFailure`)
- `ingested` (integer (uint64); required)
- `processedBytes` (integer (uint64); required)
- `walLength` (integer (uint32); required)
### 400: The dataset name is invalid or reserved, the dataset is in another edge deployment or isn't an events or logs dataset, or every event in the request was rejected.
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
### 403: The token can't ingest into this dataset, the dataset is shared from another organization, or the organization is suspended.
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
### 404: Dataset not found.
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
### 430: The organization has reached its ingest limit.
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
## Schemas
### IngestFailure
Object.
- `error` (string; required)
- `timestamp` (string (date-time); required)
---
# List all groups
Source: https://axiom.co/docs/restapi/endpoints/listGroups
```http
GET https://api.axiom.co/v2/rbac/groups
```
Lists all groups in the organization with the role IDs and user IDs assigned to each group.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Responses
### 200: Groups in the organization.
Content type: `application/json`
Type: array of `GroupWithID`
## Schemas
### GroupWithID
Extends the base Group type to include a unique identifier
All of the following:
- `Group`
- Object with:
- `id` (string; required): Unique identifier for the group
### Group
Defines a group of users for organizational purposes
Object.
- `description` (string): Detailed description of the group's purpose and scope
- `isManaged` (boolean; read-only): Whether the group is synced from your identity provider. You can't delete a managed group or change its members.
- `members` (array of string): List of user IDs that are assigned to this group
- `name` (string; required): Unique name identifier for the group
- `roles` (array of string): IDs of the roles assigned to the group. Use a custom role ID or a built-in role ID: `axiom-owner`, `axiom-admin`, `axiom-user`, `axiom-read-only`, or `axiom-none`.
---
# List label assignments
Source: https://axiom.co/docs/restapi/endpoints/listLabelAssignments
```http
POST https://api.axiom.co/v2/labels/assignments
```
Accepts 1-500 unique resource targets and preserves their request order. Returns exactly one result per target. An eligible target without assignments, a target that does not exist, and a target that the caller cannot access all return an empty labelIds array. The response does not distinguish these cases. labelIds is a set with no meaningful order. The operation is safe and idempotent despite using POST. Eligible targets are owned saved dashboards, visible integration dashboards, readable datasets, visible monitors, and visible notifiers. Each target is checked using its resource's read permission; missing permissions yield empty labelIds for that target. Dashboards shared into the organization are not eligible. A target that uses the wrong identifier for its type returns 400. An unknown target type, duplicate targets, and more than 500 targets fail request validation with 422. An internal failure while resolving targets fails the whole request instead of returning empty label sets.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
Content type: `application/json` (required)
- `targets` (array of `LabelAssignmentTarget`; items 1–500; required)
## Responses
### 200: One result for each requested target, in request order. labelIds is empty when the target has no assignments, does not exist, or is not accessible to the caller. The response does not distinguish those cases. labelIds is a set with no meaningful order.
Content type: `application/json`
Type: array of `LabelAssignmentResult`
### 400: A target uses the wrong identifier for its type.
### 422: Request validation failed. The request contains an unknown target type, duplicate targets, or more than 500 targets.
## Schemas
### LabelAssignmentTarget
A resource that supports organization labels. Single-identifier targets use id; frontend-generated integration dashboards use templateId and dataset.
Object.
- `dataset` (string): Required only for frontend-generated integration dashboards and rejected for other target types. Use the current dataset name. Assignments use the underlying dataset instance, so permanent deletion and recreation do not restore old labels.
- `id` (string): Public identifier for the resource. Use the dashboard UID for a dashboard, the dataset name for a dataset, and the ID returned by the monitor, notifier, or backend-provided integration dashboard APIs.
- `templateId` (string; length ≤ 128): Stable frontend-owned template key for a frontend-generated integration dashboard, such as k8s.stats. Requires dataset and rejects id. Whitespace and control characters are rejected.
- `type` (string; one of `"dashboard"`, `"integration_dashboard"`, `"dataset"`, `"monitor"`, `"notifier"`; required)
### LabelAssignmentResult
Object.
- `labelIds` (array of string; required)
- `target` (`LabelAssignmentTarget`; required)
---
# List all roles
Source: https://axiom.co/docs/restapi/endpoints/listRoles
```http
GET https://api.axiom.co/v2/rbac/roles
```
Lists the custom roles in the organization with their capabilities and the IDs of users assigned each role directly. Built-in roles such as `axiom-admin` aren't included.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Responses
### 200: Custom roles in the organization.
Content type: `application/json`
Type: array of `RoleWithID`
## Schemas
### RoleWithID
Extends the base Role type to include a unique identifier
All of the following:
- `Role`
- Object with:
- `id` (string; required): Unique identifier for the role
### Role
Defines a role and its associated permissions within the system
Object.
- `datasetCapabilities` (`roleDatasetCapabilities`)
- `description` (string): Detailed description of the role's purpose and scope
- `members` (array of string): IDs of users assigned this role directly. Returned in responses and ignored in requests. To assign a role to a user, use the Update user role endpoint.
- `name` (string; required): Unique name identifier for the role
- `orgCapabilities` (`roleOrgCapabilities`)
- `viewCapabilities` (`roleViewCapabilities`)
### roleDatasetCapabilities
Defines the available permissions for dataset operations
Type: map of string to object
### roleOrgCapabilities
Defines organization-wide permissions and capabilities
Object.
- `annotations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of annotations across the organization
- `apiTokens` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of API tokens for authentication
- `auditLog` (array of string; one of `"read"`): Controls access to organization audit logs
- `billing` (array of string; one of `"read"`, `"update"`): Controls access to billing information and settings
- `dashboards` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of organization dashboards
- `datasets` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of organization datasets
- `endpoints` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of API endpoints
- `integrations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of third-party integrations
- `labels` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of labels
- `monitors` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of monitoring
- `notifiers` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of notification settings
- `rbac` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls access to role-based access control settings
- `sharedAccessKeys` (array of string; one of `"read"`, `"update"`): Controls the management of shared access keys
- `users` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls user management within the organization
- `views` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of data views
### roleViewCapabilities
Defines the available permissions for view operations
Type: map of string to object
---
# Patch dashboard element
Source: https://axiom.co/docs/restapi/endpoints/patchDashboard
```http
PATCH https://api.axiom.co/v2/dashboards/uid/{uid}/charts/{chartId}
```
Applies a JSON merge patch to one chart in a dashboard. Set `version` to the dashboard's current version, or `overwrite: true` to skip the check; a stale `version` returns `412`.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `uid` (path; string; required)
- `chartId` (path; string; required)
## Request body
Content type: `application/json` (required)
- `chart` (`DashboardChartPatchDocument`; required): JSON merge patch applied to the existing chart. If id is present, it must match the chartId path parameter.
- `message` (string)
- `overwrite` (boolean; default `false`)
- `version` (integer (int64)): Required when overwrite is false.
## Responses
### 200: Updated dashboard
Content type: `application/json`
- `dashboard` (`DashboardResource`; required)
- `overwritten` (boolean)
- `status` (string; one of `"created"`, `"updated"`; required)
### 400: Invalid dashboard chart patch
Content type: `application/json`
- `code` (string; required)
- `currentVersion` (integer (int64))
- `message` (string; required)
- `reason` (string)
- `uid` (string)
### 404: Dashboard or chart not found
Content type: `application/json`
- `code` (string; required)
- `currentVersion` (integer (int64))
- `message` (string; required)
- `reason` (string)
- `uid` (string)
### 412: Version conflict
Content type: `application/json`
- `code` (string; required)
- `currentVersion` (integer (int64))
- `message` (string; required)
- `reason` (string)
- `uid` (string)
## Schemas
### DashboardChartPatchDocument
Type: object
### DashboardResource
Object.
- `createdAt` (string (date-time); nullable): Creation time, present only for managed dashboards.
- `createdBy` (string; nullable): Creator, present only for managed dashboards.
- `dashboard` (`DashboardDocument`; required)
- `id` (string; required)
- `labelIds` (array of string; required)
- `labelNames` (array of string): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`)
- `type` (string; one of `"managed"`, `"integration"`; required): Managed dashboards are saved documents; integration dashboards are read-only and generated for matching datasets.
- `uid` (string; required): Managed dashboard UID, or stable integration dashboard ID for read requests.
- `updatedAt` (string (date-time); nullable): Last save time, present only for managed dashboards.
- `updatedBy` (string; nullable): Last editor, present only for managed dashboards.
- `updatedByAgent` (boolean): true when the last save came from the MCP server
- `version` (integer (int64); nullable): Save version, present only for managed dashboards.
### DashboardDocument
Same as `Dashboard`.
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### Dashboard
Object. Other fields aren't allowed.
- `name` (string; length 1–100; required)
- `owner` (string; required): User ID of the dashboard owner. Use `X-AXIOM-EVERYONE` to make the dashboard accessible to all users in the organization.
- `description` (string; length ≤ 1000)
- `charts` (array of `Chart`; items ≤ 200; required)
- `layout` (array of `LayoutItem`; items ≤ 200; required)
- `sections` (array of `Section`; items ≤ 1000)
- `refreshTime` (integer; one of `0`, `15`, `60`, `300`; required)
- `schemaVersion` (integer; one of `2`; required)
- `against` (string; one of `"-1h"`, `"-3h"`, `"-6h"`, `"-12h"`, `"-1d"`, `"-3d"`, `"-7d"`, `"-1w"`, `"-2w"`, `"-3w"`, `"-30d"`, `"-60d"`, `"-90d"`): Relative time comparison offset. Compares the current time window against a previous period offset by this duration. Mutually exclusive with `againstTimestamp` — setting one clears the other. Use an empty string or omit to disable comparison.
- `againstTimestamp` (string; length ≤ 100): Absolute or relative timestamp to compare against. Mutually exclusive with `against` — setting one clears the other. Accepts ISO 8601, `now-{duration}` (e.g. `now-1h`), or epoch milliseconds as a string.
- `timeWindowStart` (string; length 1–100; required): Start of the dashboard time range. Use `qr-now-{duration}` for a quick range relative to now, where duration is a number followed by `s` (seconds), `m` (minutes), `h` (hours), `d` (days), or `w` (weeks). Examples: `qr-now-5m`, `qr-now-1h`, `qr-now-7d`. Alternatively, use a Unix epoch millisecond timestamp as a string (e.g. `1704067200000`).
- `timeWindowEnd` (string; length 1–100; required): End of the dashboard time range. Use `qr-now` for a rolling window that tracks the current time (pair with a `qr-now-{duration}` start), or a Unix epoch millisecond timestamp as a string (e.g. `1704153600000`).
- `uid` (string; pattern `^[A-Za-z0-9_-]{1,128}$`): Optional dashboard UID. Must contain only letters, numbers, underscores, or hyphens, with length 1-128 when provided.
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
### Chart
One of the following, selected by `type`:
- `TimeSeriesChart` (`type`: `"TimeSeries"`)
- `HeatmapChart` (`type`: `"Heatmap"`)
- `LogStreamChart` (`type`: `"LogStream"`)
- `PieChart` (`type`: `"Pie"`)
- `ScatterChart` (`type`: `"Scatter"`)
- `TableChart` (`type`: `"Table"`)
- `TopKChart` (`type`: `"TopK"`)
- `StatisticChart` (`type`: `"Statistic"`)
- `GaugeChart` (`type`: `"Gauge"`)
- `NoteChart` (`type`: `"Note"`)
- `MonitorListChart` (`type`: `"MonitorList"`)
- `SmartFilterChart` (`type`: `"SmartFilter"`)
- `SpacerChart` (`type`: `"Spacer"`)
- `VisualizeChart` (`type`: `"Visualize"`)
### LayoutItem
Object. Other fields aren't allowed.
- `i` (string; length 1–200; required)
- `x` (integer; value 0–11; required)
- `y` (number; value ≥ 0; nullable; required)
- `w` (integer; value 1–12; required)
- `h` (number; value 0.5–100; required)
- `minW` (integer; value 1–12)
- `minH` (number; value 0.5–100)
- `maxW` (integer; value 1–12)
- `maxH` (integer; value 1–100)
- `static` (boolean)
### Section
Object. Other fields aren't allowed.
- `id` (string (uuid); required)
- `title` (string; length 1–200; required)
- `defaultCollapsed` (boolean)
### TimeSeriesChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"TimeSeries"`; required)
- `name` (string; length 1–500)
- `query` (`TimeSeriesChartQuery`; required)
### HeatmapChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Heatmap"`; required)
- `name` (string; length 1–500)
- `query` (`HeatmapChartQuery`; required)
- `colorScheme` (string; one of `"Blue"`, `"Orange"`, `"Red"`, `"Purple"`, `"Teal"`, `"Yellow"`, `"Green"`, `"Pink"`, `"Grey"`, `"Brown"`)
### LogStreamChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"LogStream"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `tableSettings` (`TableSettings`)
### PieChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Pie"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### ScatterChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Scatter"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### TableChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Table"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `tableSettings` (`TableSettings`)
### TopKChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"TopK"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### StatisticChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Statistic"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `colorScheme` (string; one of `"Blue"`, `"Orange"`, `"Red"`, `"Purple"`, `"Teal"`, `"Yellow"`, `"Green"`, `"Pink"`, `"Grey"`, `"Brown"`)
- `customUnits` (string; length ≤ 200)
- `showChart` (one of boolean, string)
- `hideValue` (boolean)
- `chartHeight` (one of string; length ≤ 100, number)
- `errorThreshold` (string; one of `"Above"`, `"AboveOrEqual"`, `"Below"`, `"BelowOrEqual"`, `"AboveOrBelow"`)
- `errorThresholdValue` (string; length ≤ 100)
- `warningThreshold` (string; one of `"Above"`, `"AboveOrEqual"`, `"Below"`, `"BelowOrEqual"`, `"AboveOrBelow"`)
- `warningThresholdValue` (string; length ≤ 100)
- `roundTo` (integer; value 0–10)
- `invertTheme` (boolean)
- `background` (string; length ≤ 200)
- `textColor` (string; length ≤ 200)
- `labelColor` (string; length ≤ 200)
- `chartFillColor` (string; length ≤ 200)
- `okColorProps` (`StatisticChartColorProps`)
- `warningColorProps` (`StatisticChartColorProps`)
- `errorColorProps` (`StatisticChartColorProps`)
### GaugeChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Gauge"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `segments` (array of `GaugeChartSegment`; items 1–100; required)
- `colorScale` (string; one of `"green-to-red"`, `"red-to-green"`)
- `showRing` (boolean)
- `labelMode` (string; one of `"none"`, `"boundaries"`, `"intervals"`)
- `showSparkline` (boolean)
- `scaleToTimeRange` (boolean)
- `scaleBaseDurationMs` (number; value > 0)
- `customUnits` (string; length ≤ 200)
### NoteChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Note"`; required)
- `text` (string; length 1–100000; required)
- `variant` (string; one of `""`, `"default"`, `"plain"`; nullable)
### MonitorListChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"MonitorList"`; required)
- `name` (string; length 1–500)
- `selectedMonitors` (array of string; length 1–200; items 1–200; required)
- `columns` (`MonitorListColumns`; required)
### SmartFilterChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"SmartFilter"`; required)
- `name` (string; length 1–500)
- `filters` (array of `SmartFilterConfig`; items 1–50; required)
- `logo` (string; length ≤ 2000)
- `logoDark` (string; length ≤ 2000)
### SpacerChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Spacer"`; required)
- `name` (string; length 1–500)
- `variant` (string; one of `"transparent"`, `"dashed"`, `"solid"`)
### VisualizeChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Visualize"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `visualization` (`VisualizeConfiguration`; required)
### TimeSeriesChartQuery
One of the following:
- `TimeSeriesNonMetricsAplQuery`
- `TimeSeriesNativeMplQuery`
### HeatmapChartQuery
One of the following:
- `HeatmapNonMetricsAplQuery`
- `HeatmapNativeMplQuery`
### SimpleChartQuery
One of the following:
- `SimpleNonMetricsAplQuery`
- `SimpleNativeMplQuery`
### TableSettings
Object. Other fields aren't allowed.
- `columns` (array of `ColumnSetting`; items ≤ 500)
- `settings` (`DatasetStreamSettings`)
### StatisticChartColorProps
Object. Other fields aren't allowed.
- `background` (string; length ≤ 200)
- `chartFillColor` (string; length ≤ 200)
- `labelColor` (string; length ≤ 200)
- `textColor` (string; length ≤ 200)
### GaugeChartSegment
Object. Other fields aren't allowed.
- `from` (number; required)
- `to` (number; required)
### MonitorListColumns
Object. Other fields aren't allowed.
- `status` (boolean; required)
- `history` (boolean; required)
- `dataset` (boolean; required)
- `type` (boolean; required)
- `notifiers` (boolean; required)
### SmartFilterConfig
One of the following:
- `SmartFilterSearch`
- `SmartFilterSelect`
### VisualizeConfiguration
One of the following, selected by `type`:
- `ScatterVisualization` (`type`: `"scatter"`)
- `BarVisualization` (`type`: `"bar"`)
- `HorizontalBarVisualization` (`type`: `"horizontalBar"`)
- `HistogramVisualization` (`type`: `"histogram"`)
- `FrequencyBarVisualization` (`type`: `"frequencyBar"`)
- `VisualizeHeatmap` (`type`: `"heatmap"`)
### TimeSeriesNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
- `queryOptions` (`TimeSeriesQueryOptions`)
### TimeSeriesNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
- `queryOptions` (`TimeSeriesQueryOptions`)
### HeatmapNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
- `queryOptions` (`HeatmapQueryOptions`)
### HeatmapNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
- `queryOptions` (`HeatmapQueryOptions`)
### SimpleNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
### SimpleNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
### ColumnSetting
One of the following:
- string; length ≤ 500
- `AdvancedColumnSetting`
### DatasetStreamSettings
Object. Other fields aren't allowed.
- `fontSize` (string; length ≤ 20; pattern `^\d+px$`)
- `highlightSeverity` (boolean)
- `showRaw` (boolean)
- `showEvent` (boolean)
- `showTimestamp` (boolean)
- `wrapLines` (boolean)
- `hideNulls` (boolean)
- `fitColumns` (boolean)
### SmartFilterSearch
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `type` (string; one of `"search"`; required)
### SmartFilterSelect
One of the following, selected by `selectType`:
- `SmartFilterSelectList` (`selectType`: `"list"`)
- `SmartFilterSelectQuery` (`selectType`: `"query"`)
### ScatterVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"scatter"`; required)
- `bindings` (`ScatterVisualizationBindings`; required)
- `settings` (`ScatterVisualizationSettings`; required)
### BarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"bar"`; required)
- `bindings` (`BarVisualizationBindings`; required)
- `settings` (`VisualizeBarSettings`; required)
### HorizontalBarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"horizontalBar"`; required)
- `bindings` (`HorizontalBarVisualizationBindings`; required)
- `settings` (`VisualizeBarSettings`; required)
### HistogramVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"histogram"`; required)
- `bindings` (`HistogramVisualizationBindings`; required)
- `settings` (`HistogramVisualizationSettings`; required)
### FrequencyBarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"frequencyBar"`; required)
- `bindings` (`FrequencyBarVisualizationBindings`; required)
- `settings` (`FrequencyBarVisualizationSettings`; required)
### VisualizeHeatmap
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"heatmap"`; required)
- `bindings` (`VisualizeHeatmapBindings`; required)
- `settings` (`VisualizeHeatmapSettings`; required)
### TimeSeriesQueryOptions
Object. Other fields aren't allowed.
- `displayNull` (string; one of `"auto"`, `"null"`, `"span"`, `"zero"`, `""`): Controls how empty intervals are rendered in time series charts. `auto` infers from the query, `null` leaves gaps, `span` connects adjacent points, `zero` fills with zero.
- `overlayCharts` (string; one of `"true"`, `"false"`, `""`): When enabled, charts are overlaid on a single chart instead of stacked separately.
- `shownColumns` (string; length ≤ 10000)
- `timeSeriesVariant` (string; one of `"area"`, `"bars"`, `"line"`, `"lines"`, `""`)
- `timeSeriesView` (string; one of `"charts"`, `"resultsTable"`, `"charts|resultsTable"`, `""`)
### HeatmapQueryOptions
Object. Other fields aren't allowed.
- `timeSeriesView` (string; one of `"charts"`, `"resultsTable"`, `"charts|resultsTable"`, `""`)
### AdvancedColumnSetting
Object. Other fields aren't allowed.
- `name` (string; length ≤ 500; required)
- `width` (integer; value > 0, ≤ 9007199254740991)
### SmartFilterSelectList
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `options` (`SmartFilterOptions`)
- `type` (string; one of `"select"`; required)
- `selectType` (string; one of `"list"`; required)
### SmartFilterSelectQuery
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `options` (all of one of array of `SmartFilterOption`; items ≤ 200, string; one of `null`; nullable, string; one of `""`): Pre-defined options merged with the dynamic options returned by `query` at runtime. Typically used to seed a default option (for example an "All" entry with `unset: true`) so the filter has a sensible initial selection before — or independent of — query results.
- `type` (string; one of `"select"`; required)
- `selectType` (string; one of `"query"`; required)
- `query` (`SmartFilterQuery`)
### ScatterVisualizationBindings
Object. Other fields aren't allowed.
- `x` (`VisualizeAxisColumnRef`; required)
- `y` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### ScatterVisualizationSettings
Object. Other fields aren't allowed.
- `colors` (`VisualizeColorSettings`)
- `xAxis` (`VisualizeAxisSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### BarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
- `value` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### VisualizeBarSettings
One of the following:
- `VisualizeStandardAggregationSettings`
- `VisualizePercentileAggregationSettings`
### HorizontalBarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
- `value` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### HistogramVisualizationBindings
Object. Other fields aren't allowed.
- `value` (`VisualizeNumericColumnRef`; required)
### HistogramVisualizationSettings
Object. Other fields aren't allowed.
- `binCount` (integer; value 1–200; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
### FrequencyBarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
### FrequencyBarVisualizationSettings
Object. Other fields aren't allowed.
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
### VisualizeHeatmapBindings
Object. Other fields aren't allowed.
- `x` (`VisualizeCategoricalColumnRef`; required)
- `y` (`VisualizeCategoricalColumnRef`; required)
### VisualizeHeatmapSettings
Object. Other fields aren't allowed.
- `categoryLimit` (integer; value 1–100; required)
### SmartFilterOptions
One of the following:
- array of `SmartFilterOption`; items ≤ 200
- string; one of `null`; nullable
- string; one of `""`
### SmartFilterOption
Object. Other fields aren't allowed.
- `key` (string; length ≤ 500; required)
- `value` (string; length ≤ 10000; required)
- `default` (boolean)
- `unset` (boolean)
### SmartFilterQuery
One of the following:
- `SmartFilterAplQuery`
- `SmartFilterNativeMplQuery`
### VisualizeAxisColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"datetime"`, `"integer"`, `"float"`; required)
### VisualizeNumericColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"integer"`, `"float"`; required)
### VisualizeCategoricalColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"string"`, `"boolean"`; required)
### VisualizeColorSettings
Object. Other fields aren't allowed.
- `palette` (string; one of `"axiom"`, `"polychrome"`; required)
- `assignment` (string; one of `"series-name"`, `"series-order"`; required)
### VisualizeAxisSettings
Object. Other fields aren't allowed.
- `scale` (string; one of `"linear"`, `"log"`; required)
- `range` (string; one of `"fit"`, `"includeZero"`; required)
### VisualizeLegendSettings
Object. Other fields aren't allowed.
- `position` (string; one of `"none"`, `"bottom"`, `"right"`; required)
### VisualizeStandardAggregationSettings
Object. Other fields aren't allowed.
- `aggregation` (string; one of `"avg"`, `"sum"`, `"count"`, `"min"`, `"max"`; required)
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### VisualizePercentileAggregationSettings
Object. Other fields aren't allowed.
- `aggregation` (string; one of `"percentile"`; required)
- `percentile` (number; value 0–100; required)
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### SmartFilterAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required): APL query that returns the list of options for the filter dropdown. The result must contain a `key` column and a `value` column — Axiom interprets each row as a `{ key, value }` pair for an option. Use `distinct` to collapse the source field to unique values, then `project` to expose the `key` and `value` columns.
Example:
```
['dataset-name'] | distinct field_name | project key=field_name, value=field_name
```
### SmartFilterNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required): MPL query that returns the list of options for the filter dropdown. The query must group by exactly one tag — Axiom uses each distinct value of that tag as both the key and the value of an option. Use `align using last` to simplify the query.
Example:
```
dataset:metric | align using last | group by tag using count
```
---
# Provision org
Source: https://axiom.co/docs/restapi/endpoints/provisionOrg
```http
POST https://api.axiom.co/v2/orgs/provision
```
Creates a temporary organization for an automated agent and returns a full-permission API token and a claim URL. The organization is deleted after 24 hours unless a human claims it. Doesn't require authentication and is rate limited per client IP.
For an overview of the full lifecycle, see [Agent-created organizations](/console/intelligence/agent-created-orgs).
## Authentication
No authentication required.
## Request body
Content type: `application/json` (required)
- `edgeDeployment` (string): Optional edge deployment (region) the organization is created in. If omitted, the environment's default region is used.
- `name` (string): Optional display name for the organization. If omitted, a name is auto-generated and the owner can rename it later.
## Responses
### 200: Provisioned organization.
Content type: `application/json`
- `claimUrl` (string; required): URL a human follows to claim ownership of the temporary org.
- `defaultEdgeDeployment` (string; required)
- `expiresAt` (string (date-time); required)
- `id` (string; required)
- `name` (string; required)
- `token` (string; required): Full-permission API token the agent uses to create datasets, ingest, and query. Returned once and never retrievable again.
### 400: Invalid name or edge deployment.
### 429: Rate limit exceeded, either for the client IP or for all callers. Retry later with backoff.
---
# Run APL query (legacy)
Source: https://axiom.co/docs/restapi/endpoints/queryApl
```http
POST https://api.axiom.co/v1/datasets/_apl?format=tabular
```
Runs an APL query through `api.axiom.co` and returns the result in the requested `format`. Results are routed through US East 1 (AWS); use the edge query endpoint to keep results in the edge deployment.
This is a legacy endpoint. Use [Run APL query to edge deployment](/restapi/endpoints/queryEdge) or [Run batch query to edge deployment](/restapi/endpoints/queryBatch) instead.
[Query cost limits](/console/intelligence/query-cost-limits) are only supported on the edge query endpoints. This endpoint rejects queries from API tokens and users that have query cost limits, whatever the value of the limit.
This endpoint allows you to query data stored in any edge deployment, but query results are routed through the US East 1 (AWS) deployment. This means that if you store data in an edge deployment other than US East 1 (AWS), query results leave the edge deployment where your data is stored. For more information, see [Edge deployments](/reference/edge-deployments).
The base domain for this endpoint is `https://api.axiom.co`, irrespective of your edge deployment.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `format` (query; string; one of `"legacy"`, `"tabular"`; required)
- `nocache` (query; boolean; default `false`)
- `saveAsKind` (query; string)
- `dataset_name` (query; string): When saveAsKind is true, this parameter indicates the name of the associated dataset.
## Request body
Content type: `application/json` (required)
- `apl` (string; required): APL query to execute. For more information, see [Introduction to APL](/apl/introduction).
- `cursor` (string)
- `endTime` (string)
- `includeCursor` (boolean)
- `queryOptions` (`QueryOptions`)
- `startTime` (string): start and end time for the query, these must be specified as RFC3339 strings
or using relative time expressions (e.g. now-1h, now-1d, now-1w, etc)
- `variables` (map of string to object): Variables is an optional set of additional variables that are inserted into the APL
## Responses
### 200: Successful APL result
Content type: `application/json`
- `buckets` (`Timeseries`)
- `datasetNames` (array of string; required)
- `fieldsMetaMap` (map of string to array of `DatasetField`): FieldsMetaMap contains the unit information (if we have it) for each field in the given dataset entry
- `format` (string; required): Format specifies the result set format. Either "legacy" (default) or "tabular".
- `matches` (array of `Entry`): Matches hold the matching events of a filter query in the "legacy" result format
- `request` (`QueryRequest`)
- `status` (`Status`; required)
- `tables` (array of `Table`): Tables hold the result tables in the "tabular" result format
### 400: The query is invalid or the format is unsupported.
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 430: Query prevented because the organization reached its query limit.
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### QueryOptions
Object.
- `against` (string)
- `againstStart` (string)
- `againstTimestamp` (string)
- `aggChartOpts` (string)
- `caseSensitive` (string)
- `containsTimeFilter` (string)
- `datasets` (string)
- `displayNull` (string)
- `editorContent` (string)
- `endColumn` (string)
- `endLineNumber` (string)
- `endTime` (string)
- `integrationsFilter` (string)
- `openIntervals` (string)
- `quickRange` (string)
- `resolution` (string)
- `shownColumns` (string)
- `startColumn` (string)
- `startLineNumber` (string)
- `startTime` (string)
- `timeSeriesVariant` (string)
- `timeSeriesView` (string)
### Timeseries
Object.
- `series` (array of `Interval`)
- `totals` (array of `EntryGroup`)
### DatasetField
Object.
- `description` (string)
- `hidden` (boolean; required)
- `name` (string; required)
- `type` (string; required)
- `unit` (string; required)
### Entry
Object.
- `_rowId` (string; required)
- `_sysTime` (string (date-time); required)
- `_time` (string (date-time); required)
- `data` (map of string to object; required)
### QueryRequest
Object.
- `aggregations` (array of `Aggregation`)
- `continuationToken` (string)
- `cursor` (string)
- `endTime` (string; required)
- `fieldsMeta` (array of `DatasetField`): FieldsMeta contains the unit information (if we have it) for each field
- `filter` (`Filter`)
- `groupBy` (array of string)
- `includeCursor` (boolean)
- `limit` (integer (uint32))
- `order` (array of `Order`)
- `project` (array of `Projection`)
- `resolution` (string; required): The time resolution of the query’s graph, in seconds. Valid values are
the query’s time range /100 at maximum and /1000 at minimum or "auto".
- `startTime` (string; required): start and end time for the query, these must be specified as RFC3339 strings
or using relative time expressions (e.g. now-1h, now-1d, now-1w, etc)
- `virtualFields` (array of `VirtualColumn`)
### Status
Object.
- `blocksExamined` (integer (uint64); required)
- `cacheStatus` (integer (uint8); required)
- `continuationToken` (string)
- `elapsedTime` (integer (int64); required)
- `isEstimate` (boolean)
- `isPartial` (boolean; required)
- `maxBlockTime` (string (date-time); required)
- `maxCursor` (string): Row id of the newest row, as seen server side.
May be higher than what the results include if the server scanned more data than included in the results.
Can be used to efficiently resume time-sorted non-aggregating queries (ie filtering only).
- `messages` (array of `Message`)
- `minBlockTime` (string (date-time); required)
- `minCursor` (string): Row id of the oldest row, as seen server side.
May be lower than what the results include if the server scanned more data than included in the results.
Can be used to efficiently resume time-sorted non-aggregating queries (ie filtering only).
- `numGroups` (integer (uint32); required)
- `rowsExamined` (integer (uint64); required)
- `rowsMatched` (integer (uint64); required)
### Table
The tabular result format can be enabled via APLQueryParams.ResultFormat or QueryParams.ResultFormat.
Object.
- `buckets` (`BucketInfo`)
- `columns` (array of array of object): Columns contain a series of arrays with the raw result data.
The columns here line up with the fields in the Fields array.
- `fields` (array of `FieldInfo`; required): Fields contain information about the fields included in these results.
The order of the fields match up with the order of the data in Columns.
- `groups` (array of `GroupInfo`; required): Groups specifies which grouping operations has been performed on the results.
- `name` (string; required): Name is the name assigned to this table. Defaults to "0". The name "_totals" is reserved for system use.
- `order` (array of `Order`; required): Order echoes the ordering clauses that was used to sort the results.
- `range` (`RangeInfo`)
- `sources` (array of `SourceInfo`; required): Sources contain the names of the datasets that contributed data to these results.
### Interval
Object.
- `endTime` (string (date-time); required)
- `groups` (array of `EntryGroup`)
- `startTime` (string (date-time); required)
### EntryGroup
Object.
- `aggregations` (array of `EntryGroupAgg`)
- `group` (map of string to object; required)
- `id` (integer (uint64); required)
### Aggregation
Object.
- `alias` (string)
- `argument` (object)
- `field` (string; required)
- `op` (string; one of `"count"`, `"distinct"`, `"sum"`, `"avg"`, `"min"`, `"max"`, `"topk"`, `"percentiles"`, `"histogram"`, `"stdev"`, `"variance"`, `"argmin"`, `"argmax"`, `"makeset"`, `"rate"`, `"makelist"`; required)
### Filter
Object.
- `caseSensitive` (boolean): Supported for these filters: starts-with, not-starts-with, ends-with, not-ends-with, contains, not-contains, eq, ne.
- `children` (array of string): Supported for these filters: and, or, not.
- `field` (string; required)
- `op` (string; one of `"and"`, `"or"`, `"not"`, `"eq"`, `"!="`, `"ne"`, `"exists"`, `"not-exists"`, `"gt"`, `"gte"`, `"lt"`, `"lte"`, `"starts-with"`, `"not-starts-with"`, `"ends-with"`, `"not-ends-with"`, `"contains"`, `"not-contains"`, `"regexp"`, `"not-regexp"`; required): We also support '==', but we’re not exporting that to swagger, because it can’t deal with it add >, >=, <, <= to that list, it breaks codegen.
- `value` (object)
### Order
Object.
- `desc` (boolean; required)
- `field` (string; required)
### Projection
Object.
- `alias` (string)
- `field` (string; required)
### VirtualColumn
Object.
- `alias` (string; required)
- `expr` (string; required)
### Message
Object.
- `code` (string)
- `count` (integer (int64); required)
- `msg` (string; required)
- `priority` (string; required)
### BucketInfo
The standard mode of operation is to create buckets on the _time column,
Object.
- `field` (string; required): Field specifies the field used to create buckets on. Normally this would be _time.
- `size` (object; required): An integer or float representing the fixed bucket size.
When the bucket field is _time this value is in nanoseconds.
### FieldInfo
Object.
- `agg` (`AggInfo`)
- `name` (string; required)
- `type` (string; required)
### GroupInfo
Object.
- `name` (string)
### RangeInfo
Object.
- `end` (string (date-time); required): End is the ending time the query is limited by.
Queries are restricted to the interval [start,end).
- `field` (string; required): Field specifies the field name on which the query range was restricted. Normally _time
- `start` (string (date-time); required): Start is the starting time the query is limited by.
Queries are restricted to the interval [start,end).
### SourceInfo
Result sources will typically be the names of a datasets that were searched,
but may be expanded to other things in the future.
Object.
- `name` (string; required)
### EntryGroupAgg
Object.
- `data` (object)
- `op` (string; required)
- `value` (object; required)
### AggInfo
AggInfo captures information about an aggregation
Object.
- `args` (array of object): Args specifies any non-field arguments for the aggregation. Fx. [10] for topk(players, 10).
- `fields` (array of string): Fields specifies the names of the fields this aggregation is computed on.
Fx ["players"] for topk(players, 10)
- `name` (string; required): Name is the system name of the aggregation, which is the string form of aggregation.Type.
If the aggregation is aliased, the alias is stored in the parent FieldInfo
---
# Run batch query to edge deployment
Source: https://axiom.co/docs/restapi/endpoints/queryBatch
```http
POST https://{axiom-domain}/v1/query/batch
```
Runs several APL and MPL queries in one request and streams each result as a server-sent event when it completes. Each item sets exactly one of `aplRequest` or `mplRequest`; per-item failures, including query limit errors, arrive as `error` events.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `maxConcurrency` (query; integer; value 1–20; default `10`): Maximum number of concurrent queries to execute
- `nocache` (query; boolean; default `false`): Whether to bypass cache for all queries in the batch
- `apl-source` (query; string): Contains the source of the APL query (for example console, dashboard, etc.)
- `apl-source-id` (query; string): Contains the id of the source, for example dashboard_id
## Request body
Content type: `application/json` (required)
Type: array of object
## Responses
### 200: SSE stream of query results. Each event carries a `kind` field ("apl" or "mpl") indicating how the `data` payload for that queryId should be interpreted. Per-item query-limit errors are delivered as SSE error events with status 429, the QueryLimitError body, and X-QueryLimit-* headers.
### default: The batch is invalid, for example it's empty or has a missing or duplicate `queryId`.
Content type: `application/json`
- `code` (integer): Status is the http status code associated with this error
- `detail` (`QueryErrorDetail`)
- `message` (string): a formatted user-facing error message
## Schemas
### QueryErrorDetail
Object.
- `column` (integer (int64)): Column is the column associated with this compile type error
- `compileErrorCode` (integer (int64); one of `1`, `2`, `16`, `17`, `32`, `33`, `34`): CompileErrorCode is a special error code that is only available for Compile Errors
It is an integer value that can be used to identify the error
- `errorType` (integer (int64); one of `1`, `2`, `3`, `4`): Error Type is an integer value indicating the kind of error
- `line` (integer (int64)): Line is the line associated with this compile type error
- `message` (string): Message is the raw error message without any formatting
---
# Run query (legacy)
Source: https://axiom.co/docs/restapi/endpoints/queryDataset
```http
POST https://api.axiom.co/v1/datasets/{dataset_name}/query
```
Runs a structured (non-APL) query against a dataset. Every response carries `Deprecation`, `Sunset`, and `Link` headers.
This endpoint is deprecated and stops working after October 31, 2026. Use [Run APL query to edge deployment](/restapi/endpoints/queryEdge) instead.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `saveAsKind` (query; string)
- `dataset_name` (path; string; required): Unique name of the dataset.
- `streaming-duration` (query; string)
- `nocache` (query; boolean)
## Request body
Content type: `application/json` (required)
- `aggregations` (array of `Aggregation`)
- `continuationToken` (string)
- `cursor` (string): A cursor for use in pagination. Use the cursor string returned in previous responses to fetch the next or previous page of results.
- `endTime` (string; required)
- `filter` (`Filter`)
- `groupBy` (array of string)
- `includeCursor` (boolean): Specifies whether to include the row identified by the `cursor` in the results. Default is false.
- `limit` (integer (uint32)): Specifies the maximum number of events to return. Default is 1000, minimum is 0, maximum is 50000.
- `order` (array of `Order`)
- `project` (array of `Projection`)
- `queryOptions` (`QueryOptions`)
- `resolution` (string; required): The time resolution of the query’s graph, in seconds. Valid values are
the query’s time range /100 at maximum and /1000 at minimum or "auto".
- `startTime` (string; required): start and end time for the query, these must be specified as RFC3339 strings
or using relative time expressions (e.g. now-1h, now-1d, now-1w, etc)
- `virtualFields` (array of `VirtualColumn`)
## Responses
### 200: Result
Content type: `application/json`
- `buckets` (`Timeseries`; required)
- `fieldsMeta` (array of `DatasetField`): FieldsMeta contains the unit information (if we have it) for each field
- `format` (string; required): Format specifies the result set format. Either "legacy" (default) or "tabular".
- `matches` (array of `Entry`): Matches hold the matching events of a filter query in the "legacy" result format
- `status` (`Status`; required)
- `tables` (array of `Table`): Tables hold the result tables in the "tabular" result format
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 430: Query prevented because the organization reached its query limit.
## Schemas
### Aggregation
Object.
- `alias` (string)
- `argument` (object)
- `field` (string; required)
- `op` (string; one of `"count"`, `"distinct"`, `"sum"`, `"avg"`, `"min"`, `"max"`, `"topk"`, `"percentiles"`, `"histogram"`, `"stdev"`, `"variance"`, `"argmin"`, `"argmax"`, `"makeset"`, `"rate"`, `"makelist"`; required)
### Filter
Object.
- `caseSensitive` (boolean): Supported for these filters: starts-with, not-starts-with, ends-with, not-ends-with, contains, not-contains, eq, ne.
- `children` (array of string): Supported for these filters: and, or, not.
- `field` (string; required)
- `op` (string; one of `"and"`, `"or"`, `"not"`, `"eq"`, `"!="`, `"ne"`, `"exists"`, `"not-exists"`, `"gt"`, `"gte"`, `"lt"`, `"lte"`, `"starts-with"`, `"not-starts-with"`, `"ends-with"`, `"not-ends-with"`, `"contains"`, `"not-contains"`, `"regexp"`, `"not-regexp"`; required): We also support '==', but we’re not exporting that to swagger, because it can’t deal with it add >, >=, <, <= to that list, it breaks codegen.
- `value` (object)
### Order
Object.
- `desc` (boolean; required)
- `field` (string; required)
### Projection
Object.
- `alias` (string)
- `field` (string; required)
### QueryOptions
Object.
- `against` (string)
- `againstStart` (string)
- `againstTimestamp` (string)
- `aggChartOpts` (string)
- `caseSensitive` (string)
- `containsTimeFilter` (string)
- `datasets` (string)
- `displayNull` (string)
- `editorContent` (string)
- `endColumn` (string)
- `endLineNumber` (string)
- `endTime` (string)
- `integrationsFilter` (string)
- `openIntervals` (string)
- `quickRange` (string)
- `resolution` (string)
- `shownColumns` (string)
- `startColumn` (string)
- `startLineNumber` (string)
- `startTime` (string)
- `timeSeriesVariant` (string)
- `timeSeriesView` (string)
### VirtualColumn
Object.
- `alias` (string; required)
- `expr` (string; required)
### Timeseries
Object.
- `series` (array of `Interval`)
- `totals` (array of `EntryGroup`)
### DatasetField
Object.
- `description` (string)
- `hidden` (boolean; required)
- `name` (string; required)
- `type` (string; required)
- `unit` (string; required)
### Entry
Object.
- `_rowId` (string; required)
- `_sysTime` (string (date-time); required)
- `_time` (string (date-time); required)
- `data` (map of string to object; required)
### Status
Object.
- `blocksExamined` (integer (uint64); required)
- `cacheStatus` (integer (uint8); required)
- `continuationToken` (string)
- `elapsedTime` (integer (int64); required)
- `isEstimate` (boolean)
- `isPartial` (boolean; required)
- `maxBlockTime` (string (date-time); required)
- `maxCursor` (string): Row id of the newest row, as seen server side.
May be higher than what the results include if the server scanned more data than included in the results.
Can be used to efficiently resume time-sorted non-aggregating queries (ie filtering only).
- `messages` (array of `Message`)
- `minBlockTime` (string (date-time); required)
- `minCursor` (string): Row id of the oldest row, as seen server side.
May be lower than what the results include if the server scanned more data than included in the results.
Can be used to efficiently resume time-sorted non-aggregating queries (ie filtering only).
- `numGroups` (integer (uint32); required)
- `rowsExamined` (integer (uint64); required)
- `rowsMatched` (integer (uint64); required)
### Table
The tabular result format can be enabled via APLQueryParams.ResultFormat or QueryParams.ResultFormat.
Object.
- `buckets` (`BucketInfo`)
- `columns` (array of array of object): Columns contain a series of arrays with the raw result data.
The columns here line up with the fields in the Fields array.
- `fields` (array of `FieldInfo`; required): Fields contain information about the fields included in these results.
The order of the fields match up with the order of the data in Columns.
- `groups` (array of `GroupInfo`; required): Groups specifies which grouping operations has been performed on the results.
- `name` (string; required): Name is the name assigned to this table. Defaults to "0". The name "_totals" is reserved for system use.
- `order` (array of `Order`; required): Order echoes the ordering clauses that was used to sort the results.
- `range` (`RangeInfo`)
- `sources` (array of `SourceInfo`; required): Sources contain the names of the datasets that contributed data to these results.
### Interval
Object.
- `endTime` (string (date-time); required)
- `groups` (array of `EntryGroup`)
- `startTime` (string (date-time); required)
### EntryGroup
Object.
- `aggregations` (array of `EntryGroupAgg`)
- `group` (map of string to object; required)
- `id` (integer (uint64); required)
### Message
Object.
- `code` (string)
- `count` (integer (int64); required)
- `msg` (string; required)
- `priority` (string; required)
### BucketInfo
The standard mode of operation is to create buckets on the _time column,
Object.
- `field` (string; required): Field specifies the field used to create buckets on. Normally this would be _time.
- `size` (object; required): An integer or float representing the fixed bucket size.
When the bucket field is _time this value is in nanoseconds.
### FieldInfo
Object.
- `agg` (`AggInfo`)
- `name` (string; required)
- `type` (string; required)
### GroupInfo
Object.
- `name` (string)
### RangeInfo
Object.
- `end` (string (date-time); required): End is the ending time the query is limited by.
Queries are restricted to the interval [start,end).
- `field` (string; required): Field specifies the field name on which the query range was restricted. Normally _time
- `start` (string (date-time); required): Start is the starting time the query is limited by.
Queries are restricted to the interval [start,end).
### SourceInfo
Result sources will typically be the names of a datasets that were searched,
but may be expanded to other things in the future.
Object.
- `name` (string; required)
### EntryGroupAgg
Object.
- `data` (object)
- `op` (string; required)
- `value` (object; required)
### AggInfo
AggInfo captures information about an aggregation
Object.
- `args` (array of object): Args specifies any non-field arguments for the aggregation. Fx. [10] for topk(players, 10).
- `fields` (array of string): Fields specifies the names of the fields this aggregation is computed on.
Fx ["players"] for topk(players, 10)
- `name` (string; required): Name is the system name of the aggregation, which is the string form of aggregation.Type.
If the aggregation is aliased, the alias is stored in the parent FieldInfo
---
# Run APL query to edge deployment
Source: https://axiom.co/docs/restapi/endpoints/queryEdge
```http
POST https://{axiom-domain}/v1/query/_apl?format=tabular
```
Runs an APL query against datasets in this edge deployment and returns the result in the requested `format`. Returns `429` when an organization, token, or user query cost limit is exhausted.
This endpoint replaces the legacy [Run APL query](/restapi/endpoints/queryApl) endpoint. Send the request to your edge deployment's base domain at the path `/v1/query/_apl`. The standard `/v1/datasets/_apl` path isn't served on edge domains, so requests to it return a `404`.
If you use an Axiom SDK, set the `edge` option on the client and it sends queries to this endpoint automatically. For more information, see [Configure region](/guides/javascript#configure-region).
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `format` (query; string; one of `"legacy"`, `"tabular"`, `"tabular-rows"`; required)
- `nocache` (query; boolean; default `false`)
- `saveAsKind` (query; string)
- `id` (query; string): when saveAsKind is true, this parameter indicates the id of the associated dataset
- `streaming-duration` (query; string)
- `apl-source` (query; string): contains the source of the APL query (for example console, dashboard, etc.)
- `apl-source-id` (query; string): contains the id of the source, for example dashboard_id
- `totals` (query; boolean): Include a totals table (only supported in MetricsDB)
## Request body
Content type: `application/json` (required)
- `apl` (string; required): APL query string
- `cursor` (string): Pagination cursor
- `defaultLimit` (integer): The default limit to use when no limit is specified in the query.
- `defaultOrder` (array of object): The default order to use when no order is specified in the query.
- `desc` (boolean)
- `field` (string)
- `endTime` (string): End time for the query range
- `includeCursor` (boolean): Include cursor in response
- `includeCursorField` (boolean): Defines if the _cursor field should be projected in the result
- `libraries` (array of string)
- `maxBinAutoGroups` (integer): Maximum number of groups to automatically bin into
- `queryOptions` (`QueryOptions`)
- `startTime` (string): start and end time for the query, these must be specified as RFC3339 strings
or using relative time expressions (e.g. now-1h, now-1d, now-1w, etc)
- `variables` (map of string to object): Variables is an optional set of additional variables that are inserted into the APL
## Responses
### 200: Query result in the requested `format`.
Content type: `application/json`
Type: `AplResult`
### 429: Query limit exceeded. Returned when an org, token, or user query budget is exhausted. The body names the tripped scope with its limit, usage, and reset.
Content type: `application/json`
Actionable payload when a query is rejected because an org, token, or
user budget is exhausted.
- `code` (integer; required): HTTP status code associated with this error
- `limit` (integer (uint64); required): Configured budget for the tripped scope
- `message` (string; required): A formatted user-facing error message
- `reset` (string (date-time); required): When the limit window resets
- `scope` (string; one of `"org"`, `"org-daily"`, `"token-hourly"`, `"token-daily"`, `"user-hourly"`, `"user-daily"`; required): Which budget tripped
- `unit` (string; one of `"credits"`, `"gbms"`; required): Unit of limit and used. credits for token/user/org-daily budgets, gbms for the org monthly cap.
- `used` (integer (uint64); required): Spend in the tripped scope at the time of the rejection
### default: User or system error
Content type: `application/json`
- `code` (integer): Status is the http status code associated with this error
- `detail` (`QueryErrorDetail`)
- `message` (string): a formatted user-facing error message
## Schemas
### QueryOptions
Object.
- `against` (string)
- `againstStart` (string)
- `againstTimestamp` (string)
- `aggChartOpts` (string)
- `caseSensitive` (string)
- `containsTimeFilter` (string)
- `datasets` (string)
- `displayNull` (string)
- `editorContent` (string)
- `endColumn` (string)
- `endLineNumber` (string)
- `endTime` (string)
- `integrationsFilter` (string)
- `nanosecondPrecision` (string)
- `openIntervals` (string)
- `overlayCharts` (string)
- `queryObject` (string)
- `quickRange` (string)
- `resolution` (string)
- `resultsHistogram` (string)
- `selection` (string)
- `shownColumns` (string)
- `startColumn` (string)
- `startLineNumber` (string)
- `startTime` (string)
- `timeSeriesVariant` (string)
- `timeSeriesView` (string)
### AplResult
APL query result (streaming binary data)
Type: object
### QueryErrorDetail
Object.
- `column` (integer (int64)): Column is the column associated with this compile type error
- `compileErrorCode` (integer (int64); one of `1`, `2`, `16`, `17`, `32`, `33`, `34`): CompileErrorCode is a special error code that is only available for Compile Errors
It is an integer value that can be used to identify the error
- `errorType` (integer (int64); one of `1`, `2`, `3`, `4`): Error Type is an integer value indicating the kind of error
- `line` (integer (int64)): Line is the line associated with this compile type error
- `message` (string): Message is the raw error message without any formatting
---
# Run MPL query to edge deployment
Source: https://axiom.co/docs/restapi/endpoints/queryMetrics
```http
POST https://{axiom-domain}/v1/query/_mpl
```
Runs an MPL query against metrics datasets in this edge deployment. The response format follows the `format` parameter or the `Accept` header and defaults to `metrics-v2`. Returns `429` when a query cost limit is exhausted.
Support for MPL queries is currently in public preview. For more information, see [Feature states](/platform-overview/roadmap#feature-states).
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `format` (query; string; one of `"metrics-v1"`, `"metrics-v2"`, `"metrics-v3"`, `"metrics-v4"`): Response format. If omitted, the Accept header is used for content negotiation. Defaults to metrics-v2 when neither is specified.
## Request body
Content type: `application/json` (required)
- `endTime` (string; required): End time for the query range
- `mpl` (string): The MPL query.
- `startTime` (string; required): start and end time for the query, these must be specified as RFC3339 strings
or using relative time expressions (e.g. now-1h, now-1d, now-1w, etc)
## Responses
### 200: Query result in the requested format.
Content type: `application/json`
Type: `MetricsResult`
### 429: Query limit exceeded. Returned when an org, token, or user query budget is exhausted. The body names the tripped scope with its limit, usage, and reset.
Content type: `application/json`
Actionable payload when a query is rejected because an org, token, or
user budget is exhausted.
- `code` (integer; required): HTTP status code associated with this error
- `limit` (integer (uint64); required): Configured budget for the tripped scope
- `message` (string; required): A formatted user-facing error message
- `reset` (string (date-time); required): When the limit window resets
- `scope` (string; one of `"org"`, `"org-daily"`, `"token-hourly"`, `"token-daily"`, `"user-hourly"`, `"user-daily"`; required): Which budget tripped
- `unit` (string; one of `"credits"`, `"gbms"`; required): Unit of limit and used. credits for token/user/org-daily budgets, gbms for the org monthly cap.
- `used` (integer (uint64); required): Spend in the tripped scope at the time of the rejection
### default: User or system error
Content type: `application/json`
- `code` (integer): HTTP status code of the error
- `message` (string): A formatted user-facing error message
## Schemas
### MetricsResult
Metrics query result (streaming binary data)
Type: object
---
# Regenerate API token
Source: https://axiom.co/docs/restapi/endpoints/regenerateToken
```http
POST https://api.axiom.co/v2/tokens/{id}/regenerate
```
Creates a new API token with the existing token's capabilities, or with those in `newToken`, and returns its secret value. The existing token keeps working until `existingTokenExpiresAt`; set it to the current time to revoke it immediately.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required)
## Request body
Content type: `application/json`
- `existingTokenExpiresAt` (string (date-time); required): Expiration date of the existing token (ISO 8601 format)
- `newToken` (`CreateAPIToken`)
- `newTokenExpiresAt` (string (date-time); nullable): Expiration date of the new token (ISO 8601 format)
## Responses
### 200: New API token, including its secret `token` value.
Content type: `application/json`
Type: `CreateAPITokenResponse`
### 400: Missing `existingTokenExpiresAt`, expiry set in both `newTokenExpiresAt` and `newToken.expiresAt`, or invalid capabilities in `newToken`.
### 404: API token not found or expired.
## Schemas
### CreateAPIToken
Object.
- `datasetCapabilities` (`datasetCapabilities`)
- `description` (string): Description of the token
- `expiresAt` (string (date-time); nullable): Expiration date of the token (ISO 8601 format)
- `name` (string; required): Name of the token
- `orgCapabilities` (`orgCapabilities`)
- `viewCapabilities` (`viewCapabilities`)
### CreateAPITokenResponse
All of the following:
- `APIToken`
- Object with:
- `token` (string)
### datasetCapabilities
Type: map of string to object
### orgCapabilities
Object.
- `annotations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Annotations capability
- `apiTokens` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): API tokens capability
- `auditLog` (array of string; one of `"read"`): Audit Log capability
- `billing` (array of string; one of `"read"`, `"update"`): Billing capability
- `dashboards` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Dashboards capability
- `datasets` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Datasets capability
- `endpoints` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Endpoints capability
- `integrations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Integrations capability
- `labels` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Labels capability
- `monitors` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Monitors capability
- `notifiers` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Notifiers capability
- `rbac` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Access control capability
- `sharedAccessKeys` (array of string; one of `"read"`, `"update"`): Shared access keys capability
- `users` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Users capability
- `views` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Views capability
### viewCapabilities
Type: map of string to object
### APIToken
Object.
- `apiLastUsed` (string (date-time); nullable; read-only): When the token was last used on an API other than ingest
- `auditIdentity` (string; read-only): Audit identity of the token
- `datasetCapabilities` (`datasetCapabilities`; required)
- `description` (string): Description of the token
- `expiresAt` (string (date-time); nullable; read-only): Expiration date of the token (ISO 8601 format)
- `id` (string; required): ID of the token
- `ingestLastUsed` (string (date-time); nullable; read-only): When the token was last used to ingest
- `name` (string; required): Name of the token
- `orgCapabilities` (`orgCapabilities`; required)
- `samlAuthenticated` (boolean)
- `viewCapabilities` (`viewCapabilities`)
---
# Delete user from org
Source: https://axiom.co/docs/restapi/endpoints/removeUserFromOrg
```http
DELETE https://api.axiom.co/v2/users/{id}
```
Removes a user from the organization without deleting their Axiom account. You can't remove the organization's last member. With a personal access token (PAT), only owners can remove an owner.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required)
## Responses
### 204: User removed from the organization.
---
# Replace label assignments
Source: https://axiom.co/docs/restapi/endpoints/replaceLabelAssignments
```http
PUT https://api.axiom.co/v2/labels/assignments
```
Replaces the complete label set for one target atomically, ignoring label IDs that do not exist in the caller's organization and removing stale assignments. The response contains only existing label IDs. Concurrent replacements use last-write-wins semantics. The operation requires only the target resource's update permission: dashboards|update, datasets|update, monitors|update, or notifiers|update. Datasets must also be readable, writable, and owned by the caller's organization. Monitor dataset permissions match those required to read the monitor. A target that uses the wrong identifier for its type returns 400. An unknown target type, duplicate label IDs, and more than 500 label IDs fail request validation with 422. A target that does not exist or is not owned by the caller's organization returns 404.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
Content type: `application/json` (required)
- `labelIds` (array of string; items ≤ 500; required)
- `target` (`LabelAssignmentTarget`; required)
## Responses
### 200: The target's complete label set after the atomic replacement.
Content type: `application/json`
- `labelIds` (array of string; required)
- `target` (`LabelAssignmentTarget`; required)
### 400: The target uses the wrong identifier for its type.
### 403: The caller lacks the target resource's update permission, or the dataset is shared or not writable.
### 404: The target does not exist or is not owned by the caller's organization.
### 422: Request validation failed. The payload contains an unknown target type, duplicate label IDs, or more than 500 label IDs.
## Schemas
### LabelAssignmentTarget
A resource that supports organization labels. Single-identifier targets use id; frontend-generated integration dashboards use templateId and dataset.
Object.
- `dataset` (string): Required only for frontend-generated integration dashboards and rejected for other target types. Use the current dataset name. Assignments use the underlying dataset instance, so permanent deletion and recreation do not restore old labels.
- `id` (string): Public identifier for the resource. Use the dashboard UID for a dashboard, the dataset name for a dataset, and the ID returned by the monitor, notifier, or backend-provided integration dashboard APIs.
- `templateId` (string; length ≤ 128): Stable frontend-owned template key for a frontend-generated integration dashboard, such as k8s.stats. Requires dataset and rejects id. Whitespace and control characters are rejected.
- `type` (string; one of `"dashboard"`, `"integration_dashboard"`, `"dataset"`, `"monitor"`, `"notifier"`; required)
---
# Trim dataset
Source: https://axiom.co/docs/restapi/endpoints/trimDataset
```http
POST https://api.axiom.co/v1/datasets/{dataset_name}/trim
```
Queues a job that deletes data older than `maxDuration` from a dataset and returns the job ID. Deletion runs asynchronously and can take several hours to complete.
When the endpoint returns the status code 200, it means that the deletion request is queued. The deletion itself might take several hours to complete.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_name` (path; string; required): Unique name of the dataset.
## Request body
Content type: `application/json` (required)
- `maxDuration` (string; required)
## Responses
### 200: Job created.
Content type: `application/json`
- `jobID` (string): ID of the trim job
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
---
# Update annotation
Source: https://axiom.co/docs/restapi/endpoints/updateAnnotation
```http
PUT https://api.axiom.co/v2/annotations/{id}
```
Updates an annotation. Only the fields you include change. Omitted or empty fields keep their current values, so you can't clear a field.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; pattern `^ann_`; required): Unique ID of the annotation
## Request body
Content type: `application/json` (required)
- `datasets` (array of string; length ≥ 1): array of dataset names for which the annotation appears on charts
- `description` (string; length ≤ 512): Explanation of the event the annotation marks on the charts
- `endTime` (string (date-time)): End time of the annotation
- `time` (string (date-time)): Time the annotation marks on the charts. If you don't include this field, Axiom assigns the time of the API request to the annotation.
- `title` (string; length ≤ 256): Summary of the annotation that appears on the charts
- `type` (string; length ≤ 256; pattern `^[a-z0-9-]+$`): Type of the event marked by the annotation. Use only alphanumeric characters or hyphens. For example, "production-deployment".
- `url` (string; length ≤ 512): URL relevant for the event marked by the annotation. For example, link to GitHub pull request.
## Responses
### 200: Updated annotation.
Content type: `application/json`
- `datasets` (array of string; length ≥ 1; items ≥ 1; required): array of dataset names for which the annotation appears on charts
- `description` (string; length ≤ 512): Explanation of the event the annotation marks on the charts
- `endTime` (string (date-time); nullable): End time of the annotation
- `id` (string; required)
- `time` (string (date-time); required): Time the annotation marks on the charts. If you don't include this field, Axiom assigns the time of the API request to the annotation.
- `title` (string; length ≤ 256): Summary of the annotation that appears on the charts
- `type` (string; length ≤ 256; pattern `^[a-z0-9-]+$`; required): Type of the event marked by the annotation. Use only alphanumeric characters or hyphens. For example, "production-deployment".
- `url` (string; length ≤ 512): URL relevant for the event marked by the annotation. For example, link to GitHub pull request.
### 400: Invalid annotation ID or the updated annotation is invalid.
### 404: Annotation not found.
---
# Update current user
Source: https://axiom.co/docs/restapi/endpoints/updateCurrentUser
```http
PUT https://api.axiom.co/v2/user
```
Updates the name of the user who owns the personal access token (PAT) used to authenticate. API tokens aren't supported. The response doesn't include `role`.
Using this endpoint, you can update your own user. Authorize the request with a [personal access token (PAT)](/reference/tokens).
You can’t update other users with this endpoint, and you can’t use an API token to authorize the request.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Request body
Content type: `application/json` (required)
Object representing a user update request
- `name` (string; required): New name for the user
## Responses
### 200: Updated user.
Content type: `application/json`
Represents a user in the system
- `email` (string; required): User's email address
- `id` (string; required): Unique identifier for the user
- `name` (string; required): User's full name
- `role` (`UserDetailsRole`; required)
### 400: Invalid name, or the request was authenticated with an API token.
## Schemas
### UserDetailsRole
Detailed information about a user's role
Object.
- `id` (string; required): Unique identifier for the role
- `name` (string; required): Human-readable name of the role
---
# Update dashboard
Source: https://axiom.co/docs/restapi/endpoints/updateDashboard
```http
PUT https://api.axiom.co/v2/dashboards/uid/{uid}
```
Replaces the dashboard document for the UID. Set `version` to the current version, or `overwrite: true` to skip the check; a stale `version` returns `412`. Creates the dashboard and returns `201` if the UID doesn't exist.
For the structure of the `dashboard` field, see [Dashboard JSON](/restapi/dashboard-json). To validate a dashboard document before you send it, use the JSON Schema at `https://axiom.co/docs/schemas/dashboard.json`.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `uid` (path; string; required)
## Request body
Content type: `application/json` (required)
- `dashboard` (`DashboardDocument`; required)
- `labelIds` (array of string; items ≤ 500): Existing label IDs; replaces assignments when supplied, clears with [], and preserves them when omitted or null.
- `message` (string)
- `overwrite` (boolean; default `false`)
- `uid` (string): Stable external dashboard identifier (org-scoped unique).
- `version` (integer (int64)): Required for updates when overwrite is false.
## Responses
### 200: Updated dashboard
Content type: `application/json`
- `dashboard` (`DashboardResource`; required)
- `overwritten` (boolean)
- `status` (string; one of `"created"`, `"updated"`; required)
### 201: Created dashboard
Content type: `application/json`
- `dashboard` (`DashboardResource`; required)
- `overwritten` (boolean)
- `status` (string; one of `"created"`, `"updated"`; required)
### 400: Invalid dashboard payload
Content type: `application/json`
- `code` (string; required)
- `currentVersion` (integer (int64))
- `message` (string; required)
- `reason` (string)
- `uid` (string)
### 409: Dashboard already exists
Content type: `application/json`
- `code` (string; required)
- `currentVersion` (integer (int64))
- `message` (string; required)
- `reason` (string)
- `uid` (string)
### 412: Version conflict
Content type: `application/json`
- `code` (string; required)
- `currentVersion` (integer (int64))
- `message` (string; required)
- `reason` (string)
- `uid` (string)
## Schemas
### DashboardDocument
Same as `Dashboard`.
### DashboardResource
Object.
- `createdAt` (string (date-time); nullable): Creation time, present only for managed dashboards.
- `createdBy` (string; nullable): Creator, present only for managed dashboards.
- `dashboard` (`DashboardDocument`; required)
- `id` (string; required)
- `labelIds` (array of string; required)
- `labelNames` (array of string): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`)
- `type` (string; one of `"managed"`, `"integration"`; required): Managed dashboards are saved documents; integration dashboards are read-only and generated for matching datasets.
- `uid` (string; required): Managed dashboard UID, or stable integration dashboard ID for read requests.
- `updatedAt` (string (date-time); nullable): Last save time, present only for managed dashboards.
- `updatedBy` (string; nullable): Last editor, present only for managed dashboards.
- `updatedByAgent` (boolean): true when the last save came from the MCP server
- `version` (integer (int64); nullable): Save version, present only for managed dashboards.
### Dashboard
Object. Other fields aren't allowed.
- `name` (string; length 1–100; required)
- `owner` (string; required): User ID of the dashboard owner. Use `X-AXIOM-EVERYONE` to make the dashboard accessible to all users in the organization.
- `description` (string; length ≤ 1000)
- `charts` (array of `Chart`; items ≤ 200; required)
- `layout` (array of `LayoutItem`; items ≤ 200; required)
- `sections` (array of `Section`; items ≤ 1000)
- `refreshTime` (integer; one of `0`, `15`, `60`, `300`; required)
- `schemaVersion` (integer; one of `2`; required)
- `against` (string; one of `"-1h"`, `"-3h"`, `"-6h"`, `"-12h"`, `"-1d"`, `"-3d"`, `"-7d"`, `"-1w"`, `"-2w"`, `"-3w"`, `"-30d"`, `"-60d"`, `"-90d"`): Relative time comparison offset. Compares the current time window against a previous period offset by this duration. Mutually exclusive with `againstTimestamp` — setting one clears the other. Use an empty string or omit to disable comparison.
- `againstTimestamp` (string; length ≤ 100): Absolute or relative timestamp to compare against. Mutually exclusive with `against` — setting one clears the other. Accepts ISO 8601, `now-{duration}` (e.g. `now-1h`), or epoch milliseconds as a string.
- `timeWindowStart` (string; length 1–100; required): Start of the dashboard time range. Use `qr-now-{duration}` for a quick range relative to now, where duration is a number followed by `s` (seconds), `m` (minutes), `h` (hours), `d` (days), or `w` (weeks). Examples: `qr-now-5m`, `qr-now-1h`, `qr-now-7d`. Alternatively, use a Unix epoch millisecond timestamp as a string (e.g. `1704067200000`).
- `timeWindowEnd` (string; length 1–100; required): End of the dashboard time range. Use `qr-now` for a rolling window that tracks the current time (pair with a `qr-now-{duration}` start), or a Unix epoch millisecond timestamp as a string (e.g. `1704153600000`).
- `uid` (string; pattern `^[A-Za-z0-9_-]{1,128}$`): Optional dashboard UID. Must contain only letters, numbers, underscores, or hyphens, with length 1-128 when provided.
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### Chart
One of the following, selected by `type`:
- `TimeSeriesChart` (`type`: `"TimeSeries"`)
- `HeatmapChart` (`type`: `"Heatmap"`)
- `LogStreamChart` (`type`: `"LogStream"`)
- `PieChart` (`type`: `"Pie"`)
- `ScatterChart` (`type`: `"Scatter"`)
- `TableChart` (`type`: `"Table"`)
- `TopKChart` (`type`: `"TopK"`)
- `StatisticChart` (`type`: `"Statistic"`)
- `GaugeChart` (`type`: `"Gauge"`)
- `NoteChart` (`type`: `"Note"`)
- `MonitorListChart` (`type`: `"MonitorList"`)
- `SmartFilterChart` (`type`: `"SmartFilter"`)
- `SpacerChart` (`type`: `"Spacer"`)
- `VisualizeChart` (`type`: `"Visualize"`)
### LayoutItem
Object. Other fields aren't allowed.
- `i` (string; length 1–200; required)
- `x` (integer; value 0–11; required)
- `y` (number; value ≥ 0; nullable; required)
- `w` (integer; value 1–12; required)
- `h` (number; value 0.5–100; required)
- `minW` (integer; value 1–12)
- `minH` (number; value 0.5–100)
- `maxW` (integer; value 1–12)
- `maxH` (integer; value 1–100)
- `static` (boolean)
### Section
Object. Other fields aren't allowed.
- `id` (string (uuid); required)
- `title` (string; length 1–200; required)
- `defaultCollapsed` (boolean)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
### TimeSeriesChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"TimeSeries"`; required)
- `name` (string; length 1–500)
- `query` (`TimeSeriesChartQuery`; required)
### HeatmapChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Heatmap"`; required)
- `name` (string; length 1–500)
- `query` (`HeatmapChartQuery`; required)
- `colorScheme` (string; one of `"Blue"`, `"Orange"`, `"Red"`, `"Purple"`, `"Teal"`, `"Yellow"`, `"Green"`, `"Pink"`, `"Grey"`, `"Brown"`)
### LogStreamChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"LogStream"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `tableSettings` (`TableSettings`)
### PieChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Pie"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### ScatterChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Scatter"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### TableChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Table"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `tableSettings` (`TableSettings`)
### TopKChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"TopK"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
### StatisticChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Statistic"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `colorScheme` (string; one of `"Blue"`, `"Orange"`, `"Red"`, `"Purple"`, `"Teal"`, `"Yellow"`, `"Green"`, `"Pink"`, `"Grey"`, `"Brown"`)
- `customUnits` (string; length ≤ 200)
- `showChart` (one of boolean, string)
- `hideValue` (boolean)
- `chartHeight` (one of string; length ≤ 100, number)
- `errorThreshold` (string; one of `"Above"`, `"AboveOrEqual"`, `"Below"`, `"BelowOrEqual"`, `"AboveOrBelow"`)
- `errorThresholdValue` (string; length ≤ 100)
- `warningThreshold` (string; one of `"Above"`, `"AboveOrEqual"`, `"Below"`, `"BelowOrEqual"`, `"AboveOrBelow"`)
- `warningThresholdValue` (string; length ≤ 100)
- `roundTo` (integer; value 0–10)
- `invertTheme` (boolean)
- `background` (string; length ≤ 200)
- `textColor` (string; length ≤ 200)
- `labelColor` (string; length ≤ 200)
- `chartFillColor` (string; length ≤ 200)
- `okColorProps` (`StatisticChartColorProps`)
- `warningColorProps` (`StatisticChartColorProps`)
- `errorColorProps` (`StatisticChartColorProps`)
### GaugeChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Gauge"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `segments` (array of `GaugeChartSegment`; items 1–100; required)
- `colorScale` (string; one of `"green-to-red"`, `"red-to-green"`)
- `showRing` (boolean)
- `labelMode` (string; one of `"none"`, `"boundaries"`, `"intervals"`)
- `showSparkline` (boolean)
- `scaleToTimeRange` (boolean)
- `scaleBaseDurationMs` (number; value > 0)
- `customUnits` (string; length ≤ 200)
### NoteChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Note"`; required)
- `text` (string; length 1–100000; required)
- `variant` (string; one of `""`, `"default"`, `"plain"`; nullable)
### MonitorListChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"MonitorList"`; required)
- `name` (string; length 1–500)
- `selectedMonitors` (array of string; length 1–200; items 1–200; required)
- `columns` (`MonitorListColumns`; required)
### SmartFilterChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"SmartFilter"`; required)
- `name` (string; length 1–500)
- `filters` (array of `SmartFilterConfig`; items 1–50; required)
- `logo` (string; length ≤ 2000)
- `logoDark` (string; length ≤ 2000)
### SpacerChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Spacer"`; required)
- `name` (string; length 1–500)
- `variant` (string; one of `"transparent"`, `"dashed"`, `"solid"`)
### VisualizeChart
Object. Other fields aren't allowed.
- `id` (string; length 1–200; required)
- `sectionId` (string (uuid))
- `type` (string; one of `"Visualize"`; required)
- `name` (string; length 1–500)
- `query` (`SimpleChartQuery`; required)
- `visualization` (`VisualizeConfiguration`; required)
### TimeSeriesChartQuery
One of the following:
- `TimeSeriesNonMetricsAplQuery`
- `TimeSeriesNativeMplQuery`
### HeatmapChartQuery
One of the following:
- `HeatmapNonMetricsAplQuery`
- `HeatmapNativeMplQuery`
### SimpleChartQuery
One of the following:
- `SimpleNonMetricsAplQuery`
- `SimpleNativeMplQuery`
### TableSettings
Object. Other fields aren't allowed.
- `columns` (array of `ColumnSetting`; items ≤ 500)
- `settings` (`DatasetStreamSettings`)
### StatisticChartColorProps
Object. Other fields aren't allowed.
- `background` (string; length ≤ 200)
- `chartFillColor` (string; length ≤ 200)
- `labelColor` (string; length ≤ 200)
- `textColor` (string; length ≤ 200)
### GaugeChartSegment
Object. Other fields aren't allowed.
- `from` (number; required)
- `to` (number; required)
### MonitorListColumns
Object. Other fields aren't allowed.
- `status` (boolean; required)
- `history` (boolean; required)
- `dataset` (boolean; required)
- `type` (boolean; required)
- `notifiers` (boolean; required)
### SmartFilterConfig
One of the following:
- `SmartFilterSearch`
- `SmartFilterSelect`
### VisualizeConfiguration
One of the following, selected by `type`:
- `ScatterVisualization` (`type`: `"scatter"`)
- `BarVisualization` (`type`: `"bar"`)
- `HorizontalBarVisualization` (`type`: `"horizontalBar"`)
- `HistogramVisualization` (`type`: `"histogram"`)
- `FrequencyBarVisualization` (`type`: `"frequencyBar"`)
- `VisualizeHeatmap` (`type`: `"heatmap"`)
### TimeSeriesNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
- `queryOptions` (`TimeSeriesQueryOptions`)
### TimeSeriesNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
- `queryOptions` (`TimeSeriesQueryOptions`)
### HeatmapNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
- `queryOptions` (`HeatmapQueryOptions`)
### HeatmapNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
- `queryOptions` (`HeatmapQueryOptions`)
### SimpleNonMetricsAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required)
### SimpleNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required)
### ColumnSetting
One of the following:
- string; length ≤ 500
- `AdvancedColumnSetting`
### DatasetStreamSettings
Object. Other fields aren't allowed.
- `fontSize` (string; length ≤ 20; pattern `^\d+px$`)
- `highlightSeverity` (boolean)
- `showRaw` (boolean)
- `showEvent` (boolean)
- `showTimestamp` (boolean)
- `wrapLines` (boolean)
- `hideNulls` (boolean)
- `fitColumns` (boolean)
### SmartFilterSearch
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `type` (string; one of `"search"`; required)
### SmartFilterSelect
One of the following, selected by `selectType`:
- `SmartFilterSelectList` (`selectType`: `"list"`)
- `SmartFilterSelectQuery` (`selectType`: `"query"`)
### ScatterVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"scatter"`; required)
- `bindings` (`ScatterVisualizationBindings`; required)
- `settings` (`ScatterVisualizationSettings`; required)
### BarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"bar"`; required)
- `bindings` (`BarVisualizationBindings`; required)
- `settings` (`VisualizeBarSettings`; required)
### HorizontalBarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"horizontalBar"`; required)
- `bindings` (`HorizontalBarVisualizationBindings`; required)
- `settings` (`VisualizeBarSettings`; required)
### HistogramVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"histogram"`; required)
- `bindings` (`HistogramVisualizationBindings`; required)
- `settings` (`HistogramVisualizationSettings`; required)
### FrequencyBarVisualization
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"frequencyBar"`; required)
- `bindings` (`FrequencyBarVisualizationBindings`; required)
- `settings` (`FrequencyBarVisualizationSettings`; required)
### VisualizeHeatmap
Object. Other fields aren't allowed.
- `version` (number; one of `1`; required)
- `type` (string; one of `"heatmap"`; required)
- `bindings` (`VisualizeHeatmapBindings`; required)
- `settings` (`VisualizeHeatmapSettings`; required)
### TimeSeriesQueryOptions
Object. Other fields aren't allowed.
- `displayNull` (string; one of `"auto"`, `"null"`, `"span"`, `"zero"`, `""`): Controls how empty intervals are rendered in time series charts. `auto` infers from the query, `null` leaves gaps, `span` connects adjacent points, `zero` fills with zero.
- `overlayCharts` (string; one of `"true"`, `"false"`, `""`): When enabled, charts are overlaid on a single chart instead of stacked separately.
- `shownColumns` (string; length ≤ 10000)
- `timeSeriesVariant` (string; one of `"area"`, `"bars"`, `"line"`, `"lines"`, `""`)
- `timeSeriesView` (string; one of `"charts"`, `"resultsTable"`, `"charts|resultsTable"`, `""`)
### HeatmapQueryOptions
Object. Other fields aren't allowed.
- `timeSeriesView` (string; one of `"charts"`, `"resultsTable"`, `"charts|resultsTable"`, `""`)
### AdvancedColumnSetting
Object. Other fields aren't allowed.
- `name` (string; length ≤ 500; required)
- `width` (integer; value > 0, ≤ 9007199254740991)
### SmartFilterSelectList
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `options` (`SmartFilterOptions`)
- `type` (string; one of `"select"`; required)
- `selectType` (string; one of `"list"`; required)
### SmartFilterSelectQuery
Object. Other fields aren't allowed.
- `id` (string; length ≤ 200; required)
- `name` (string; length ≤ 200; required)
- `active` (boolean)
- `options` (all of one of array of `SmartFilterOption`; items ≤ 200, string; one of `null`; nullable, string; one of `""`): Pre-defined options merged with the dynamic options returned by `query` at runtime. Typically used to seed a default option (for example an "All" entry with `unset: true`) so the filter has a sensible initial selection before — or independent of — query results.
- `type` (string; one of `"select"`; required)
- `selectType` (string; one of `"query"`; required)
- `query` (`SmartFilterQuery`)
### ScatterVisualizationBindings
Object. Other fields aren't allowed.
- `x` (`VisualizeAxisColumnRef`; required)
- `y` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### ScatterVisualizationSettings
Object. Other fields aren't allowed.
- `colors` (`VisualizeColorSettings`)
- `xAxis` (`VisualizeAxisSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### BarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
- `value` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### VisualizeBarSettings
One of the following:
- `VisualizeStandardAggregationSettings`
- `VisualizePercentileAggregationSettings`
### HorizontalBarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
- `value` (`VisualizeNumericColumnRef`; required)
- `series` (`VisualizeCategoricalColumnRef`)
### HistogramVisualizationBindings
Object. Other fields aren't allowed.
- `value` (`VisualizeNumericColumnRef`; required)
### HistogramVisualizationSettings
Object. Other fields aren't allowed.
- `binCount` (integer; value 1–200; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
### FrequencyBarVisualizationBindings
Object. Other fields aren't allowed.
- `category` (`VisualizeCategoricalColumnRef`; required)
### FrequencyBarVisualizationSettings
Object. Other fields aren't allowed.
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
### VisualizeHeatmapBindings
Object. Other fields aren't allowed.
- `x` (`VisualizeCategoricalColumnRef`; required)
- `y` (`VisualizeCategoricalColumnRef`; required)
### VisualizeHeatmapSettings
Object. Other fields aren't allowed.
- `categoryLimit` (integer; value 1–100; required)
### SmartFilterOptions
One of the following:
- array of `SmartFilterOption`; items ≤ 200
- string; one of `null`; nullable
- string; one of `""`
### SmartFilterOption
Object. Other fields aren't allowed.
- `key` (string; length ≤ 500; required)
- `value` (string; length ≤ 10000; required)
- `default` (boolean)
- `unset` (boolean)
### SmartFilterQuery
One of the following:
- `SmartFilterAplQuery`
- `SmartFilterNativeMplQuery`
### VisualizeAxisColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"datetime"`, `"integer"`, `"float"`; required)
### VisualizeNumericColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"integer"`, `"float"`; required)
### VisualizeCategoricalColumnRef
Object. Other fields aren't allowed.
- `name` (string; length 1–500; required)
- `type` (string; one of `"string"`, `"boolean"`; required)
### VisualizeColorSettings
Object. Other fields aren't allowed.
- `palette` (string; one of `"axiom"`, `"polychrome"`; required)
- `assignment` (string; one of `"series-name"`, `"series-order"`; required)
### VisualizeAxisSettings
Object. Other fields aren't allowed.
- `scale` (string; one of `"linear"`, `"log"`; required)
- `range` (string; one of `"fit"`, `"includeZero"`; required)
### VisualizeLegendSettings
Object. Other fields aren't allowed.
- `position` (string; one of `"none"`, `"bottom"`, `"right"`; required)
### VisualizeStandardAggregationSettings
Object. Other fields aren't allowed.
- `aggregation` (string; one of `"avg"`, `"sum"`, `"count"`, `"min"`, `"max"`; required)
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### VisualizePercentileAggregationSettings
Object. Other fields aren't allowed.
- `aggregation` (string; one of `"percentile"`; required)
- `percentile` (number; value 0–100; required)
- `categoryLimit` (integer; value 1–100; required)
- `colors` (`VisualizeColorSettings`)
- `yAxis` (`VisualizeAxisSettings`)
- `legend` (`VisualizeLegendSettings`)
### SmartFilterAplQuery
Object. Other fields aren't allowed.
- `apl` (string; length 1–500000; required): APL query that returns the list of options for the filter dropdown. The result must contain a `key` column and a `value` column — Axiom interprets each row as a `{ key, value }` pair for an option. Use `distinct` to collapse the source field to unique values, then `project` to expose the `key` and `value` columns.
Example:
```
['dataset-name'] | distinct field_name | project key=field_name, value=field_name
```
### SmartFilterNativeMplQuery
Object. Other fields aren't allowed.
- `mpl` (string; length 1–500000; required): MPL query that returns the list of options for the filter dropdown. The query must group by exactly one tag — Axiom uses each distinct value of that tag as both the key and the value of an option. Use `align using last` to simplify the query.
Example:
```
dataset:metric | align using last | group by tag using count
```
---
# Update dataset
Source: https://axiom.co/docs/restapi/endpoints/updateDataset
```http
PUT https://api.axiom.co/v2/datasets/{dataset_id}
```
Updates the `description` and `retentionDays` of a dataset. Both values are replaced, so omitting `description` clears it, and omitting `retentionDays` or setting it to `0` applies your plan's default retention. `labelIds` replaces assignments when supplied; [] clears them. Omitted or null `labelIds` preserves assignments on updates and creates an unlabeled resource on creation. IDs must belong to existing labels in your organization and are validated before saving.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_id` (path; string; required)
## Request body
Content type: `application/json` (required)
- `description` (string)
- `labelIds` (array of string; items ≤ 500): Existing label IDs; replaces assignments when supplied, clears with [], and preserves them when omitted or null.
- `retentionDays` (integer): Number of days to retain data in the dataset
- `useRetentionPeriod` (boolean): Ignored. Axiom derives this value from `retentionDays`.
## Responses
### 200: Updated dataset.
Content type: `application/json`
- `canWrite` (boolean): Whether this dataset has write access
- `created` (string (date-time); required): The RFC3339-formatted time when the dataset was created.
- `createdByAgent` (boolean): true when the MCP server created this dataset
- `description` (string; required): Dataset description
- `edgeDeployment` (string): Edge deployment of the dataset
- `edgeDeploymentUrl` (string): URL of the edge deployment
- `id` (string; required): Dataset ID
- `kind` (string; one of `"otel:metrics:v1"`, `"otel:traces:v1"`, `"otel:logs:v1"`, `"axiom:events:v1"`; default `"axiom:events:v1"`; required): The kind of the dataset
- `labelIds` (array of string; required): IDs of labels assigned to this dataset.
- `labelNames` (array of string; required): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`): Resolved labels assigned to this dataset.
- `mapFields` (array of string)
- `name` (string; required): Unique dataset name
- `reclaimableFields` (integer (int64)): Number of unused fields a vacuum can reclaim, when the dataset is a vacuum candidate
- `retentionDays` (integer): Number of days to retain data in the dataset
- `sharedByOrg` (string): ID of the org that shared this resource, if it's shared
- `updatedAt` (string (date-time); required): The RFC3339-formatted time when the dataset was last updated.
- `useRetentionPeriod` (boolean): Whether to use the retention period
- `vacuumCandidate` (boolean): Whether the dataset has unused fields that a vacuum can reclaim
- `who` (string; required): Name of the dataset creator
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
---
# Update field
Source: https://axiom.co/docs/restapi/endpoints/updateFieldForDataset
```http
PUT https://api.axiom.co/v2/datasets/{dataset_id}/fields/{field_id}
```
Updates the `unit`, `description`, and `hidden` settings of a field. All three are replaced, so omitted values are cleared. The `name` and `type` in the body are ignored.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_id` (path; string; required)
- `field_id` (path; string; required)
## Request body
Content type: `application/json` (required)
- `description` (string): Description of the field
- `hidden` (boolean): Whether the field is hidden
- `name` (string; required): Name of the field
- `type` (string; required): Type of the field
- `unit` (string): Unit of the field
## Responses
### 200: Updated field.
Content type: `application/json`
- `description` (string): Description of the field
- `hidden` (boolean): Whether the field is hidden
- `name` (string; required): Name of the field
- `type` (string; required): Type of the field
- `unit` (string): Unit of the field
### 400: A metrics dataset or a dataset managed by Axiom.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: The dataset doesn't exist or the field isn't in its schema.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
---
# Update group
Source: https://axiom.co/docs/restapi/endpoints/updateGroup
```http
PUT https://api.axiom.co/v2/rbac/groups/{id}
```
Replaces a group's name, description, roles, and members. Fields you omit are cleared, and members of managed groups aren't changed. Requires an Enterprise plan or the RBAC add-on.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Unique identifier of the group to update
## Request body
The group's new name, description, roles, and members
Content type: `application/json` (required)
Defines a group of users for organizational purposes
- `description` (string): Detailed description of the group's purpose and scope
- `isManaged` (boolean; read-only): Whether the group is synced from your identity provider. You can't delete a managed group or change its members.
- `members` (array of string): List of user IDs that are assigned to this group
- `name` (string; required): Unique name identifier for the group
- `roles` (array of string): IDs of the roles assigned to the group. Use a custom role ID or a built-in role ID: `axiom-owner`, `axiom-admin`, `axiom-user`, `axiom-read-only`, or `axiom-none`.
## Responses
### 200: The updated group.
Content type: `application/json`
Type: `GroupWithID`
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### GroupWithID
Extends the base Group type to include a unique identifier
All of the following:
- `Group`
- Object with:
- `id` (string; required): Unique identifier for the group
### Group
Defines a group of users for organizational purposes
Object.
- `description` (string): Detailed description of the group's purpose and scope
- `isManaged` (boolean; read-only): Whether the group is synced from your identity provider. You can't delete a managed group or change its members.
- `members` (array of string): List of user IDs that are assigned to this group
- `name` (string; required): Unique name identifier for the group
- `roles` (array of string): IDs of the roles assigned to the group. Use a custom role ID or a built-in role ID: `axiom-owner`, `axiom-admin`, `axiom-user`, `axiom-read-only`, or `axiom-none`.
---
# Update label
Source: https://axiom.co/docs/restapi/endpoints/updateLabel
```http
PUT https://api.axiom.co/v2/labels/{id}
```
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; pattern `^lbl_`; required)
## Request body
Content type: `application/json` (required)
- `color` (`LabelColor`)
- `description` (string; length ≤ 512; nullable)
- `name` (string; length 1–128; required)
## Responses
### 200: Updated label
Content type: `application/json`
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
- `resources_count` (`LabelResourcesCount`; required)
### 400: Invalid label ID or payload
### 404: Label not found
### 409: A label with this name already exists
## Schemas
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
### LabelResourcesCount
Object.
- `dashboards` (integer (int64); required)
- `datasets` (integer (int64); required)
- `monitors` (integer (int64); required)
- `notifiers` (integer (int64); required)
- `total` (integer (int64); required)
---
# Update list of map fields
Source: https://axiom.co/docs/restapi/endpoints/updateMapFields
```http
PUT https://api.axiom.co/v2/datasets/{dataset_id}/mapfields
```
Replaces the list of map fields in a dataset. Fields you leave out of the list stop being map fields. Not supported for metrics datasets.
In the body of the API request that you send to this endpoint, specify a list of field names:
* Fields you haven’t previously defined as map fields but include in the list become map fields.
* Fields you have previously defined as map fields and include in the list remain map fields.
* Fields you have previously defined as map fields but exclude from the list are removed.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_id` (path; string; required)
## Request body
A list of MapField-names
Content type: `application/json` (required)
Type: `MapFields`
## Responses
### 200: Map field names after the update.
Content type: `application/json`
Type: `MapFields`
### 400: Empty, invalid, or duplicate field name, or a metrics dataset.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### MapFields
A list of map field names
Type: array of string
---
# Update monitor
Source: https://axiom.co/docs/restapi/endpoints/updateMonitor
```http
PUT https://api.axiom.co/v2/monitors/{id}
```
Replaces a monitor's configuration with the request body, so omitted fields reset to their defaults. Axiom runs the new query once before saving, and the update clears the monitor's current alert state. `labelIds` replaces assignments when supplied; [] clears them. Omitted or null `labelIds` preserves assignments on updates and creates an unlabeled resource on creation. IDs must belong to existing labels in your organization and are validated before saving.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Monitor ID.
## Request body
Content type: `application/json` (required)
Type: `MonitorUpsertRequest`
## Responses
### 200: Updated monitor.
Content type: `application/json`
Type: `MonitorWithId`
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### MonitorUpsertRequest
All of the following:
- `Monitor`
- Object with:
- `labelIds` (array of string; items ≤ 500): Existing label IDs; replaces assignments when supplied, clears with [], and preserves them when omitted or null.
### MonitorWithId
Monitor configuration with its unique identifier
All of the following:
- `Monitor`
- Object with:
- `createdAt` (string (date-time)): Timestamp when the monitor was created
- `createdBy` (string): ID of the user who created the monitor
- `createdByAgent` (boolean): true when the MCP server created this monitor
- `datasets` (array of string): Dataset names referenced by the monitor query.
- `id` (string; required): Unique identifier for the monitor
- `labelIds` (array of string; required): IDs of labels assigned to this monitor.
- `labelNames` (array of string; required): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`): Resolved labels assigned to this monitor.
- `lastError` (string): Most recent error encountered while evaluating the monitor.
- `updatedAt` (string (date-time)): Timestamp when the monitor was last updated
### Monitor
Configuration for a monitoring rule. Monitors can be configured to:
- Check threshold values (e.g., CPU usage > 90%)
- Match specific events in logs
- Detect anomalies based on historical patterns
Each monitor runs on a specified interval and can trigger notifications through configured notifiers.
Object.
- `alertOnNoData` (boolean): Whether to alert when no data is received
- `aplQuery` (string): APL (Axiom Processing Language) query string used for monitoring.
This query defines what data to analyze and how to process it.
At least one of aplQuery or mplQuery must be provided.
- `backfillDays` (integer (int64)): NewValues monitors only. Before the first evaluation, the values the query returns over this many days are recorded as seen, so they do not alert. Must not exceed lookbackDays. 0 disables the backfill.
- `columnName` (string): Name of the column to monitor
- `compareDays` (number (int64); value ≤ 7): Number of days to compare for anomaly detection
- `description` (string): Detailed description of the monitor's purpose
- `disabled` (boolean): Whether the monitor is currently disabled
- `disabledUntil` (string (date-time); nullable): Timestamp until when the monitor should remain disabled
- `includeChart` (boolean): Whether to include a query chart in triggered notifications
- `intervalMinutes` (integer (int64); value ≥ 1): How frequently the monitor should run, in minutes.
Minimum value is 1 minute.
- `lookbackDays` (integer (int64); value ≥ 1): NewValues monitors only. A value counts as new when it was not seen in this many days.
- `mplQuery` (string): MPL (Metrics Processing Language) query string for metrics-based monitoring.
Use this as an alternative to aplQuery for metrics datasets.
At least one of aplQuery or mplQuery must be provided.
- `name` (string; required): Name of the monitor
- `notifierIds` (array of string): List of notifier IDs that will receive alerts.
Notifiers can be email, Slack, webhook endpoints, etc.
- `notifyByGroup` (boolean): Whether to group notifications
- `notifyEveryRun` (boolean): Whether to send notifications on every check
- `operator` (string; one of `"Below"`, `"BelowOrEqual"`, `"Above"`, `"AboveOrEqual"`, `"AboveOrBelow"`): Comparison operator for threshold checks:
- Below: Trigger when value < threshold
- BelowOrEqual: Trigger when value <= threshold
- Above: Trigger when value > threshold
- AboveOrEqual: Trigger when value >= threshold
- AboveOrBelow: Trigger when value is outside a range
- `rangeMinutes` (integer (int64); value ≥ 1): Time window to evaluate in each check, in minutes.
For example, "last 5 minutes of data"
- `resolvable` (boolean): Whether the alert can be manually resolved
- `secondDelay` (number (int64); value ≤ 86400): Number of seconds to move each run's query window into the past, so data that arrives late is included.
For example, with a value of 300, a run at 10:05 queries up to 10:00.
- `skipResolved` (boolean): Whether to skip resolved alerts
- `threshold` (number (double)): Threshold value for triggering the alert
- `tolerance` (number; value ≤ 100): Tolerance percentage for anomaly detection
- `trackedValue` (string): NewValues monitors only, and required for them. The column of the query result whose values are checked for new ones.
- `triggerAfterNPositiveResults` (number (int64)): Number of runs among the last `triggerFromNRuns` runs, including the current one, that must meet the trigger condition for the monitor to trigger.
The current run must always meet it.
For example, set both fields to 3 to trigger only after 3 consecutive runs meet the condition.
If unset or 0, the first run that meets the condition triggers.
Values above `triggerFromNRuns` are lowered to it when the monitor is saved.
Applies to Threshold and AnomalyDetection monitors.
- `triggerFromNRuns` (number (int64)): Number of most recent runs, including the current one, that the monitor looks at when deciding whether to trigger.
Has no effect unless `triggerAfterNPositiveResults` is also set.
Applies to Threshold and AnomalyDetection monitors.
- `type` (string; one of `"Threshold"`, `"MatchEvent"`, `"AnomalyDetection"`, `"NewValues"`; required): Type of monitoring check to perform:
- Threshold: Compares a numeric value against a threshold
- MatchEvent: Looks for specific events or patterns
- AnomalyDetection: Identifies unusual patterns based on historical data
- NewValues: Alerts when the trackedValue column of the query result holds a value not seen within lookbackDays. Each run queries the last rangeMinutes, which defaults to intervalMinutes and cannot be less. Sends one notification per new value.
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
---
# Update notifier
Source: https://axiom.co/docs/restapi/endpoints/updateNotifier
```http
PUT https://api.axiom.co/v2/notifiers/{id}
```
Replaces a notifier's name, channel `properties`, and `disabledUntil` with the request body, so omitted fields are cleared. `labelIds` replaces assignments when supplied; [] clears them. Omitted or null `labelIds` preserves assignments on updates and creates an unlabeled resource on creation. IDs must belong to existing labels in your organization and are validated before saving.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Notifier ID.
## Request body
Content type: `application/json` (required)
Type: `NotifierUpsertRequest`
## Responses
### 200: Updated notifier.
Content type: `application/json`
Type: `NotifierWithId`
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### NotifierUpsertRequest
All of the following:
- `Notifier`
- Object with:
- `labelIds` (array of string; items ≤ 500): Existing label IDs; replaces assignments when supplied, clears with [], and preserves them when omitted or null.
### NotifierWithId
Notifier configuration with its unique identifier
All of the following:
- `Notifier`
- Object with:
- `id` (string): Unique identifier for the notifier
- `labelIds` (array of string; required): IDs of labels assigned to this notifier.
- `labelNames` (array of string; required): Names of assigned labels, including with exclude=labels; [] when unassigned.
- `labels` (array of `Label`): Resolved labels assigned to this notifier.
### Notifier
Configuration for a notification channel. Notifiers can be configured for various services like:
- Slack
- Email
- PagerDuty
- OpsGenie
- Discord
- Microsoft Teams
- Custom Webhooks
- Cursor
- Claude Code
- Jira Service Management
Object.
- `createdAt` (string (date-time); read-only): Timestamp when the notifier was created
- `createdBy` (string; read-only): Email or ID of the user who created the notifier
- `createdByAgent` (boolean): true when the MCP server created this notifier
- `disabled` (boolean): Whether repeated delivery failures disabled the notifier. False when a user snoozed it with disabledUntil. Ignored on requests
- `disabledUntil` (string): ISO timestamp until which the notifier is disabled (null if enabled)
- `lastError` (string): The delivery error that disabled the notifier. Empty for email notifiers and when disabled is false. Ignored on requests
- `name` (string; required): Human-readable name for the notifier
- `properties` (`NotifierProperties`; required)
- `updatedAt` (string (date-time); read-only): Timestamp when the notifier was last updated
### Label
Object.
- `color` (`LabelColor`; required)
- `description` (string; nullable)
- `id` (string; required)
- `name` (string; required)
### NotifierProperties
Configuration options for different notification channels. Only one channel should be configured per notifier.
Object.
- `amp` (`AmpConfig`)
- `chatgptWorkspaceAgent` (`ChatGPTWorkspaceAgentConfig`)
- `claudeCode` (`ClaudeCodeConfig`)
- `cursor` (`CursorConfig`)
- `customWebhook` (`CustomNotifierConfig`)
- `discord` (`DiscordConfig`)
- `discordWebhook` (`DiscordWebhookConfig`)
- `email` (`EmailConfig`)
- `jiraServiceManagement` (`JiraServiceManagementConfig`)
- `microsoftTeams` (`MicrosoftTeamsConfig`)
- `opsgenie` (`OpsGenieConfig`)
- `pagerduty` (`PagerDutyConfig`)
- `slack` (`SlackConfig`)
- `webhook` (`WebhookConfig`)
### LabelColor
Object.
- `name` (string; one of `"red"`, `"coral"`, `"orange"`, `"amber"`, `"yellow"`, `"lime"`, `"green"`, `"teal"`, `"blue"`, `"iris"`, `"purple"`, `"pink"`; required)
- `type` (string; one of `"palette"`; required)
### AmpConfig
Amp Orb webhook. The receiving plugin must accept {"text": ""}.
Object.
- `webhookUrl` (string; required): Secret HTTPS URL from the Amp plugin createWebhook registration. Returned encrypted on reads; submit it unchanged to retain it on updates.
### ChatGPTWorkspaceAgentConfig
Published ChatGPT Workspace Agent API channel. Axiom sends {"input": ""}.
Object.
- `token` (string; required): ChatGPT access token with the Workspace Agents scope
- `triggerId` (string; required): API channel trigger ID beginning with agtch_
### ClaudeCodeConfig
Claude Code routine. Axiom sends a fixed text body when the monitor fires.
Object.
- `routineId` (string; required): Routine ID from a Claude Code API trigger
- `token` (string; required): Bearer token for the routine
### CursorConfig
Cursor automation webhook. Axiom sends a fixed context body when the monitor fires.
Object.
- `token` (string; required): Bearer token for the automation webhook
- `webhookUrl` (string; required): Automation webhook URL from a Cursor automation
### CustomNotifierConfig
Configuration for custom webhook notifications with flexible headers and body template.
Supports variable substitution in the body template using {{.Variable}} syntax.
Object.
- `body` (string; required): Template for the webhook body, supports variable substitution
- `headers` (map of string to string): HTTP headers to include in the request
- `secretHeaders` (map of string to string): Sensitive HTTP headers (tokens, keys) that should be masked in logs
- `url` (string; required): Custom webhook endpoint URL
### DiscordConfig
Configuration for Discord notifications using bot token
Object.
- `discordChannel` (string): Discord channel ID to send notifications
- `discordToken` (string): Discord bot token for authentication
- `messageTemplate` (`MessageTemplate`)
### DiscordWebhookConfig
Configuration for Discord notifications using webhooks
Object.
- `discordWebhookUrl` (string): Discord webhook URL
- `messageTemplate` (`MessageTemplate`)
### EmailConfig
Configuration for email notifications
Object.
- `emails` (array of string): List of email addresses to receive notifications
- `messageTemplate` (`MessageTemplate`)
### JiraServiceManagementConfig
Configuration for Jira Service Management Ops alerts using an API integration
Object.
- `apiKey` (string; required): API key of the Jira Service Management API integration
### MicrosoftTeamsConfig
Configuration for Microsoft Teams notifications
Object.
- `messageTemplate` (`MessageTemplate`)
- `microsoftTeamsUrl` (string): Microsoft Teams webhook URL
### OpsGenieConfig
Configuration for OpsGenie integration
Object.
- `apiKey` (string): OpsGenie API key for authentication
- `isEU` (boolean): Whether to use EU region endpoints
### PagerDutyConfig
Configuration for PagerDuty integration
Object.
- `routingKey` (string): PagerDuty integration key for routing alerts
- `token` (string): PagerDuty API token for additional functionality
### SlackConfig
Configuration for Slack notifications using incoming webhooks
Object.
- `messageTemplate` (`MessageTemplate`)
- `slackUrl` (string): Slack incoming webhook URL
### WebhookConfig
Configuration for simple webhook notifications
Object.
- `url` (string): Webhook endpoint URL
### MessageTemplate
Go templates that replace the title and body of the notifier's default message. An empty field keeps the default.
Variables include {{.Title}}, {{.Body}}, {{.Name}}, {{.Action}}, {{.Value}}, {{.Threshold}}, {{.Labels}}, {{.Groups}} and {{.MatchedEvent}}.
If a template fails when a notification is sent, the default message is sent and the delivery records the error.
Object.
- `body` (string): Template for the message body
- `title` (string): Template for the message title
---
# Update org
Source: https://axiom.co/docs/restapi/endpoints/updateOrg
```http
PUT https://api.axiom.co/v2/orgs/{id}
```
Renames an organization and returns the updated organization. Requires a personal access token (PAT) of an owner of the organization.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required)
## Request body
Content type: `application/json` (required)
- `name` (string; required)
## Responses
### 200: Updated organization.
Content type: `application/json`
- `defaultEdgeDeployment` (string)
- `firstFailedPayment` (string)
- `id` (string; required)
- `lastUsageSync` (string; required)
- `license` (`License`; required)
- `metaCreated` (string)
- `metaModified` (string)
- `metaVersion` (string)
- `name` (string; required)
- `paymentStatus` (string; one of `"na"`, `"failed"`, `"success"`, `"blocked"`; required)
- `plan` (string; one of `"personal"`, `"teamMonthlyAws"`, `"axiomCloud"`, `"teamPlus"`, `"enterprise"`, `"comped"`, `"accelerator"`; required)
- `planCreated` (string; required)
- `primaryEmail` (string; required)
- `role` (string)
### 400: Invalid name.
### 403: The user isn't an owner of the organization.
## Schemas
### License
Object.
- `apiRateLimitPerSecond` (integer (uint64); required)
- `billingPeriodEnd` (string (date-time); required)
- `billingPeriodStart` (string (date-time); required)
- `defaultEdgeDeployment` (string; required)
- `edgeDeployments` (array of string; required)
- `expiresAt` (string (date-time); nullable)
- `features` (map of string to boolean; required)
- `id` (string; required)
- `issuedAt` (string (date-time); required)
- `issuedTo` (string; required)
- `issuer` (string; required)
- `maxAuditWindowSeconds` (integer (uint64); required)
- `maxDatasets` (integer (uint64); required)
- `maxEndpoints` (integer (uint64); required)
- `maxFields` (integer (uint64); required)
- `maxMonitors` (integer (uint64); required)
- `maxQueryWindowSeconds` (integer (uint64); required)
- `maxUsers` (integer (uint64); required)
- `monthlyIngestGb` (integer (uint64); required)
- `monthlyQueryGbHours` (integer (uint64); required)
- `storageAllowanceGB` (integer (uint64))
- `tier` (string; one of `"personal"`, `"teamMonthlyAws"`, `"axiomCloud"`, `"teamPlus"`, `"enterprise"`, `"comped"`, `"accelerator"`; required)
- `validFrom` (string (date-time); required)
- `withAuths` (array of string; required)
---
# Update role
Source: https://axiom.co/docs/restapi/endpoints/updateRole
```http
PUT https://api.axiom.co/v2/rbac/roles/{id}
```
Replaces a custom role's name, description, and capabilities. Capabilities you omit are removed, and the `members` field is ignored. Requires an Enterprise plan or the RBAC add-on.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Unique identifier of the role to update
## Request body
The role's new name, description, and capabilities
Content type: `application/json` (required)
Defines a role and its associated permissions within the system
- `datasetCapabilities` (`roleDatasetCapabilities`)
- `description` (string): Detailed description of the role's purpose and scope
- `members` (array of string): IDs of users assigned this role directly. Returned in responses and ignored in requests. To assign a role to a user, use the Update user role endpoint.
- `name` (string; required): Unique name identifier for the role
- `orgCapabilities` (`roleOrgCapabilities`)
- `viewCapabilities` (`roleViewCapabilities`)
## Responses
### 200: The updated role.
Content type: `application/json`
Type: `RoleWithID`
### 400: Bad request
Content type: `application/json`
- `code` (string)
- `message` (string)
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
## Schemas
### roleDatasetCapabilities
Defines the available permissions for dataset operations
Type: map of string to object
### roleOrgCapabilities
Defines organization-wide permissions and capabilities
Object.
- `annotations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of annotations across the organization
- `apiTokens` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of API tokens for authentication
- `auditLog` (array of string; one of `"read"`): Controls access to organization audit logs
- `billing` (array of string; one of `"read"`, `"update"`): Controls access to billing information and settings
- `dashboards` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of organization dashboards
- `datasets` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of organization datasets
- `endpoints` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of API endpoints
- `integrations` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of third-party integrations
- `labels` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of labels
- `monitors` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of monitoring
- `notifiers` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of notification settings
- `rbac` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls access to role-based access control settings
- `sharedAccessKeys` (array of string; one of `"read"`, `"update"`): Controls the management of shared access keys
- `users` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls user management within the organization
- `views` (array of string; one of `"create"`, `"read"`, `"update"`, `"delete"`): Controls the management of data views
### roleViewCapabilities
Defines the available permissions for view operations
Type: map of string to object
### RoleWithID
Extends the base Role type to include a unique identifier
All of the following:
- `Role`
- Object with:
- `id` (string; required): Unique identifier for the role
### Role
Defines a role and its associated permissions within the system
Object.
- `datasetCapabilities` (`roleDatasetCapabilities`)
- `description` (string): Detailed description of the role's purpose and scope
- `members` (array of string): IDs of users assigned this role directly. Returned in responses and ignored in requests. To assign a role to a user, use the Update user role endpoint.
- `name` (string; required): Unique name identifier for the role
- `orgCapabilities` (`roleOrgCapabilities`)
- `viewCapabilities` (`roleViewCapabilities`)
---
# Update saved query
Source: https://axiom.co/docs/restapi/endpoints/updateStarred
```http
PUT https://api.axiom.co/v2/apl-starred-queries/{id}
```
Replaces the `name`, `dataset`, `query`, and `metadata` of a saved query. With a personal access token, you can only update queries you saved.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required)
## Request body
Content type: `application/json` (required)
- `dataset` (string)
- `kind` (string; one of `"apl"`; required)
- `metadata` (map of string to string; required)
- `name` (string; required)
- `query` (`APLRequestWithOptions`; required)
- `who` (string; required)
## Responses
### 200: Updated saved query.
Content type: `application/json`
Type: `StarredQueryWithId`
### 400: Missing `name`, or no `dataset` given and none found in `query.apl`.
### 401: The saved query belongs to another user.
### 403: You don't have permission to update saved queries on the current or new dataset.
### 404: Saved query not found.
## Schemas
### APLRequestWithOptions
Object.
- `apl` (string; required)
- `cursor` (string)
- `defaultLimit` (integer (int64))
- `defaultOrder` (array of `APLRequestWithOptionsDefaultOrder`)
- `endTime` (string)
- `includeCursor` (boolean)
- `includeCursorField` (boolean)
- `libraries` (array of string)
- `queryOptions` (`QueryOptions`)
- `startTime` (string)
- `variables` (object)
### StarredQueryWithId
All of the following:
- `StarredQuery`
- Object with:
- `id` (string; required)
### APLRequestWithOptionsDefaultOrder
Object.
- `desc` (boolean)
- `field` (string)
### QueryOptions
Object. Other fields aren't allowed.
- `disableCache` (boolean)
- `disableStats` (boolean)
- `disableTrace` (boolean)
- `maxDataPoints` (integer (int64))
- `maxSeries` (integer (int64))
- `noAggregation` (boolean)
- `noFill` (boolean)
- `noInterpolation` (boolean)
- `priority` (string; one of `"low"`, `"medium"`, `"high"`)
- `resolution` (string)
- `displayNull` (string; one of `"auto"`, `"null"`, `"span"`, `"zero"`, `""`): Controls how empty intervals are rendered in time series charts. `auto` infers from the query, `null` leaves gaps, `span` connects adjacent points, `zero` fills with zero.
- `overlayCharts` (string; one of `"true"`, `"false"`, `""`): When enabled, charts are overlaid on a single chart instead of stacked separately.
- `shownColumns` (string; length ≤ 10000)
- `timeSeriesVariant` (string; one of `"area"`, `"bars"`, `"line"`, `"lines"`, `""`)
- `timeSeriesView` (string; one of `"charts"`, `"resultsTable"`, `"charts|resultsTable"`, `""`)
### StarredQuery
Object.
- `dataset` (string)
- `kind` (string; one of `"apl"`; required)
- `metadata` (map of string to string; required)
- `name` (string; required)
- `query` (`APLRequestWithOptions`; required)
- `who` (string; required)
---
# Update user role
Source: https://axiom.co/docs/restapi/endpoints/updateUserRole
```http
PUT https://api.axiom.co/v2/users/{id}/role
```
Changes the role of a member of the organization and returns the updated user. You can't change your own role. Only owners using a personal access token (PAT) can assign `owner` or change an owner's role.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required)
## Request body
Content type: `application/json` (required)
Object representing a user's role update request
- `role` (string; required): Role identifier to assign to the user
## Responses
### 200: Updated user.
Content type: `application/json`
Represents a user in the system
- `email` (string; required): User's email address
- `id` (string; required): Unique identifier for the user
- `name` (string; required): User's full name
- `role` (`UserDetailsRole`; required)
### 403: Insufficient permissions, you tried to change your own role, or the caller isn't allowed to assign or change the `owner` role.
### 404: User or role not found.
## Schemas
### UserDetailsRole
Detailed information about a user's role
Object.
- `id` (string; required): Unique identifier for the role
- `name` (string; required): Human-readable name of the role
---
# Update view
Source: https://axiom.co/docs/restapi/endpoints/updateView
```http
PUT https://api.axiom.co/v2/views/{id}
```
Replaces the `aplQuery` and `description` of a view, identified by its name. Axiom ignores `name` and `datasets` in the body and derives `datasets` from the new query.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): Name of the view
## Request body
Content type: `application/json` (required)
- `aplQuery` (string; required): APL query that defines the view
- `datasets` (array of string): Datasets the view queries. Axiom derives this from `aplQuery` and ignores it in requests.
- `description` (string)
- `edgeDeployment` (string): Region of the source datasets; ignored in requests
- `edgeDeploymentUrl` (string): URL of the edge deployment; ignored in requests
- `name` (string; required): Name of the view. Use it as the view ID and to query the view like a dataset.
- `sharedByOrg` (string): ID of the org that shared this resource, if it's shared
- `sharedByOrgName` (string): The name of the org that shared this resource, if it's shared
## Responses
### 200: Updated view.
Content type: `application/json`
- `aplQuery` (string; required): APL query that defines the view
- `datasets` (array of string): Datasets the view queries. Axiom derives this from `aplQuery` and ignores it in requests.
- `description` (string)
- `edgeDeployment` (string): Region of the source datasets; ignored in requests
- `edgeDeploymentUrl` (string): URL of the edge deployment; ignored in requests
- `name` (string; required): Name of the view. Use it as the view ID and to query the view like a dataset.
- `sharedByOrg` (string): ID of the org that shared this resource, if it's shared
- `sharedByOrgName` (string): The name of the org that shared this resource, if it's shared
### 403: You don't have query access to the view's current or new datasets.
### 404: View not found.
---
# Update virtual field
Source: https://axiom.co/docs/restapi/endpoints/updateVirtualField
```http
PUT https://api.axiom.co/v2/vfields/{id}
```
Replaces all fields of a virtual field. Omitted optional fields are cleared. The ID doesn't change, even if you change `name` or `dataset`.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `id` (path; string; required): ID of the virtual field in the form `.`
## Request body
Content type: `application/json` (required)
- `dataset` (string; required)
- `description` (string)
- `expression` (string; required)
- `name` (string; required): Name of the virtual field. Use letters, digits, underscores, and hyphens, starting and ending with a letter or digit.
- `type` (string)
- `unit` (string)
## Responses
### 200: Updated virtual field.
Content type: `application/json`
Type: `VirtualFieldWithId`
### 400: Missing `dataset`, `name`, or `expression`, an invalid `name`, or an expression that doesn't parse.
### 403: You don't have permission to update virtual fields on the current or new dataset.
### 404: Virtual field not found.
## Schemas
### VirtualFieldWithId
All of the following:
- `VirtualField`
- Object with:
- `id` (string; required)
### VirtualField
Object.
- `dataset` (string; required)
- `description` (string)
- `expression` (string; required)
- `name` (string; required): Name of the virtual field. Use letters, digits, underscores, and hyphens, starting and ending with a letter or digit.
- `type` (string)
- `unit` (string)
---
# Vacuum dataset
Source: https://axiom.co/docs/restapi/endpoints/vacuumDataset
```http
POST https://api.axiom.co/v2/datasets/{dataset_id}/vacuum
```
Queues a job that rebuilds the field schema of a dataset from its stored events, removing fields that no longer occur in any event. Doesn't delete events. You can vacuum each dataset once per hour.
When the endpoint returns the status code 200, it means that the vacuuming request is queued. The vacuuming itself might take several hours to complete.
## Authentication
Authenticate using an API token or personal access token (PAT). Include the token as a Bearer token: `Authorization: Bearer `. For more information, see [Tokens](/reference/tokens).
## Parameters
- `dataset_id` (path; string; required)
## Responses
### 200: Vacuum job queued.
Content type: `application/json`
- `jobID` (string; required)
### 400: The dataset is a metrics dataset.
Content type: `application/json`
- `code` (integer): HTTP status code.
- `message` (string): Error message.
### 403: Forbidden
Content type: `application/json`
- `code` (string)
- `message` (string)
### 404: Not found
Content type: `application/json`
- `code` (string)
- `message` (string)
### 429: The dataset was vacuumed less than an hour ago. Retry after the time in `Retry-After`.
---
# Agent-created organizations
Source: https://axiom.co/docs/console/intelligence/agent-created-orgs
An AI agent can create a real, fully functional Axiom organization with a single unauthenticated HTTP request. The response includes an API token the agent can use immediately to create datasets, ingest and query data, and build dashboards and monitors.
The organization starts out temporary. A human follows the claim URL returned at provisioning time to take ownership and make the organization permanent, keeping everything the agent built. If nobody claims the organization within 24 hours, Axiom permanently deletes it together with all its data.
## Provision an organization [#provision-an-organization]
Send a POST request to `https://api.axiom.co/v2/orgs/provision`. The endpoint is public: no authentication header is required.
The request body is a JSON object. Both fields are optional, so the minimal valid body is `{}`.
| Field | Type | Description |
| :--------------- | :----- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | string | Optional display name for the organization. If omitted, Axiom generates a name like `Agent Org 3f2a91bc`. The owner can rename the organization after claiming it. |
| `edgeDeployment` | string | Optional [edge deployment](/reference/edge-deployments) where the organization stores its data. If omitted, the organization is created in the default edge deployment, `US East 1 (AWS)`. |
For example:
```bash
curl -X 'POST' 'https://api.axiom.co/v2/orgs/provision' \
-H 'Content-Type: application/json' \
-d '{ "name": "canary-experiments" }'
```
A successful request returns `200 OK` with a body like the following:
```json
{
"id": "canary-experiments-x7q2",
"name": "canary-experiments",
"defaultEdgeDeployment": "cloud.us-east-1.aws",
"expiresAt": "2026-07-17T09:14:07Z",
"claimUrl": "https://app.axiom.co/canary-experiments-x7q2/claim?token=a3d2f9c8-4b1e-4f6a-9c3d-8e7b2a1f0d4e",
"token": "xaat-8b4d2f0a-1c9e-4d7b-b3a5-6f2e8c1d9a70"
}
```
| Field | Description |
| :---------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | The organization ID. Use it in API routes that require an org ID. |
| `name` | The display name of the organization. |
| `defaultEdgeDeployment` | The edge deployment where the organization stores its data. |
| `expiresAt` | The time at which the organization is deleted if it hasn’t been claimed. This is 24 hours after provisioning. |
| `claimUrl` | The URL a human opens to take ownership of the organization. Surface this URL to the user. Treat it as a secret: anyone who opens it can claim the organization. |
| `token` | An API token with full permissions on the organization. Treat it as a secret. Use it as a Bearer token in the `Authorization` header of subsequent API requests. |
The API token and the claim URL are returned exactly once, in this response. They can never be retrieved again, by anyone. Store the token before doing anything else, and treat both values as secrets: the token grants full API access to the organization, and anyone who opens the claim URL can take ownership of it. If the token is lost, the organization and its data are inaccessible over the API until a human claims the organization and creates a new token.
## Work in the organization [#work-in-the-organization]
The organization is not a sandbox: it behaves like any other Axiom organization. Using the returned token, the agent can immediately:
* [Create datasets](/restapi/endpoints/createDataset)
* [Ingest data](/restapi/ingest)
* [Query data](/restapi/query)
* [Create dashboards](/restapi/endpoints/createDashboard)
* [Create monitors](/restapi/endpoints/createMonitor)
The acting identity inside the organization is a synthetic agent user that Axiom creates during provisioning. This user owns the organization until a human claims it.
## Claim the organization [#claim-the-organization]
To keep the organization beyond its 24-hour lifespan, a human must claim it:
1. Open the `claimUrl` from the provisioning response in a browser.
2. Sign in to Axiom. If you don’t have an Axiom account yet, one is created as part of the flow.
3. You become the owner of the organization and the organization becomes permanent.
Claiming keeps everything the agent built: datasets, ingested data, dashboards, monitors, and other configuration all carry over unchanged.
Claiming also has the following effects:
* The temporary markers are removed. The organization no longer expires and behaves like any other Axiom organization on the Personal plan.
* The throttled limits are lifted and the full [Personal plan limits](/reference/limits) apply.
* The synthetic agent user is removed. The API token issued at provisioning continues to work, so the agent keeps its API access. As the new owner, you can revoke it or create additional [API tokens](/reference/tokens) at any time.
Claim links are single-use: after an organization has been claimed, its claim URL is invalid.
## Limits for unclaimed organizations [#limits-for-unclaimed-organizations]
While an organization is unclaimed, reduced limits apply that are sized for its 24-hour lifespan:
* **Ingest and query:** The organization can ingest up to 10 GB of data and use up to 1 GB-hour of query compute during its 24-hour lifespan.
* **Notifiers:** Agents can create and configure monitors and notifiers, but notifiers are disabled: notifications aren’t delivered until the organization is claimed.
* **Provisioning:** An agent can create at most 3 organizations in a day.
Claiming the organization restores the full Personal plan allowances and enables notifiers.
## Expiry [#expiry]
If the organization isn’t claimed within 24 hours (see `expiresAt` in the provisioning response), Axiom deletes it: the organization, all datasets and ingested data, dashboards, monitors, the API token, and the synthetic agent user are permanently removed. Deleted organizations can’t be recovered.
## Error behavior [#error-behavior]
If provisioning returns `429 Too Many Requests`, you have exceeded the provisioning rate limit. Retry later with backoff, and don’t provision more than one organization for the same task.
For the full request and response schema, see the [API reference](/restapi/endpoints/provisionOrg).
---
# AI agents
Source: https://axiom.co/docs/console/intelligence/ai-agents-overview
Axiom provides two complementary approaches for integrating AI agents with your data: Axiom MCP Server and Axiom Skills. Both enable AI agents to query and analyze your Axiom data, but they differ in how they handle credentials, context, and capabilities.
If an agent doesn’t have an Axiom organization to work in yet, it can provision a temporary one itself and hand you a claim link later. For more information, see [Agent-created organizations](/console/intelligence/agent-created-orgs).
## Choose between Axiom MCP Server and Axiom Skills [#choose-between-axiom-mcp-server-and-axiom-skills]
| Aspect | Axiom MCP Server | Axiom Skills |
| ----------------------- | --------------------------------------------- | --------------------------------------------- |
| **Credential handling** | OAuth-based isolation—agents never see tokens | Requires configured API tokens |
| **Context usage** | Tool definitions loaded upfront | On-demand loading, lower context overhead |
| **Capabilities** | Curated, read-only operations | Flexible, extensible beyond curated tools |
| **Methodology** | Query execution only | Includes investigation methodology and memory |
| **Setup complexity** | Browser-based OAuth flow | Manual token configuration |
### When to use Axiom MCP Server [#when-to-use-axiom-mcp-server]
Consider [Axiom MCP Server](/console/intelligence/mcp-server) when:
* You want curated, read-only operations with no risk of destructive actions.
* You prefer OAuth-based credential isolation where agents never see tokens.
* You're comfortable with the context overhead MCP introduces when tool definitions are loaded upfront.
### When to use Axiom Skills [#when-to-use-axiom-skills]
Consider [Axiom Skills](/console/intelligence/skills) when:
* You want lower context usage and on-demand loading of capabilities.
* You need flexibility beyond the curated Axiom MCP Server tool set.
* You want structured investigation methodology alongside data access.
* You're comfortable configuring properly scoped tokens.
### Use both Axiom MCP Server and Axiom Skills [#use-both-axiom-mcp-server-and-axiom-skills]
Axiom Skills can complement Axiom MCP Server by providing investigation methodology, memory systems, and APL guidance without duplicating the query interface. Configure your agent to:
1. Use Axiom MCP Server for executing Axiom queries.
2. Use Axiom Skills for structured investigation methodology and learning from past incidents.
This approach gives you the security benefits of Axiom MCP Server's credential isolation while gaining the systematic debugging capabilities of Axiom Skills.
## Token hygiene for AI agents [#token-hygiene-for-ai-agents]
Proper token scoping is essential for secure AI agent integration.
The guidance below applies when you use Axiom Skills with direct API access.
You don't need to follow the guidance below for remote Axiom MCP Server. It uses OAuth for authentication and handles credential isolation automatically. The OAuth process creates appropriately scoped sessions that you can revoke at any time, and agents never see your tokens.
* [Create a new API token](/reference/tokens#api-tokens) specifically for the AI agent. This limits the blast radius if the token is compromised.
* Never use personal access tokens for AI agent use. Personal access tokens have full control over your Axiom account.
* Select only the minimum permissions needed for the agent to perform its tasks:
* Grant query permission on specific datasets the agent needs to access.
* Avoid ingest permissions unless explicitly required. If the agent needs to ingest data, scope the token to the specific datasets.
* Never grant delete, admin, or organization-level permissions.
* Set a short expiry for the token (hours or days rather than months).
* Set [query cost limits](/console/intelligence/query-cost-limits) on the token. A capped token bounds your worst-case query costs in advance, no matter how many queries the agent runs.
* Rotate tokens regularly as part of your security practices.
Query cost limits also cover the remote Axiom MCP Server: its OAuth sessions act as your user account, so limits on your roles cap what agents can spend on your behalf. For more information, see [Set query cost limits for AI agents](/console/intelligence/query-cost-limits).
## Get started [#get-started]
Connect AI agents to Axiom using the Model Context Protocol with OAuth-based credential isolation.
Give AI agents structured investigation capabilities with axiom-sre for hypothesis-driven debugging.
---
# Axiom MCP Server
Source: https://axiom.co/docs/console/intelligence/mcp-server
Axiom MCP Server is a [Model Context Protocol](https://modelcontextprotocol.io/) server implementation that enables AI agents to query your data using Axiom Processing Language (APL).
For guidance on when to use Axiom MCP Server and Axiom Skills, see [AI agents](/console/intelligence/ai-agents-overview).
For the full list of tools and prompts with example queries, see [MCP tools reference](/console/intelligence/mcp-server/tools).
If your agent doesn’t have an Axiom organization to work in yet, it can provision a temporary one itself and hand you a claim link later. For more information, see [Agent-created organizations](/console/intelligence/agent-created-orgs).
## Current capabilities [#current-capabilities]
### Tools and prompts [#tools-and-prompts]
Axiom MCP Server works with AI agents that support MCP. It exposes tools for querying data, exploring datasets and metrics, and managing dashboards, monitors, and notifiers, plus prebuilt prompts for common investigations. For the full list with example queries, see [MCP tools reference](/console/intelligence/mcp-server/tools).
## Setup [#setup]
Remote MCP with OAuth is the recommended setup for most use cases.
### Choose a region [#choose-a-region]
Axiom hosts the MCP Server in the US and in the EU:
| Region | Remote MCP URL |
| ------ | ----------------------------- |
| US | `https://mcp.axiom.co/mcp` |
| EU | `https://mcp.eu.axiom.co/mcp` |
Both MCP Servers work with every Axiom organization and use the same sign-in. Wherever your agent connects, each query runs in the [edge deployment](/reference/edge-deployments) that holds the dataset. The region determines where the MCP Server handles query results on their way to your agent:
* The US MCP Server handles query results in data centers worldwide.
* The EU MCP Server handles query results only in data centers in the EU.
If your datasets are in the `EU Central 1 (AWS)` edge deployment and query results must stay in the EU, use the EU MCP Server.
Both MCP Servers send sign-in and other requests that aren’t queries, such as listing datasets, fields, dashboards, and monitors, to Axiom’s US API.
The setup steps on this page use the US MCP Server. To use the EU MCP Server, replace `mcp.axiom.co` with `mcp.eu.axiom.co`.
### Install with add-mcp [#install-with-add-mcp]
Use the [`add-mcp`](https://add-mcp.com/docs/quickstart) CLI to add Axiom MCP Server to your coding agents:
```bash
npx -y add-mcp https://mcp.axiom.co/mcp -g
```
For the EU MCP Server:
```bash
npx -y add-mcp https://mcp.eu.axiom.co/mcp -g
```
Authenticate in your browser when the agent prompts you.
Optional flags:
* Omit `-g` to install for the current project only.
* Add `-y` to skip confirmation prompts.
* Target specific agents with `-a`, for example `-a cursor -a claude-code`.
### Quick setup [#quick-setup]
Choose your client to get its fastest setup path, or copy a setup prompt for your AI agent.
To have an AI agent set up Axiom MCP Server for you, give it the [setup prompt](https://axiom.co/docs/mcp/setup-prompt.md).
#### Claude Code
```bash
claude mcp add --transport http --scope user axiom https://mcp.axiom.co/mcp
```
In Claude Code, run `/mcp` and select **axiom** to sign in in your browser.
For more information, see the [Claude Code documentation](https://code.claude.com/docs/en/mcp).
#### Codex
```bash
codex mcp add axiom --url https://mcp.axiom.co/mcp
codex mcp login axiom
```
Sign in to Axiom in the browser window that the login command opens.
For more information, see the [Codex documentation](https://learn.chatgpt.com/docs/extend/mcp?surface=cli).
#### Gemini CLI
```bash
gemini mcp add --transport http --scope user axiom https://mcp.axiom.co/mcp
```
Gemini CLI opens your browser to sign in the first time it connects. To sign in again, run `/mcp auth axiom`.
Gemini CLI requires a paid Gemini API key or a Gemini Code Assist Standard or Enterprise license. On other plans, use Antigravity.
For more information, see the [Gemini CLI documentation](https://geminicli.com/docs/tools/mcp-server/).
#### Antigravity
Add the following to `~/.gemini/config/mcp_config.json`. Antigravity CLI and the Antigravity IDE both read this file.
```json
{
"mcpServers": {
"axiom": {
"serverUrl": "https://mcp.axiom.co/mcp"
}
}
}
```
Sign in to Axiom in your browser when Antigravity connects. In Antigravity CLI, run `/mcp` to check the connection.
For more information, see the [Antigravity documentation](https://antigravity.google/docs/mcp).
#### Copilot CLI
```bash
copilot mcp add --transport http axiom https://mcp.axiom.co/mcp
```
In Copilot CLI, run `/mcp auth axiom` to sign in in your browser.
For more information, see the [Copilot CLI documentation](https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/add-mcp-servers).
#### Amp
```bash
amp mcp add axiom https://mcp.axiom.co/mcp
```
Amp opens your browser to sign in the next time it starts.
For more information, see the [Amp documentation](https://ampcode.com/docs/customize/mcp).
#### fx
```bash
fx mcp add --transport http axiom https://mcp.axiom.co/mcp
fx mcp auth axiom
```
Sign in to Axiom in the browser window that the auth command opens.
For more information, see the [fx documentation](https://fx.sh/docs/capabilities/mcp).
#### OpenCode
Add the following to `~/.config/opencode/opencode.json`:
```json
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"axiom": {
"type": "remote",
"url": "https://mcp.axiom.co/mcp",
"enabled": true
}
}
}
```
Run `opencode mcp auth axiom` to sign in in your browser.
For more information, see the [OpenCode documentation](https://opencode.ai/docs/mcp-servers/).
#### Cursor
[Add to Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=axiom&config=eyJ1cmwiOiJodHRwczovL21jcC5heGlvbS5jby9tY3AifQ%3D%3D)
Add the following to `~/.cursor/mcp.json` for all projects, or to `.cursor/mcp.json` for one project:
```json
{
"mcpServers": {
"axiom": {
"url": "https://mcp.axiom.co/mcp"
}
}
}
```
Sign in to Axiom when Cursor prompts you.
To add Axiom MCP Server for your Cursor team, go to **Dashboard > Integrations & MCP** in Cursor, and then add the URL `https://mcp.axiom.co/mcp`. To make it available to Cursor cloud agents, also make it available by default on **Dashboard > Plugins**.
For more information, see the [Cursor documentation](https://cursor.com/docs/mcp).
#### VS Code
[Add to VS Code](vscode:mcp/install?%7B%22name%22%3A%22axiom%22%2C%22type%22%3A%22http%22%2C%22url%22%3A%22https%3A%2F%2Fmcp.axiom.co%2Fmcp%22%7D)
```bash
code --add-mcp '{"name":"axiom","type":"http","url":"https://mcp.axiom.co/mcp"}'
```
VS Code opens your browser to sign in the first time it starts the server.
For more information, see the [VS Code documentation](https://code.visualstudio.com/docs/agent-customization/mcp-servers).
#### Devin Desktop
```bash
devin mcp add -s user axiom https://mcp.axiom.co/mcp
```
Devin prompts you to sign in the first time it uses Axiom. To sign in sooner, run `devin mcp login axiom`.
Devin Desktop was formerly Windsurf.
For more information, see the [Devin Desktop documentation](https://docs.devin.ai/cli/extensibility/mcp/configuration).
#### Kiro
[Add to Kiro](https://kiro.dev/launch/mcp/add?name=axiom&config=%7B%22url%22%3A%22https%3A%2F%2Fmcp.axiom.co%2Fmcp%22%7D)
Add the following to `~/.kiro/settings/mcp.json`:
```json
{
"mcpServers": {
"axiom": {
"url": "https://mcp.axiom.co/mcp"
}
}
}
```
Kiro opens your browser to sign in when it connects.
For more information, see the [Kiro documentation](https://kiro.dev/docs/mcp/).
#### Zed
Run **zed: open settings file**, and then add the following:
```json
{
"context_servers": {
"axiom": {
"url": "https://mcp.axiom.co/mcp"
}
}
}
```
Zed prompts you to sign in when it connects.
For more information, see the [Zed documentation](https://zed.dev/docs/ai/mcp).
#### Warp
Go to **Settings > Agents > MCP servers**, click **+ Add**, and then paste the following:
```json
{
"Axiom": {
"url": "https://mcp.axiom.co/mcp"
}
}
```
Warp opens your browser to sign in when the server starts.
For more information, see the [Warp documentation](https://docs.warp.dev/agents/capabilities/mcp/).
#### Claude
[Add to Claude](https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=Axiom&connectorUrl=https%3A%2F%2Fmcp.axiom.co%2Fmcp)
1. Review the prefilled name and URL, and then confirm.
2. Click **Connect** and sign in to Axiom in your browser.
Custom connectors work on every Claude plan, including Free. On Team and Enterprise plans, an owner may need to add the connector first in **Organization settings > Connectors**.
For more information, see the [Claude documentation](https://support.claude.com/en/articles/11175166-getting-started-with-custom-connectors-using-remote-mcp).
#### ChatGPT
1. In ChatGPT, go to **Plugins**, click **+**, and then click **Add custom MCP server**.
2. In **Name**, enter `Axiom`. **Description** is optional.
3. Under **Connection**, select **Server URL**, and then enter `https://mcp.axiom.co/mcp`.
4. Leave **Authentication** set to **OAuth**, and then select the **I understand and want to continue** checkbox.
5. Click **Create as a plugin**, and then sign in to Axiom in your browser.
The **Axiom** plugin in ChatGPT’s plugin directory is an unrelated app. To connect Axiom, use the steps above.
For more information, see the [ChatGPT documentation](https://developers.openai.com/apps-sdk/deploy/connect-chatgpt).
#### Goose
[Add to Goose](goose://extension?url=https%3A%2F%2Fmcp.axiom.co%2Fmcp&type=streamable_http&id=axiom&name=Axiom&description=Query%20and%20analyze%20Axiom%20data%20with%20APL%20from%20your%20AI%20agent)
Sign in to Axiom when Goose prompts you.
For more information, see the [Goose documentation](https://goose-docs.ai/docs/getting-started/using-extensions/).
#### Other
```bash
npx -y add-mcp https://mcp.axiom.co/mcp -g
```
If your agent supports remote MCP over HTTP, add a server named `Axiom` with the URL `https://mcp.axiom.co/mcp`. If it doesn’t, use `mcp-remote`:
```json
{
"mcpServers": {
"axiom": {
"command": "npx",
"args": [
"-y",
"mcp-remote",
"https://mcp.axiom.co/mcp"
]
}
}
}
```
Sign in to Axiom in your browser when your agent prompts you.
Clients that only support the older HTTP+SSE transport can use `https://mcp.axiom.co/sse`.
For agents that can’t sign in through a browser, use header-based authentication below.
For more information, see the [Other documentation](https://add-mcp.com/docs/quickstart).
#### Header-based authentication [#header-based-authentication]
If your AI agent doesn’t support browser-based OAuth (for example, Agent Builder from OpenAI), authenticate with headers:
1. [Create a personal access token](/reference/tokens#personal-access-tokens-pat).
2. [Determine organization ID](/reference/tokens#determine-organization-id).
3. Configure your AI agent to use the [remote MCP URL](#choose-a-region) for your region, for example `https://mcp.axiom.co/mcp`.
4. Send these headers with each request:
* **Authorization:** `Bearer PERSONAL_ACCESS_TOKEN`
* **x-axiom-org-id:** `ORGANIZATION_ID`
Replace `PERSONAL_ACCESS_TOKEN` with the personal access token you have generated.
If your agent only supports the Authorization header, pass the organization ID as a URL parameter: `https://mcp.axiom.co/mcp?org-id=ORGANIZATION_ID`
## Token hygiene [#token-hygiene]
The remote MCP Server uses OAuth for authentication which handles credential isolation automatically. Agents never see your tokens. You can [revoke access](#revoke-access) at any time.
When you use [Axiom Skills](/console/intelligence/skills), you configure API tokens directly. For detailed guidance on secure token configuration, see [Token hygiene for AI agents](/console/intelligence/ai-agents-overview#token-hygiene-for-ai-agents).
## Limit query costs [#limit-query-costs]
Query cost limits let you cap the hourly and daily query costs of an AI agent so it can query your data autonomously without creating unexpected costs. With MCP Server, the agent acts as your user account through OAuth, so set query cost limits on your roles.
For more information, see [Set query cost limits for AI agents](/console/intelligence/query-cost-limits).
## Use MCP Server [#use-mcp-server]
After setup, ask your agent about your data. For example:
* “List datasets.”
* “List the fields in the dataset `logs`.”
* “Get the most common status codes in the last 30 minutes in the dataset `logs`.”
Optional: use the [prebuilt prompts](/console/intelligence/mcp-server/tools#prompts) in clients that support MCP prompts.
For more examples and the full tool list, see [MCP tools reference](/console/intelligence/mcp-server/tools).
## Revoke access [#revoke-access]
To revoke access:
1. In Axiom, go to **Settings > Profile**.
2. In the Sessions section, find the session where you authorized your AI client, and then click **Delete** on the right.
If you connected with the `mcp-remote` library, clear the `.mcp-auth` folder. On a Mac, the default path is `~/.mcp-auth`.
---
# Set query cost limits for AI agents
Source: https://axiom.co/docs/console/intelligence/query-cost-limits
Connecting an AI agent to Axiom is one of the most valuable things you can do with your data. Your datasets hold the context an agent needs to investigate an incident, verify a deploy, or answer questions about production with evidence rather than guesses — and capable agents query a lot, precisely because that context is so rich. Query cost limits give you the peace of mind to say yes to this: you give a token or a role an hourly and a daily query budget in dollars, and Axiom blocks further queries for that identity when the budget is spent, until the window resets.
With a capped token, you can let an agent work autonomously against your data and know your worst case in advance: an agent with a $1 hourly and $10 daily limit can never spend more than $10 per day on queries, no matter what it does.
Query cost limits are separate from your organization’s [monthly spending limit](/reference/usage-billing#spending-limit). The spending limit caps your whole organization’s bill; query cost limits cap the query costs of individual tokens and members.
## How query cost limits work [#how-query-cost-limits-work]
* Limits apply to **query costs**: the query compute (GB-hours) an identity uses, priced at your plan’s standard rate. Discounts such as tier pricing and credits aren’t factored in, so the tracked cost is approximate — but always on the high side: your actual query costs never exceed the limit. Ingest, storage, and other operations don’t count towards the limit and are never blocked by it.
* You can set an **hourly limit**, a **daily limit**, or both, in dollars. The hourly window resets at the top of each hour (UTC), and the daily window resets at midnight UTC.
* When an identity exceeds a limit, its query requests fail with HTTP status code `429` until the window resets. Other requests continue to work as normal.
* Limits are enforced on the [edge query endpoints](/restapi/endpoints/queryEdge). The legacy [Run APL query](/restapi/endpoints/queryApl) endpoint on `api.axiom.co` rejects all queries from identities with limits, so send API queries to the edge query endpoints.
You can set query cost limits on two kinds of identity:
* **API tokens.** The limit caps everything that authenticates with that token. Use token limits for agents that hold an API token: [Axiom Skills](/console/intelligence/skills), coding agents like Claude Code, and any script or SDK.
* **Roles.** The limit caps each member that holds the role, individually. A member’s queries count against their budget whether they query in the Axiom console, with a personal access token, or through an OAuth session such as the remote [Axiom MCP Server](/console/intelligence/mcp-server), because all of these act as the member. If a member holds several roles with limits, the strictest limit for each window applies.
## Give an agent a budget [#give-an-agent-a-budget]
The typical setup for an agent that connects with an API token:
1. Click **Settings > API tokens**, and then click **New API token**.
2. Create a dedicated token for the agent with the minimum permissions it needs. For more information, see [Token hygiene for AI agents](/console/intelligence/ai-agents-overview#token-hygiene-for-ai-agents).
3. In **Query cost limits**, enter an hourly limit, a daily limit, or both, in dollars.
4. Click **Create**, and then configure your agent with the new token.
The agent now queries freely within its budget. If it exhausts the budget, its queries fail with an error that states the limit and when it resets.
To add limits to an existing token, click **Settings > API tokens**, select the token, and then edit **Query cost limits**. The token page also shows live usage meters for each limit with a countdown to the next reset.
If your agents connect through the remote Axiom MCP Server, they authenticate with OAuth and act as your user account, so token limits don’t apply to them. Instead, set limits on a role you hold. Role limits cap everything you run as that member, including your own console queries.
## Set limits on a role [#set-limits-on-a-role]
To cap the query costs of each member that holds a role:
1. Click **Settings > Roles**, and then select the role.
2. In **Query cost limits**, click **Edit**.
3. Enter an hourly limit, a daily limit, or both, in dollars, and then save.
The limit applies to each member individually, not to the role as a group. For example, a $5 daily limit on a role with 10 members lets each member spend up to $5 per day.
Role limits work on both built-in and custom roles.
## Monitor usage against limits [#monitor-usage-against-limits]
* To see how much of its budget a token has used, click **Settings > API tokens**, and then select the token. The usage meters show current usage against each limit and when the window resets.
* To see usage across members, click **Settings > Users**. Members with limits show their current query usage.
* To see your own usage, go to your profile. The **Query usage** section shows your effective limits and current usage.
Axiom only tracks and displays usage for identities that have limits configured.
## What happens when a limit is reached [#what-happens-when-a-limit-is-reached]
When a token or member exceeds a limit, query requests return HTTP status code `429` with a `Retry-After` header that states the number of seconds until the window resets. The error message identifies which limit tripped, for example the token’s hourly limit or the member’s daily limit.
* Queries from that identity are blocked until the window resets. No action is needed: an hourly limit unblocks at the top of the next hour (UTC), a daily limit at midnight UTC.
* Other identities are unaffected. Other tokens, members, monitors, and dashboards keep querying as usual.
* Ingest and management operations from the limited identity keep working.
To unblock an identity before the window resets, raise or clear its limits. The change takes effect for new queries within moments.
---
# Skills for AI agents
Source: https://axiom.co/docs/console/intelligence/skills
Axiom Skills are instruction files that give AI coding agents specialized capabilities. Unlike [Axiom MCP Server](/console/intelligence/mcp-server), which provides a standardized protocol for tool discovery and execution, Axiom Skills work by embedding methodology and context directly into the agent's prompt.
For guidance on when to use Axiom Skills and Axiom MCP Server, see [AI agents](/console/intelligence/ai-agents-overview).
Axiom Skills are open-source and welcome your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/skills).
## Available skills [#available-skills]
Axiom provides the following skills:
Create and manage monitors and notifiers using the Axiom API
Design and build Axiom dashboards via API with chart types, APL patterns, and layouts
Analyze query patterns, find unused data, and build cost optimization dashboards
Expert SRE investigator for incidents and debugging with hypothesis-driven methodology
Translate Splunk SPL queries to Axiom APL for migrations
---
# Spotlight
Source: https://axiom.co/docs/console/intelligence/spotlight
Spotlight allows you to highlight a region of event data and automatically identify how it deviates from baseline across different fields. Instead of manually crafting queries to investigate anomalies, Spotlight analyzes every field in your data and presents the most significant differences through intelligent visualizations.
This page explains how Spotlight works in the Axiom Console. For more information about the `spotlight` APL function, see [spotlight](/apl/aggregation-function/spotlight).
Spotlight is particularly useful for:
* **Root cause analysis**: Quickly identify why certain traces are slower, errors are occurring, or performance is degraded.
* **Anomaly investigation**: Understand what makes problematic events different from normal baseline behavior.
* **Pattern discovery**: Spot trends and correlations in your data that might not be immediately obvious.
## How Spotlight works [#how-spotlight-works]
Spotlight compares two sets of events:
* **Comparison set**: The events you select by highlighting a region on a chart.
* **Baseline set**: All other events that contributed to the chart.
For each field present in your data, Spotlight does the following:
* Calculates the differences between the two sets and ranks them by significance.
* Displays the most interesting differences using visualizations that adapt to your data types.
* Gives an AI-generated summary that helps you interpret the visualizations.
## Use Spotlight [#use-spotlight]
### Start Spotlight analysis [#start-spotlight-analysis]
1. In the **Query** tab, create a query that produces a heatmap or time series chart.
2. On the chart, click and drag to select the region you want to investigate.
3. In the selection tooltip, click **Run Spotlight**.
Spotlight analyzes the selected events and displays the results in a new panel showing the most significant differences across all fields.
Alternatively, start Spotlight from a table view by right-clicking on the value you want to select and choosing **Run spotlight**.
### Interpret results [#interpret-results]
Spotlight displays results using two types of visualization, depending on your data:
* **Bar charts** for categorical fields (strings, booleans)
* Compares the proportion of events that have a given value for selected and baseline events.
* Useful for understanding differences in status codes, service names, or boolean flags.
* **Boxplots** for numeric fields (integers, floats, timespans) with many distinct values
* Shows the range of values in both comparison and baseline sets.
* Identifies the minimum, P25, P75, and maximum values.
* Useful for understanding differences in response times or other numeric quantities.
For each visualization, Axiom displays the proportion of selected and baseline events (where the field is present).
### Dig deeper [#dig-deeper]
To dig deeper, iteratively refine your Spotlight analysis or jump to a view of matching events.
1. **Filter and re-run**: Right-click specific values in the results and select **Re-run spotlight** to filter your data and run Spotlight again with a more focused scope.
2. **Show events**: Rick-click specific values in the results and select **Show events** to filter your data and see matching events.
## Spotlight limitations [#spotlight-limitations]
* **Custom attributes**: Currently, custom attributes in OTel spans aren’t included in the Spotlight results. Axiom will soon support custom attributes in Spotlight.
* **Complex queries**: Spotlight works well for queries with maximum one aggregation step. Complex queries with multiple aggregations aren’t supported.
## Example workflows [#example-workflows]
### Investigate slow traces [#investigate-slow-traces]
1. Create a heatmap of trace durations. For example, run the following query:
```kusto
['otel-demo-traces']
| summarize histogram(duration, 20) by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20histogram\(duration%2C%2020\)%20by%20bin_auto\(_time\)%22%7D)
2. Select the region showing the slowest traces.
3. Run Spotlight to see if slow traces are associated with specific endpoints, regions, or user segments.
### Understand error spikes [#understand-error-spikes]
1. Build a time series of error-level logs. For example, run the following query:
```kusto
['sample-http-logs']
| where status startswith "5"
| summarize count() by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20where%20status%20startswith%20'5'%20%7C%20summarize%20count\(\)%20by%20bin_auto\(_time\)%22%7D)
2. Select the time period where errors spiked.
3. Run Spotlight to identify if there’s anything different about the selected errors.
---
# Axiom for Splunk app commands
Source: https://axiom.co/docs/splunk/app/commands
The Axiom for Splunk app adds the following commands to SPL. Filtering, projection, and aggregation run inside Axiom. Splunk receives tabular rows and continues with normal SPL.
| Command | Use it for | Pipeline type |
| ----------------------------- | --------------------------------------------------------------- | ---------------------- |
| [`axdatasets`](#axdatasets) | List datasets visible to the configured Axiom token. | Generating |
| [`axfields`](#axfields) | List fields in one Axiom dataset. | Generating |
| [`axsample`](#axsample) | Fetch recent sample events without writing a query. | Generating |
| [`axsearch`](#axsearch) | Search one Axiom dataset with Splunk-like syntax. | Generating |
| [`axstats`](#axstats) | Push `stats`-style aggregations into Axiom. | Generating |
| [`axtimechart`](#axtimechart) | Push time-bucketed aggregations into Axiom. | Generating (reporting) |
| [`axlookup`](#axlookup) | Look up Axiom context and add fields to existing Splunk events. | Streaming |
| [`axquery`](#axquery) | Run raw APL for full control. | Generating |
Generating commands must be the first command in a Splunk search, so they start with a leading pipe. `axlookup` is a streaming command and appears later in an SPL pipeline, after a base Splunk search. `axtimechart` generates reporting output, so its results are a chartable table rather than events.
## Time ranges [#time-ranges]
Commands that query Axiom data use the Splunk dispatch time range by default. The Splunk time picker, saved search schedule, or dispatch `earliest` and `latest` values become the Axiom query window. A user who runs a search for **Last 15 minutes** gets the same 15-minute Axiom window without adding command-specific time arguments.
This applies to `axsample`, `axsearch`, `axstats`, `axtimechart`, `axlookup`, and `axquery`. `axdatasets` and `axfields` don’t query event time ranges.
Each boundary resolves independently:
| Boundary | First choice | Second choice | Default |
| -------- | ------------ | ------------- | ----------------------------- |
| Start | `startTime` | `earliest` | Splunk dispatch earliest time |
| End | `endTime` | `latest` | Splunk dispatch latest time |
If a boundary can’t be resolved, that side is omitted from the Axiom request. Splunk **All time** is treated as unbounded.
Use explicit options when the Axiom query window should differ from the current Splunk search range:
```spl
| axsearch dataset="http-logs" q="error" startTime="-24h" endTime="now" limit=100
```
Supported time inputs:
* RFC3339 UTC, such as `2026-07-02T12:00:00Z`
* Splunk-style relative time, such as `-15m`, `-24h`, `-7d@d`, `@d`, or `+1h`
* `now`
Relative inputs resolve on the Splunk search head at command runtime and are normalized to UTC before being sent to Axiom. If an exact boundary matters, use explicit RFC3339 UTC.
To inspect the resolved range without querying Axiom, use `explain=true` on `axsearch`, `axstats`, or `axtimechart`:
```spl
| axsearch dataset="http-logs" q="status>=500" explain=true
| table compiled_apl, startTime, endTime
```
## Splunk-like `q` syntax [#splunk-like-q-syntax]
`axsearch`, `axstats`, and `axtimechart` support a constrained Splunk-like `q` option that compiles to APL. Supported patterns include:
```spl
q="error timeout"
q="error OR timeout"
q="error NOT debug"
q="(error OR timeout) service=api"
q="status>=500"
q="service=checkout"
q="service!=checkout"
q="trace_id=*"
q="service IN (api, worker)"
q="service NOT IN (api, worker)"
q="message:timeout*"
```
Use the `where` option on `axsearch`, or use `axquery`, when you need an APL predicate outside this subset. To see the APL a `q` expression compiles to, add `explain=true`.
## Field conventions [#field-conventions]
Every command returns Axiom fields as real Splunk fields. You don’t need to append `| spath` to reach them:
```spl
| axsearch dataset="http-logs" limit=10
| table _time service.name severity_text body
```
* Nested Axiom objects are flattened to dotted field names, so `attributes.http.method` is addressable directly.
* Arrays arrive as Splunk multivalue fields.
* Commands other than `axtimechart` keep the original row in `_raw` as JSON, so the Events tab shows the underlying Axiom record.
* `axsample`, `axsearch`, `axstats`, and `axtimechart` add `axiom_dataset` to each returned event. `axlookup` adds `axiom_lookup_dataset` to enriched events.
`axlookup` output fields are prefixed and normalized to Splunk-friendly names. The default prefix is `axiom_`, and punctuation in Axiom field names becomes `_`:
| Axiom field | Default Splunk field |
| ------------------------------ | ------------------------------------ |
| `service.version` | `axiom_service_version` |
| `resource.k8s.deployment.name` | `axiom_resource_k8s_deployment_name` |
| `trace-id` | `axiom_trace_id` |
The app also ships Splunk workflow actions. When an event has `axiom_dataset` plus a supported field such as `trace_id`, `span_id`, `service`, or `service.name`, the event menu can launch a focused Axiom search for traces, spans, services, or Kubernetes deployments. The action preserves the current Splunk time range and opens the search in Axiom.
## Command reference [#command-reference]
### axdatasets [#axdatasets]
List datasets visible to the configured Axiom token.
```spl
| axdatasets
| table id, name, kind, retentionDays
| sort name
```
| Option | Required | Description |
| ----------- | -------- | --------------------------------------------------- |
| `tokenName` | No | Stored Axiom token name. Defaults to `axiom_token`. |
### axfields [#axfields]
List fields for one Axiom dataset.
```spl
| axfields dataset="http-logs"
| table name, type, unit
| sort name
```
| Option | Required | Description |
| ----------- | -------- | --------------------------------------------------- |
| `dataset` | Yes | Axiom dataset ID. |
| `tokenName` | No | Stored Axiom token name. Defaults to `axiom_token`. |
### axsample [#axsample]
Fetch recent events from one dataset without writing a query.
```spl
| axsample dataset="http-logs" fields="service,status,message" limit=20
```
| Option | Required | Description |
| -------------------------------------------- | -------- | ------------------------------------------------------------------- |
| `dataset` | Yes | Axiom dataset ID. |
| `limit` | No | Maximum sample events. Defaults to `20`. |
| `fields` | No | Comma-separated fields to keep. `_time` is preserved automatically. |
| `startTime`, `endTime`, `earliest`, `latest` | No | Time controls. See [Time ranges](#time-ranges). |
| `tokenName` | No | Stored Axiom token name. |
### axsearch [#axsearch]
Search one Axiom dataset and return event-shaped rows.
```spl
| axsearch dataset="http-logs" q="status>=500 service=checkout" fields="service,status,message" limit=100
```
| Option | Required | Description |
| -------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------- |
| `dataset` | Yes | Axiom dataset ID. |
| `q` | No | Splunk-like query expression compiled to APL. See [Splunk-like `q` syntax](#splunk-like-q-syntax). |
| `search` | No | Text search string compiled to APL `search`. |
| `where` | No | Raw APL predicate for structured filtering. |
| `fields` | No | Comma-separated fields to keep. `_time` is preserved automatically. |
| `sort` | No | APL sort expression. Defaults to `_time desc`. |
| `limit` | No | Maximum events returned. Defaults to `100`. |
| `explain` | No | Return compiled APL without querying Axiom. |
| `startTime`, `endTime`, `earliest`, `latest` | No | Time controls. See [Time ranges](#time-ranges). |
| `tokenName` | No | Stored Axiom token name. |
### axstats [#axstats]
Push grouped aggregations into Axiom.
```spl
| axstats dataset="http-logs" q="status>=500" stats="count as errors, avg(duration_ms) as avg_duration" by="service" limit=100
```
Supported aggregation functions:
* `count` or `count()`
* `sum(field)`
* `avg(field)`
* `min(field)` and `max(field)`
* `dcount(field)` or `dc(field)`
* `stdev(field)`
* `variance(field)`
* `percentile(field, pct)`, `perc(field, pct)`, or `p95(field)` style shorthand
Use `axquery` for APL aggregations outside this subset, such as conditional aggregations.
| Option | Required | Description |
| -------------------------------------------- | -------- | ----------------------------------------------------------------- |
| `dataset` | Yes | Axiom dataset ID. |
| `q` | No | Splunk-like query expression compiled to APL. |
| `stats` | No | Aggregation list. Defaults to `count`. |
| `by` | No | Comma-separated group-by fields. |
| `limit` | No | Maximum grouped rows when grouping with `by`. Defaults to `1000`. |
| `explain` | No | Return compiled APL without querying Axiom. |
| `startTime`, `endTime`, `earliest`, `latest` | No | Time controls. See [Time ranges](#time-ranges). |
| `tokenName` | No | Stored Axiom token name. |
### axtimechart [#axtimechart]
Push time-bucketed aggregations into Axiom and return a time series table.
This is a reporting command. The result is a stats table with `_time` plus the aggregation columns, so the Visualization tab works without further piping.
```spl
| axtimechart dataset="http-logs" q="status>=500" span=5m agg="count as errors" by="service" limit=1000
```
| Option | Required | Description |
| -------------------------------------------- | -------- | ------------------------------------------------------------------ |
| `dataset` | Yes | Axiom dataset ID. |
| `q` | No | Splunk-like query expression compiled to APL. |
| `agg` | No | Aggregation expression. Defaults to `count`. |
| `span` | No | Bucket width such as `30s`, `5m`, `1h`, or `1d`. Defaults to `1m`. |
| `by` | No | Optional split-by field. |
| `limit` | No | Maximum returned rows. Defaults to `10000`. |
| `explain` | No | Return compiled APL without querying Axiom. |
| `startTime`, `endTime`, `earliest`, `latest` | No | Time controls. See [Time ranges](#time-ranges). |
| `tokenName` | No | Stored Axiom token name. |
### axlookup [#axlookup]
Look up the latest matching context from Axiom and add selected fields to incoming Splunk events. It follows Splunk’s lookup mental model, but the backing source is an Axiom dataset rather than a Splunk lookup table.
```spl
index=main service=api
| axlookup dataset="deployments" on="service=service.name" fields="version,owner,team"
| table _time, service, axiom_version, axiom_owner, axiom_team
```
| Option | Required | Description |
| -------------------------------------------- | -------- | ---------------------------------------------------------------------------------------- |
| `dataset` | Yes | Axiom dataset used as the lookup source. |
| `on` | Yes | Join key as `field` or `splunkField=axiomField`. |
| `fields` | Yes | Comma-separated Axiom fields to add, or `*`. |
| `prefix` | No | Prefix for added fields. Defaults to `axiom_`. Added field names are normalized for SPL. |
| `overwrite` | No | Whether added fields may replace existing fields. Defaults to `false`. |
| `batchSize` | No | Distinct join values per Axiom query. Defaults to `250`, capped at `1000`. |
| `maxFields` | No | Maximum added fields with `fields=*`. Defaults to `50`. |
| `strict` | No | Whether Axiom failures fail the Splunk search. Defaults to `true`. |
| `startTime`, `endTime`, `earliest`, `latest` | No | Time controls for the Axiom lookup. See [Time ranges](#time-ranges). |
| `tokenName` | No | Stored Axiom token name. |
The time range controls the Axiom lookup dataset, not the already-returned Splunk events. By default, the same Splunk dispatch window applies to both. Override the lookup window when your context data lives outside the base search window.
### axquery [#axquery]
Run raw APL when you need full control of the Axiom query language.
```spl
| axquery apl="['http-logs'] | where status >= 500 | summarize errors=count() by service, bin(_time, 1h) | sort by _time asc"
| table _time, service, errors
```
| Option | Required | Description |
| -------------------------------------------- | -------- | ----------------------------------------------------------------------- |
| `apl` | Yes | Raw APL query. |
| `paginate` | No | `cursor` or `time`. Requires `\| sort by _time [asc\|desc]` in the APL. |
| `debug` | No | Enable detailed logs in Splunk’s `_internal` index. |
| `maxTime` | No | Maximum runtime in seconds. Defaults to `600`. |
| `startTime`, `endTime`, `earliest`, `latest` | No | Time controls. See [Time ranges](#time-ranges). |
| `tokenName` | No | Stored Axiom token name. |
Pagination notes:
* Without pagination, Axiom’s per-page limit applies.
* With pagination, put `| limit n` in the APL to cap total returned events.
* `paginate=cursor` uses Axiom cursors. `paginate=time` advances by `_time` and deduplicates rows.
For the APL language itself, see the [APL introduction](/apl/introduction) and the [Splunk SPL to APL cheat sheet](/apl/guides/splunk-cheat-sheet).
## Debug searches [#debug-searches]
For `axsearch`, `axstats`, and `axtimechart`, start with `explain=true`. It shows the generated APL and resolved time range without querying Axiom, which separates app syntax issues from Axiom query issues:
```spl
| axstats dataset="http-logs" q="status>=500" stats="count as errors" by="service" explain=true
| table compiled_apl, startTime, endTime
```
Use `debug=true` with `axquery` when you need detailed runtime logs, then inspect the latest run with the `axquery_latest` search macro:
```spl
`axquery_latest`
```
---
# Axiom for Splunk app examples
Source: https://axiom.co/docs/splunk/app/examples
These examples show common workflows with the Axiom for Splunk app. Each one pushes the expensive part of the search into Axiom, returns a focused result set, and uses normal SPL for presentation. Replace the dataset and field names with your own.
## Explore an unfamiliar dataset [#explore-an-unfamiliar-dataset]
Start with the discovery commands when you’re learning what a dataset contains:
```spl
| axdatasets
| table name, kind, retentionDays
| sort name
```
```spl
| axfields dataset="payments"
| table name, type, unit
| sort name
```
```spl
| axsample dataset="payments" limit=10 fields="customer_id,amount,status"
```
## Investigate errors [#investigate-errors]
Use `axsearch` for event searches where you want Splunk-like syntax and event-shaped rows back. The Splunk time picker controls the Axiom query window, so a search over **Last 60 minutes** queries the same hour in Axiom:
```spl
| axsearch dataset="payments" q="status=failed amount>1000" fields="customer_id,amount,status,reason" limit=500
| table _time, customer_id, amount, reason
```
The returned rows are real Splunk events, so everything downstream is normal SPL:
```spl
| axsearch dataset="http-logs" q="status>=500" fields="service,status,message" limit=1000
| rex field=message "timeout after (?\d+)ms"
| stats count by service, timeout_ms
```
## Aggregate at scale [#aggregate-at-scale]
Use `axstats` when the next thing you want is a grouped table. The aggregation runs inside Axiom, so it stays exact over any number of events and only the grouped rows cross into Splunk:
```spl
| axstats dataset="payments" q="status=failed" stats="count as failures, sum(amount) as failed_amount" by="reason"
| sort -failures
```
Combine multiple aggregations in one command:
```spl
| axstats dataset="http-logs" stats="count as requests, avg(duration_ms) as avg_ms, p95(duration_ms) as p95_ms" by="service"
| sort -requests
```
## Build dashboards and alerts [#build-dashboards-and-alerts]
Use `axtimechart` when the next thing you want is a time series. It’s a reporting command, so the Visualization tab works directly and the search drops into dashboard panels and alerts unchanged:
```spl
| axtimechart dataset="payments" q="status=failed" span=15m agg="count as failures" by="reason" limit=1000
```
In a saved search or alert, the schedule’s dispatch window becomes the Axiom query window, so an alert that runs every 5 minutes over the last 5 minutes queries exactly that window in Axiom.
## Enrich Splunk events with Axiom context [#enrich-splunk-events-with-axiom-context]
Use `axlookup` when the base events are already in Splunk and Axiom has useful context to look up. This example adds deployment metadata from an Axiom dataset to Splunk events:
```spl
index=main service=api
| axlookup dataset="deployments" on="service=service.name" fields="version,owner,team"
| table _time, service, axiom_version, axiom_owner, axiom_team
```
Added fields are prefixed with `axiom_` and normalized to Splunk-friendly names, so `service.version` becomes `axiom_service_version`. For the conventions, see [Field conventions](/splunk/app/commands#field-conventions).
## Reach for full APL [#reach-for-full-apl]
Use `axquery` when the command-specific surface isn’t enough. Any APL query works, including operators and functions that have no SPL equivalent:
```spl
| axquery apl="['http-logs'] | where status >= 500 | summarize errors=count() by service, bin(_time, 1h) | sort by _time asc"
| table _time, service, errors
```
Browse the [APL tutorial](/apl/tutorial) for query patterns you can adapt, and use the [Splunk SPL to APL cheat sheet](/apl/guides/splunk-cheat-sheet) to translate familiar SPL idioms.
---
# Install and configure the Axiom for Splunk app
Source: https://axiom.co/docs/splunk/app/setup
The Axiom for Splunk app adds a set of `ax` commands to SPL. With the app, Splunk users discover Axiom datasets, run Axiom-backed searches, push aggregations down into Axiom, look up Axiom context for Splunk events, and keep using normal SPL for the final shaping, dashboards, and alerts.
The app is a query bridge, not an index replication tool. Axiom remains the system that stores and queries Axiom datasets. Splunk remains the system where your team composes investigations, shapes results, and connects output to existing operational workflows.
## Prerequisites [#prerequisites]
* [Create an Axiom account](https://app.axiom.co/register).
* [Create an advanced API token in Axiom](/reference/tokens#create-advanced-api-token) with query permissions on the datasets you want to expose in Splunk.
* Splunk Enterprise 9.0 or later. The app supports Splunk 9 and Splunk 10.
Dataset visibility in Splunk comes from the token. Users of the app see and query exactly the datasets the configured token can read, so scope the token to the datasets you intend to share.
## Install the app [#install-the-app]
1. Install the [Axiom app from Splunkbase](https://splunkbase.splunk.com/app/9339) using Splunk Web, or download the package and install it from file.
2. In Splunk Web, open the Axiom app. On first use, Splunk redirects you to the app’s setup page.
3. Enter your Axiom API token. The app stores it securely in Splunk’s credential store, marks the app configured, and reloads.
The token is shared by users of the app on that Splunk instance. Use a token scoped to the datasets the whole team should see. To store additional credentials for specific use cases, save them under a different name and select them per search with the `tokenName` option.
## Verify the connection [#verify-the-connection]
List the datasets the token can access:
```spl
| axdatasets
| table name, kind, retentionDays
| sort name
```
If the table shows your datasets, the app is ready. Next, inspect the fields in a dataset and sample some events:
```spl
| axfields dataset="http-logs"
| table name, type, unit
| sort name
```
```spl
| axsample dataset="http-logs" fields="service,status,message" limit=20
```
## Run your first search [#run-your-first-search]
Search an Axiom dataset with Splunk-like syntax, then shape the results with normal SPL:
```spl
| axsearch dataset="http-logs" q="status>=500 service=checkout" fields="service,status,message" limit=100
| table _time, service, status, message
```
Aggregate inside Axiom and present in Splunk:
```spl
| axstats dataset="http-logs" q="status>=500" stats="count as errors" by="service" limit=100
| sort -errors
```
A good search pushes the expensive part into Axiom, returns a focused result set, and then uses SPL for presentation. For the full command surface, see [Commands](/splunk/app/commands). For worked examples, see [Examples](/splunk/app/examples).
## Troubleshoot setup [#troubleshoot-setup]
**No datasets appear.** Confirm setup saved the token, then verify the token can query at least one dataset. For more information, see [Tokens](/reference/tokens) and [Datasets](/reference/datasets).
**You need to replace the token.** Open the app’s setup page again and enter the new token. The old token stops being used immediately.
For help, visit [axiom.co/support](https://axiom.co/support) or email [support@axiom.co](mailto:support@axiom.co). Include the app version, the Splunk version, and the command you ran.
---
# Axiom Portal for Splunk examples
Source: https://axiom.co/docs/splunk/portal/examples
These examples use standard mode syntax, `index=federated:`, against a dataset of OpenTelemetry trace data. In transparent mode, drop the `federated:` prefix and use the dataset name directly. Adjust index and field names to your setup.
## First searches [#first-searches]
Raw events, newest first. Click any event to see the full record, and use the field sidebar to explore:
```spl
index=federated:otel-traces | head 20
```
Filters push down, so only matching events leave Axiom:
```spl
index=federated:otel-traces "service.name"=frontend kind=server | head 50
```
Note that dotted field names take double quotes in SPL, as on any Splunk index.
## Count at any scale [#count-at-any-scale]
Exact counts per service over millions of events, computed inside Axiom:
```spl
index=federated:otel-traces | stats count by "service.name" | sort - count
```
The classic top-N and rare patterns push down too:
```spl
index=federated:otel-traces | top 10 "service.name"
index=federated:otel-traces | rare kind
```
## Aggregations [#aggregations]
Any mix of aggregation functions in one `stats` command:
```spl
index=federated:otel-traces | stats dc("service.name") as services
index=federated:otel-traces | stats count avg(duration_ms) median(duration_ms) by kind
index=federated:otel-traces | stats first("service.name") last("service.name")
```
## Time series and dashboards [#time-series-and-dashboards]
`timechart` is computed Axiom-side, including the time bins, so dashboard panels backed by federated searches stay fast at any data volume:
```spl
index=federated:otel-traces | timechart count
index=federated:otel-traces | timechart span=1h count by kind
index=federated:otel-traces kind=server | timechart count
```
## Shape results on the search head [#shape-results-on-the-search-head]
Streaming commands run on the search head over the events Axiom returns, so familiar SPL shaping works unchanged:
```spl
index=federated:otel-traces | head 100 | eval svc='service.name' | stats count by svc
index=federated:otel-traces | head 100 | rex field=name "(?^\w+)" | top verb
index=federated:otel-traces | head 200 | dedup "service.name" | table "service.name"
```
## Use lookups against Axiom data [#use-lookups-against-axiom-data]
In transparent mode, CSV lookups that live on your Splunk search head are replicated to Axiom and joined there:
```spl
index=otel-traces | lookup kind_names kind OUTPUT kind_label | stats count by kind_label
```
This is the pattern that makes existing Splunk content work: the lookup table stays in Splunk, the events stay in Axiom, and the Portal joins them where the data is.
## Query data models with tstats [#query-data-models-with-tstats]
In transparent mode, data models queried with `tstats`, the pattern security content uses, are answered exactly from Axiom:
```spl
| tstats summariesonly=false count from datamodel=Web by Web.status
```
## Search OCSF security data [#search-ocsf-security-data]
To search OCSF security events stored in Axiom, including arrays such as `observables`, see [Search OCSF data from Splunk](/splunk/portal/ocsf).
## Inspect what happened [#inspect-what-happened]
On any federated search, click **Job**, and then select **Inspect Job**. The `axiom.*` entries in Execution costs show what happened on the Axiom side: events scanned, query time, and rows in and out. For pushed-down aggregations, the events-scanned count reflects the full scan Axiom performed, even though only a handful of result rows crossed the wire. For details, see [Monitor and troubleshoot](/splunk/portal/troubleshoot).
---
# View Axiom logs in Splunk Observability Cloud
Source: https://axiom.co/docs/splunk/portal/observability-cloud
Splunk Observability Cloud doesn't store logs. Its Log Observer feature reads logs from a Splunk platform search head through [Log Observer Connect](https://help.splunk.com/en/splunk-observability-cloud/manage-data/view-splunk-platform-logs/introduction-to-splunk-log-observer-connect): Observability Cloud connects to the search head's management port and runs ordinary searches against the indexes you select.
Because the Axiom Portal for Splunk makes Axiom datasets searchable as ordinary indexes in [transparent mode](/splunk/portal/set-up-transparent), this composes: point Log Observer Connect at a search head with a transparent-mode Portal provider, and Observability Cloud renders logs that live only in Axiom. The log list, the time histogram, and the field summaries in the Logs explorer are all served by searches that federate to Axiom.
This completes Splunk's own three-signals architecture — metrics and traces flow to Observability Cloud from the OpenTelemetry Collector as usual, and logs are correlated in from the Splunk platform — with Axiom as the log store. You keep the Observability Cloud experience and pay no Splunk log ingest. Spans stored in Axiom as events are searchable through the same connection, so trace-shaped data is browsable in the Logs explorer too.
## Prerequisites [#prerequisites]
* A Splunk Enterprise search head with the Portal registered as a [transparent mode provider](/splunk/portal/set-up-transparent), and admin access to it.
* Administrator access to a Splunk Observability Cloud organization that includes Log Observer Connect.
* Network access from Observability Cloud to the search head's management port (8089) over HTTPS. The search head needs a hostname reachable from Splunk's cloud and a TLS certificate you can provide during setup. Restrict access to [Splunk's published Log Observer Connect IP ranges](https://help.splunk.com/en/splunk-observability-cloud/manage-data/view-splunk-platform-logs/set-up-log-observer-connect-for-splunk-enterprise) where possible.
## Prepare the search head [#prepare-the-search-head]
Log Observer Connect discovers indexes from the search head's local index list, and transparent-mode datasets aren't in it. Create an empty local index for each Axiom dataset you want to expose, with the exact same name:
```bash
curl -u admin: -k https://:8089/services/data/indexes \
-d name=
```
Searches over these index names transparently merge the empty local index with the Axiom data, so everything Log Observer retrieves comes from Axiom.
Create a role for the Log Observer Connect service account:
* Import the `user` role.
* Allow exactly the stub indexes you created in the previous step.
* Add the `edit_tokens_own` capability. Observability Cloud authenticates once with the service account password and then mints Splunk authentication tokens, which requires this capability.
* Make sure `indexes_list_all` isn't selected.
* Set the user search job limit to at least 4 per concurrent Log Observer user. One Logs explorer interaction fans out several parallel searches.
Create a user with the role from the previous step and a strong password. This is the account you enter in the Observability Cloud connection wizard.
## Create the connection in Observability Cloud [#create-the-connection-in-observability-cloud]
In Splunk Observability Cloud, go to **Data Management**, and follow the guided onboarding for **Connect to Splunk Enterprise**, or go directly to **Logs Connections** and click **Add new connection**. Select **Splunk Enterprise**.
* For the service account username and password, enter the account you created on the search head.
* For the Splunk platform URL, enter the externally reachable management endpoint, for example `https://splunk.example.com:8089`. Any HTTPS port works if a proxy fronts the management port.
* For the certificate, upload or paste the PEM chain the endpoint serves.
Click **Save and Continue**. Observability Cloud validates the connection against the search head before proceeding.
Choose which Observability Cloud users can use the connection, then click **Save and Activate**.
Go to **Logs** and open the **Logs explorer**. Select an index you exposed, and filter, aggregate, and browse — the results are served from Axiom through the Portal.
After you create the organization's first Logs connection, the Logs explorer can render blank until your session picks up the new entitlement. If that happens, log out of Observability Cloud and log back in.
## Limitations [#limitations]
* Log Observer Connect reads event indexes. Metrics indexes aren't part of this path, and internal indexes (names starting with `_`) aren't supported by Log Observer Connect.
* Observability Cloud's APM and Infrastructure Monitoring have their own ingest and can't read from a federated provider. Use the OpenTelemetry Collector to send those signals to Observability Cloud directly, and keep full-fidelity logs — and optionally traces — in Axiom.
* Every active Log Observer user runs several concurrent searches through the search head and the Portal. Size the service role's search job limit accordingly.
---
# Search OCSF data as Splunk CIM
Source: https://axiom.co/docs/splunk/portal/ocsf-cim
Security teams in Splunk build on the [Common Information Model](https://help.splunk.com/en/splunk-enterprise-security-8/common-information-model/8.5/introduction/overview-of-the-splunk-common-information-model) (CIM): data models such as Authentication and Network\_Traffic, `tstats` searches over them, and the Enterprise Security (ES) detections built on both. OCSF data uses different field names for the same ideas. For example, CIM’s `user` is OCSF’s `user.name` in a logon, and CIM’s `action` comes from `status_id` in a logon or from `action_id` in network traffic.
The Axiom Portal for Splunk bridges the two at read time. It presents an [OCSF dataset in Axiom](/use-cases/ocsf) as a second Splunk index whose events carry CIM field names and values. Nothing is copied or rewritten in Axiom. This page covers the last step of the OCSF flow: searching OCSF data from Splunk.
Searching OCSF data as CIM requires transparent mode and the [Axiom for Splunk app](/splunk/app/setup) 1.4.0 or later on the search head. It maps the OCSF classes and CIM data models listed on this page.
## How it works [#how-it-works]
Three pieces work together:
* **Two indexes for one dataset.** For every Axiom dataset that looks like OCSF, the Portal advertises two indexes. `index=ocsf` shows the native OCSF fields. `index=cim_ocsf` points at the same dataset and adds CIM fields to every event. A dataset looks like OCSF when its `class_uid` field is an integer and it has at least one of `metadata.version`, `category_uid`, `type_uid`, `activity_id`, or `severity_id`.
* **CIM fields computed in Axiom.** When you search a `cim_` index, the Portal computes the CIM fields inside the Axiom query, before filtering and aggregation. Filters such as `action=failure` and aggregations such as `stats count by user` therefore run in Axiom, like any other pushed-down search.
* **Eventtypes and tags on the search head.** CIM data models find events by tag, for example `tag=authentication`. A set of eventtypes selects OCSF events by `class_uid` and attaches the CIM tags. In transparent mode, the search head expands tags into `class_uid` constraints before it sends the search to the Portal.
### Class-aware mapping [#class-aware-mapping]
The same CIM field comes from different OCSF fields depending on the event class. The Portal reads the `*_id` enumerations first and falls back to their string siblings. For example:
| CIM field | Authentication (`3002`) | Network Activity (`4001`) | Process Activity (`1007`) |
| ---------- | --------------------------------------------------------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------ |
| `action` | `success` or `failure`, from `status_id` | `allowed` or `blocked`, from `action_id`, then `disposition_id` | `allowed` or `blocked`, from `action_id`, then `disposition_id` |
| `user` | The account that logged on, `user.name` | The acting account, `actor.user.name` | The acting account, `actor.user.name` |
| `dest` | The system logged on to, `dst_endpoint.ip` or `dst_endpoint.hostname` | The remote peer, `dst_endpoint.ip` or `dst_endpoint.hostname` | The device the event happened on, `device.hostname` or `device.ip` |
| `src` | `src_endpoint.ip` or `src_endpoint.hostname` | `src_endpoint.ip` or `src_endpoint.hostname` | `src_endpoint.ip` or `src_endpoint.hostname` |
| `severity` | Lowercase CIM severity from `severity_id` | Lowercase CIM severity from `severity_id` | Lowercase CIM severity from `severity_id` |
For example, here is a failed logon from the [OCSF for Axiom sample data](/use-cases/ocsf/query#filter-on-promoted-columns) in the two indexes:
| OCSF field in `index=ocsf` | Value | CIM field in `index=cim_ocsf` | Value |
| -------------------------- | ------------------------------------ | ----------------------------- | ------------------------------------ |
| `status_id` | `2` | `action` | `failure` |
| `user.name` | `heidi` | `user` | `heidi` |
| `user.domain` | `CORP` | `dest_nt_domain` | `CORP` |
| `src_endpoint.ip` | `10.24.111.174` | `src` | `10.24.111.174` |
| `dst_endpoint.hostname` | `dc01.corp.example.com` | `dest` | `dc01.corp.example.com` |
| `auth_protocol` | `Kerberos` | `authentication_method` | `Kerberos` |
| `status_detail` | `Unknown user name or bad password.` | `reason` | `Unknown user name or bad password.` |
| `severity_id` | `3` | `severity` | `medium` |
Events in `index=cim_ocsf` keep their OCSF fields as well, so you can mix both vocabularies in one search. Where OCSF and CIM share a field name, such as `action`, `status`, and `severity`, the `cim_` index shows the CIM value for the classes the mapping covers and the native OCSF value for the others.
The mapping reads only the typed columns of the dataset. Attributes stored under the `unmapped` map field don’t become CIM fields. Arrays of objects become multivalue CIM fields: `cve` from `vulnerabilities`, `file_hash` from `file.hashes`, `process_hash` from `process.file.hashes`, `answer` from `answers`, and `mitre_technique_id` from `attacks`. `cvss` is the first CVSS base score of the first vulnerability only.
## Supported data models [#supported-data-models]
| CIM data model | OCSF classes | Tags |
| ------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------ |
| Authentication | Authentication (`3002`), logon activity (`activity_id=1`) only | `authentication` |
| Network\_Traffic | Network Activity (`4001`) | `network`, `communicate` |
| Network\_Resolution | DNS Activity (`4003`) | `network`, `resolution`, `dns` |
| Network\_Sessions | DHCP Activity (`4004`) | `network`, `session`, `dhcp` |
| Web | HTTP Activity (`4002`) | `web` |
| Email | Email Activity (`4009`) | `email` |
| `Endpoint.Processes` | Process Activity (`1007`) | `process`, `report` |
| `Endpoint.Filesystem` | File System Activity (`1001`) | `endpoint`, `filesystem` |
| `Endpoint.Registry` | Registry Key Activity (`201001`), Registry Value Activity (`201002`) | `endpoint`, `registry` |
| `Endpoint.Services` | Windows Service Activity (`201004`) | `service`, `report` |
| Change, including Account\_Management | Account Change (`3001`), User Access Management (`3005`), Group Management (`3006`) | `change`, `account` |
| Change | Entity Management (`3004`), Scheduled Job Activity (`1006`), API Activity (`6003`) | `change` |
| Change, auditing changes | Event Log Activity (`1008`) | `change`, `audit` |
| Intrusion\_Detection and Alerts | Detection Finding (`2004`), Security Finding (`2001`) | `ids`, `attack`, `alert` |
| Vulnerabilities | Vulnerability Finding (`2002`) | `report`, `vulnerability` |
| Data\_Loss\_Prevention | Data Security Finding (`2006`) | `dlp`, `incident` |
Data models without an OCSF source, such as Risk, Certificates, Updates, and the inventory data models, return no OCSF events. OCSF classes not listed in the table keep their native fields in the `cim_` index and match no CIM data model.
## Requirements [#requirements]
* A Splunk Enterprise 9.2 or later search head.
* The Portal registered as a [transparent mode provider](/splunk/portal/set-up-transparent), with the search head’s knowledge objects turned on. Standard mode doesn’t expand tags or send data model definitions, so the CIM mapping doesn’t work with it.
* The [Axiom for Splunk app](/splunk/app/setup) 1.4.0 or later on the search head. It provides the eventtypes and tags that connect OCSF classes to CIM data models.
* The [Splunk Common Information Model add-on](https://splunkbase.splunk.com/app/1621) (`Splunk_SA_CIM`) on the search head. Enterprise Security includes it.
* An OCSF dataset in Axiom that follows the [Axiom OCSF schema](/use-cases/ocsf#the-axiom-ocsf-schema). For more information, see [Send OCSF data to Axiom](/use-cases/ocsf/send-data).
* A dataset name that Splunk accepts as an index name: lowercase letters, digits, underscores, and hyphens, starting with a letter or digit. The `cim_` prefix is reserved, so the Portal can’t search a dataset whose own name starts with `cim_` as a native index.
## Set up OCSF as CIM [#set-up-ocsf-as-cim]
These steps use a dataset named `ocsf`. Replace it with the name of your dataset.
On the search head, install or upgrade the [Axiom for Splunk app](https://splunkbase.splunk.com/app/9339) to 1.4.0 or later from Splunkbase. Complete the app’s setup page, then restart Splunk. For more information, see [Set up the Axiom for Splunk app](/splunk/app/setup). The app ships eventtypes that select OCSF events by `class_uid` and tags them for the CIM data models in [Supported data models](#supported-data-models). They’re shared with every app on the search head, including Splunk\_SA\_CIM and Enterprise Security.
The `cim_` index appears automatically once the dataset contains OCSF data. Search it with a tag to confirm that tags expand and CIM fields are present:
```spl
index=cim_ocsf tag=authentication | stats count by action, user
```
If `cim_ocsf` isn’t found, check that the dataset name meets the [requirements](#requirements) and that it contains OCSF events. The Portal checks a dataset again within 15 minutes after it last found no OCSF data, or within 2 minutes if the dataset was empty.
Every Splunk\_SA\_CIM data model starts its constraint with an index macro, such as `` `cim_Network_Traffic_indexes` ``. By default the macro matches every index but names none. The Portal needs a concrete `cim_` index in the constraint to know which Axiom dataset to search, so set the macro of each data model you use to one OCSF dataset index:
| Data model | Macro |
| -------------------- | --------------------------------- |
| Alerts | `cim_Alerts_indexes` |
| Authentication | `cim_Authentication_indexes` |
| Change | `cim_Change_indexes` |
| Data Loss Prevention | `cim_DLP_indexes` |
| Email | `cim_Email_indexes` |
| Endpoint | `cim_Endpoint_indexes` |
| Intrusion Detection | `cim_Intrusion_Detection_indexes` |
| Network Resolution | `cim_Network_Resolution_indexes` |
| Network Sessions | `cim_Network_Sessions_indexes` |
| Network Traffic | `cim_Network_Traffic_indexes` |
| Vulnerabilities | `cim_Vulnerabilities_indexes` |
| Web | `cim_Web_indexes` |
Set each macro to one concrete index, such as `(index=cim_ocsf)`. Don’t use a pattern such as `index=cim_*`: it stops working as soon as the Portal advertises more than one OCSF dataset, and the search returns an error that names the matching indexes. If a data model already lists local Splunk indexes, keep them and add the `cim_` index with `OR`, for example `(index=firewall OR index=cim_ocsf)`.
Set the macros in one of the following ways:
* **Splunk Web:** Go to **Apps > Manage Apps**, and then click **Set up** for Splunk Common Information Model. Alternatively, use the CIM Setup page in Enterprise Security. Select each data model and enter the index.
* **Configuration file:** Add the macros to `$SPLUNK_HOME/etc/apps/Splunk_SA_CIM/local/macros.conf`, then reload macros or restart Splunk:
```ini
[cim_Network_Traffic_indexes]
definition = (index=cim_ocsf)
[cim_Authentication_indexes]
definition = (index=cim_ocsf)
```
* **REST API:** Set all twelve macros at once. Replace the index, host, and credentials:
```bash
IDX='(index=cim_ocsf)'
for m in Alerts Authentication Change DLP Email Endpoint Intrusion_Detection \
Network_Resolution Network_Sessions Network_Traffic Vulnerabilities Web; do
curl -sk -u admin: \
"https://localhost:8089/servicesNS/nobody/Splunk_SA_CIM/configs/conf-macros/cim_${m}_indexes" \
--data-urlencode "definition=${IDX}" -o /dev/null -w "cim_${m}_indexes %{http_code}\n"
done
```
Searches with `index=cim_ocsf` and a tag work without this step. Data model searches, including `tstats` and ES and ESCU detections, need it.
```spl
| tstats count from datamodel=Authentication by Authentication.action
```
A count by `success` and `failure` confirms the full path: tags, data model, Portal mapping, and aggregation in Axiom.
## Example searches [#example-searches]
Failed logons by user and source, in the native OCSF vocabulary:
```spl
index=ocsf class_uid=3002 activity_id=1 status_id=2
| stats count by "user.name", "src_endpoint.ip"
```
The same question in CIM vocabulary:
```spl
index=cim_ocsf tag=authentication action=failure
| stats count by user, src
```
As a data model search, the form that ES and ES Content Update (ESCU) detections use:
```spl
| tstats count from datamodel=Authentication
where Authentication.action=failure
by Authentication.user, Authentication.src
```
Blocked network traffic and bytes by destination:
```spl
| tstats count sum(All_Traffic.bytes) from datamodel=Network_Traffic
where All_Traffic.action=blocked
by All_Traffic.dest
```
Accelerated data model searches with `summariesonly=true`, the default in ESCU detections, return the same results as unaccelerated ones:
```spl
| tstats summariesonly=true count from datamodel=Network_Traffic by All_Traffic.action
```
An ESCU-style process search with first and last seen times:
```spl
| tstats summariesonly=true count min(_time) as firstTime max(_time) as lastTime
from datamodel=Endpoint.Processes
where Processes.process_name=powershell.exe
by Processes.dest Processes.user Processes.process_name
```
Vulnerabilities with their CVE IDs, a multivalue field from the `vulnerabilities` array:
```spl
index=cim_ocsf tag=report tag=vulnerability cve=*
| table cve, cvss, severity, signature
```
MITRE ATT\&CK techniques in detection findings, from the `attacks` array:
```spl
index=cim_ocsf tag=ids tag=attack mitre_technique_id=*
| stats count by mitre_technique_id, signature, dest
```
## Data model acceleration [#data-model-acceleration]
ES and ESCU detections run `| tstats summariesonly=true … from datamodel=…`. Against a `cim_` index, `summariesonly=true` and `summariesonly=false` return the same complete result, but not because Splunk reads acceleration summaries:
* Splunk builds no tsidx summary for Axiom data. The periodic summary-building searches Splunk sends to the Portal return nothing for `cim_` indexes.
* For a `summariesonly=true` search, the Portal takes the data model definition that Splunk sends with the search and runs the equivalent aggregation live in Axiom.
* Results cover the full time range of the search with no summary lag. Each detection run is a live Axiom query, so its cost and duration follow the time range and data volume rather than a pre-built summary.
You don’t need to change ES data model acceleration settings or use `summariesonly=false`. You do need to [scope the index macros](#set-up-ocsf-as-cim).
## Limitations [#limitations]
* **Transparent mode only.** Standard mode doesn’t expand tags or send data model definitions.
* **Not every CIM field is populated.** The Portal fills a CIM field only when the dataset has an OCSF source for it. Fields without a source are empty.
* **`unmapped` isn’t mapped.** Attributes stored under the `unmapped` map field don’t become CIM fields.
* **Authentication covers logons only.** The Authentication eventtype selects `activity_id=1`. Other Authentication activities, such as logoffs, stay out of the data model.
* **Index patterns must match one index.** An index pattern such as `index=cim_*`, for example in a data model macro, must match exactly one index. If it matches several, the search returns an error that names them. Name the concrete `cim_` index instead.
* **Asset and identity exports aren’t supported.** The Axiom for Splunk app includes two scheduled searches that export ES asset and identity lists from OCSF data. They’re turned off by default and aren’t supported in this release. Leave them turned off.
* **Enterprise Security.** OCSF as CIM has been tested with Splunk Enterprise Security. In addition, the Portal’s translation of data model searches is checked against a large set of ES, ESCU, and community detection search shapes. That check confirms that the searches run against Axiom. It doesn’t confirm that every detection returns the results you expect on your data, so validate the detections you rely on. ES features that depend on other configuration, such as asset and identity lookups, need their usual setup in ES.
* **One index per data model search.** A data model search that spans more than one `cim_` index returns an error.
## What’s next [#whats-next]
* [Query OCSF data with APL](/use-cases/ocsf/query)
* [Set up transparent mode](/splunk/portal/set-up-transparent)
* [SPL command support](/splunk/portal/spl-support#transparent-mode-knowledge-objects)
---
# Search OCSF data from Splunk
Source: https://axiom.co/docs/splunk/portal/ocsf
An [OCSF dataset in Axiom](/use-cases/ocsf) is an ordinary Axiom dataset, so both Splunk integrations search it like any other dataset. Analysts search OCSF events with SPL from the Splunk interface they already know, and pushed-down filters and aggregations run inside Axiom. This page covers the last step of the OCSF flow: searching OCSF data from Splunk.
The examples on this page use a dataset named `ocsf` that contains events conformed to the [Axiom OCSF schema](/use-cases/ocsf#the-axiom-ocsf-schema). Replace `ocsf` with the name of your dataset.
In transparent mode, the Portal can also present an OCSF dataset as Splunk CIM data for CIM data models, `tstats`, and Enterprise Security searches. For more information, see [Search OCSF data as Splunk CIM](/splunk/portal/ocsf-cim).
## Search OCSF data with the Portal [#search-ocsf-data-with-the-portal]
Through the [Axiom Portal for Splunk](/splunk/portal/overview), the OCSF dataset is an index like any other: `index=federated:ocsf` in standard mode, or `index=ocsf` in transparent mode. The following examples use transparent mode.
Events carry the native OCSF fields under their dotted names, such as `class_uid`, `user.name`, and `src_endpoint.ip`. Dotted field names take double quotes in SPL, as on any Splunk index. In `where` and `eval` expressions, use single quotes instead, for example `'user.name'`.
Count events by OCSF class:
```spl
index=ocsf | stats count by class_uid, class_name
```
Failed logons by user and source address. In the Authentication class (`3002`), `activity_id` `1` is a logon and `status_id` `2` is a failure:
```spl
index=ocsf class_uid=3002 activity_id=1 status_id=2
| stats count by "user.name", "src_endpoint.ip"
| sort - count
```
Bytes by destination for network traffic over time:
```spl
index=ocsf class_uid=4001
| timechart span=1h sum("traffic.bytes") by "dst_endpoint.ip"
```
Filters and aggregations like these are computed inside Axiom. For the full list of what runs in Axiom and what runs on the search head, see [SPL command support](/splunk/portal/spl-support).
As with any OCSF query, filter on the numeric `*_id` fields rather than their display strings. The IDs are fixed by OCSF, while producers spell the strings differently.
### Arrays of objects [#arrays-of-objects]
Promoted arrays of objects, such as `observables`, `attacks`, and `vulnerabilities`, arrive as one field that contains the array as compact JSON. Arrays of scalar values, such as `email.to`, arrive as ordinary Splunk multivalue fields.
To work with the elements of an array of objects, extract them with `spath`. `spath` returns a multivalue field, which you can expand with `mvexpand`. For example, list the IP address observables in Detection Findings (`2004`):
```spl
index=ocsf class_uid=2004
| spath input=_raw path=observables{}.value output=observable
| mvexpand observable
| stats count by observable
```
`spath` and `mvexpand` run on the search head over the events Axiom returns, so filter the search first, for example by `class_uid`, to keep the number of events small. A search-time filter on an element, such as `observables{}.value=192.0.2.145`, matches nothing, because the field only exists after `spath` runs. Filter after `spath` instead:
```spl
index=ocsf class_uid=2004
| spath input=_raw path=observables{}.value output=observable
| search observable="192.0.2.145"
| table _time, "device.hostname", "finding_info.title", observable
```
### Fields in `unmapped` [#fields-in-unmapped]
Fields stored under the [`unmapped` map field](/use-cases/ocsf#the-axiom-ocsf-schema) appear in events as dotted fields that start with `unmapped.`, for example `unmapped.device.os.name`. You can use them in the base search like any other field. Filters, `stats ... by`, `top`, and `timechart` on them run inside Axiom:
```spl
index=ocsf class_uid=3002 "unmapped.device.os.name"="Windows Server 2022"
| stats count by "user.name"
```
```spl
index=ocsf class_uid=3002
| stats count by "unmapped.device.os.name"
```
Base-search filters and aggregations work for paths up to 8 segments below `unmapped`. For example, `unmapped.device.os.name` is 3 segments below `unmapped`. For a deeper path, the search returns an error instead of results. Extract deeper fields with `spath` instead:
```spl
index=ocsf class_uid=2004
| spath input=_raw path=unmapped.PATH output=deep_field
| stats count by deep_field
```
Replace `PATH` with the path of the field below `unmapped`. `spath` runs on the search head over the events Axiom returns, so narrow the base search first, for example by `class_uid` and time range.
An array inside `unmapped`, such as `unmapped.evidences`, behaves like a [promoted array of objects](#arrays-of-objects): you can’t filter or aggregate on its elements in the base search. To read its elements, extract them with `spath`:
```spl
index=ocsf class_uid=2004
| spath input=_raw path=unmapped.evidences{}.process.name output=evidence_process
| stats count by evidence_process
```
## Search OCSF data with the Axiom app [#search-ocsf-data-with-the-axiom-app]
The [Axiom for Splunk app](/splunk/app/setup) queries the dataset by name with its `ax` commands, and returns OCSF fields as Splunk fields.
In version 1.2.0 and later, the app names array fields the same way Splunk’s `spath` command does, so you don’t need `spath` for arrays:
* Nested objects become dotted field names, for example `src_endpoint.ip`.
* An array of scalar values becomes a multivalue field whose name ends in `{}`, for example `email.to{}`.
* Each attribute of an array of objects becomes a multivalue field named `{}.`, for example `observables{}.value`, `attacks{}.technique.uid`, and `unmapped.evidences{}.process.name`.
Failed logons, using the `q` syntax:
```spl
| axstats dataset="ocsf" q="class_uid=3002 activity_id=1 status_id=2" stats="count" by="user.name,src_endpoint.ip"
```
MITRE ATT\&CK techniques in recent Detection Findings:
```spl
| axsearch dataset="ocsf" q="class_uid=2004" limit=1000
| stats count by "attacks{}.technique.uid", "device.hostname"
```
`axsearch` returns at most `limit` events, and `stats` runs on the search head over them, so these counts cover only the returned events.
For exact counts over the whole dataset, and for the full APL language, including map fields and arrays, run an APL query with `axquery`:
```spl
| axquery apl="['ocsf'] | where class_uid == 2004 | mv-expand observables | where toint(observables['type_id']) == 2 | summarize count() by ip = tostring(observables['value'])"
```
For more information, see [Commands](/splunk/app/commands).
## Choose between the Portal and the app [#choose-between-the-portal-and-the-app]
| | Axiom Portal for Splunk | Axiom for Splunk app |
| ------------------------------------------ | ----------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| Address the dataset | `index=ocsf`, or `index=federated:ocsf` in standard mode | `dataset="ocsf"` in an `ax` command |
| Arrays of objects such as `observables` | One JSON field. Extract elements with `spath` | Multivalue fields such as `observables{}.value` |
| Arrays of scalar values such as `email.to` | Multivalue field `email.to` | Multivalue field `email.to{}` |
| Nested fields under `unmapped` | Dotted fields. Filter and aggregate in the base search, up to 8 segments below `unmapped` | Dotted fields. Filter inside Axiom with APL in `axquery` |
| Full APL, including map fields | No | Yes, with `axquery` |
For a general comparison of the two integrations, see [Axiom and Splunk](/splunk/overview).
## What’s next [#whats-next]
* [Search OCSF data as Splunk CIM](/splunk/portal/ocsf-cim)
* [Query OCSF data with APL](/use-cases/ocsf/query)
* [SPL command support](/splunk/portal/spl-support)
* [Axiom for Splunk app commands](/splunk/app/commands)
---
# How the Axiom Portal for Splunk works
Source: https://axiom.co/docs/splunk/portal/overview
The Axiom Portal for Splunk makes Axiom datasets appear as ordinary Splunk indexes. Anyone who knows SPL, or just knows how to click around Splunk dashboards, can search petabyte-scale Axiom data from their existing Splunk search head, live and with exact results.
The Portal implements the remote side of Splunk’s federated search protocol, the same protocol Splunk uses between its own deployments. Your Splunk search head registers the Portal as a federated provider and treats it like a remote Splunk peer. The Portal translates the dispatched work into Axiom queries, runs them inside Axiom, and streams results back in Splunk’s native result format. No data is copied into Splunk, and nothing is installed on the search head.
A Portal is an Axiom integration that speaks another tool’s own remote-data protocol, so Axiom appears natively inside that tool. The Portal for Splunk is the first of the family.
## Where the work happens [#where-the-work-happens]
The defining feature of the Portal is **pushdown**: the expensive parts of a search run inside Axiom, next to the data.
* **Pushed down to Axiom.** Filters, projections, and aggregations are translated and computed inside Axiom. A `stats count` over a billion events scans the data in Axiom and returns a handful of rows to Splunk. Pushed-down aggregations are exact at any dataset size, not sampled, and include `stats`, `timechart`, `chart`, `top`, `rare`, and `tstats`.
* **Run on the search head.** Streaming and transforming commands like `eval`, `rex`, `dedup`, and `transaction` run on the Splunk search head over the events Axiom returns, identical to how Splunk works with its own remote peers. Everything behaves like native SPL because it is native SPL.
This split means the Splunk search head’s limits stop mattering for anything except raw event retrieval. Aggregation results are effectively unbounded because they’re computed in Axiom. For the exact command-by-command breakdown, see [SPL command support](/splunk/portal/spl-support).
The Portal never degrades results silently. Whenever a result is trimmed or estimated, the search shows a WARN or INFO banner explaining what happened, and per-search Axiom metrics appear in Splunk’s Job Inspector. For details, see [Monitor and troubleshoot](/splunk/portal/troubleshoot).
## Two modes [#two-modes]
Splunk federated search has two modes, and the Portal supports both.
**Standard mode** maps each Axiom dataset to a federated index that users address as `index=federated:`. It’s explicit, simple to reason about, and the recommended starting point. Each dataset you expose is mapped once by a Splunk admin.
**Transparent mode** makes Axiom datasets directly addressable by their own names, as `index=`, with zero per-dataset mapping. Splunk also replicates the search head’s knowledge bundle to Axiom, so your existing CSV lookups, automatic lookups, and data models work against Axiom data. Transparent mode works from Splunk Enterprise and Splunk Cloud Platform on the Victoria Experience.
| | Standard mode | Transparent mode |
| ------------------------------- | ------------------------------------------- | ----------------------------------------------------------------- |
| Index syntax | `index=federated:http-logs` | `index=http-logs` |
| Per-dataset setup | One federated index per dataset | None |
| Splunk lookups over Axiom data | No | Yes, CSV and automatic lookups |
| Data models and `tstats` | Limited | Yes |
| Machine Learning Toolkit (MLTK) | Yes | Yes |
| Splunk Enterprise Security | Not supported by Splunk | Supported |
| Splunk editions | Splunk Enterprise and Splunk Cloud Platform | Splunk Enterprise and Splunk Cloud Platform (Victoria Experience) |
If you store security data in Axiom in OCSF format, transparent mode also presents it as Splunk CIM data, so CIM data models, `tstats`, and Enterprise Security detections run against it. For more information, see [Search OCSF data as Splunk CIM](/splunk/portal/ocsf-cim).
If you use Splunk Enterprise Security, choose transparent mode. Splunk doesn’t support federated search in standard mode with Enterprise Security. For more information, see [Use federated searches in transparent mode with Splunk Enterprise Security](https://help.splunk.com/en/splunk-enterprise-security-8/user-guide/8.5/introduction/use-federated-searches-in-transparent-mode-with-splunk-enterprise-security) in the Splunk documentation.
Use one mode per Splunk deployment. Registering both a standard and a transparent provider against the same Portal endpoint yields inconsistent results. This is a general caveat of Splunk federated search, not specific to Axiom.
## Supported Splunk versions [#supported-splunk-versions]
Axiom verifies the Portal against Splunk Enterprise 9.0 through 10.4 in both modes. Splunk Enterprise 9.0 or later is recommended.
The Portal supports Splunk Cloud Platform on the Victoria Experience, which all new Splunk Cloud instances use, in both modes. To check which experience your environment uses, see [Determine your Splunk Cloud Platform Experience](https://help.splunk.com/en/splunk-cloud-platform/administer/admin-manual/10.5.2605/get-started-managing-splunk-cloud-platform/determine-your-splunk-cloud-platform-experience) in the Splunk documentation.
## Security model [#security-model]
* The connection is always initiated by your Splunk search head over HTTPS. The Portal never connects into your network.
* Splunk authenticates with an Axiom API token that needs only query permissions on the datasets you choose to expose. Reads only, no ingest or management access.
* Revoking the token immediately removes Splunk’s access. For more information, see [Tokens](/reference/tokens).
## What’s next [#whats-next]
* [Set up standard mode](/splunk/portal/set-up-standard)
* [Set up transparent mode](/splunk/portal/set-up-transparent)
* [SPL command support](/splunk/portal/spl-support)
* [Examples](/splunk/portal/examples)
* [Search OCSF data from Splunk](/splunk/portal/ocsf)
---
# Set up the Axiom Portal for Splunk in standard mode
Source: https://axiom.co/docs/splunk/portal/set-up-standard
In standard mode, each Axiom dataset you expose is mapped to a Splunk federated index, and users search it as `index=federated:`. Standard mode is explicit, simple to reason about, and the recommended starting point. For how the modes differ, see [How the Portal works](/splunk/portal/overview).
If you use Splunk Enterprise Security, [set up transparent mode](/splunk/portal/set-up-transparent) instead. Splunk doesn’t support federated search in standard mode with Enterprise Security.
## Prerequisites [#prerequisites]
* [Create an advanced API token in Axiom](/reference/tokens#create-advanced-api-token) with query permissions on the datasets you want to expose. The token needs no other permissions.
* [Determine your Axiom organization ID](/reference/tokens#determine-organization-id).
* A Splunk Enterprise 9.0 or later search head, or Splunk Cloud Platform on the Victoria Experience, and a Splunk role with permissions to manage federated search. The search head must be able to reach `splunk.portal.axiom.co` on port 443 over HTTPS. If your Splunk Cloud environment restricts outbound traffic, allow egress to this host and port first.
The dataset scope of the token defines what Splunk can see. Splunk users can only search datasets the token can query, and revoking the token removes access immediately.
## Register the Portal as a federated provider [#register-the-portal-as-a-federated-provider]
In Splunk Web, go to **Settings**, and then select **Federated search**.
Click **Add federated provider** and fill in the fields:
* For the provider mode, select **Standard**.
* Enter a provider name, for example `axiom`.
* For the remote host, enter `splunk.portal.axiom.co:443`.
* For the service account username, enter your Axiom organization ID.
* For the service account password, enter your Axiom API token.
Click **Test connection**, and then save the provider.
The service account password is the token value itself, the string starting with `xaat-`, not the token’s name in the Axiom UI. A mistyped or expired token can still pass **Test connection**, because the connection test verifies the protocol handshake without running a query. The verification search below is the real credential check.
## Map datasets as federated indexes [#map-datasets-as-federated-indexes]
Create one federated index for each Axiom dataset you want to expose:
In Splunk Web, go to **Settings**, select **Federated search**, and then click **Add federated index**.
Fill in the fields:
* Enter a federated index name, for example `http-logs`. This becomes the name users search: `index=federated:http-logs`.
* Select the federated provider you created.
* For the remote dataset, enter the Axiom dataset name. Datasets the token can query are listed for autocomplete.
Repeat for each dataset. When you add datasets in Axiom later, map them the same way.
## Verify the setup [#verify-the-setup]
Run a search that queries Axiom:
```spl
index=federated:http-logs | stats count
```
An exact event count confirms that authentication, dataset mapping, and query pushdown all work. Then try a raw event search:
```spl
index=federated:http-logs | head 20
```
If either search shows an error banner, see [Monitor and troubleshoot](/splunk/portal/troubleshoot).
## What’s next [#whats-next]
* [SPL command support](/splunk/portal/spl-support)
* [Examples](/splunk/portal/examples)
* Want your Splunk lookups and data models to work against Axiom data? [Set up transparent mode](/splunk/portal/set-up-transparent).
---
# Set up the Axiom Portal for Splunk in transparent mode
Source: https://axiom.co/docs/splunk/portal/set-up-transparent
In transparent mode, Axiom datasets are directly addressable by their own names, as `index=`, with no per-dataset mapping. Splunk also replicates the search head’s knowledge bundle to Axiom, so your existing knowledge objects work against Axiom data:
* **CSV lookups**, both explicit `| lookup` and automatic lookups defined in props.
* **Data models**, including `tstats` queries and `pivot`.
* **Tags and event types**, which the search head expands before dispatch.
Transparent mode works from a Splunk Enterprise search head or Splunk Cloud Platform on the Victoria Experience. For how the modes differ, see [How the Portal works](/splunk/portal/overview).
If you use Splunk Enterprise Security, transparent mode is the mode to use: Splunk doesn’t support standard mode federated search with Enterprise Security.
Use one mode per Splunk deployment. If you already registered a standard mode provider for the Portal, remove it before setting up transparent mode. Registering both modes against the same endpoint yields inconsistent results.
## Prerequisites [#prerequisites]
* [Create an advanced API token in Axiom](/reference/tokens#create-advanced-api-token) with query permissions on the datasets you want to expose. The token needs no other permissions.
* [Determine your Axiom organization ID](/reference/tokens#determine-organization-id).
* A Splunk Enterprise 9.0 or later search head, or Splunk Cloud Platform on the Victoria Experience, and a Splunk role with permissions to manage federated search. The search head must be able to reach `splunk.portal.axiom.co` on port 443 over HTTPS. If your Splunk Cloud environment restricts outbound traffic, allow egress to this host and port first.
## Register the Portal as a transparent mode provider [#register-the-portal-as-a-transparent-mode-provider]
In Splunk Web, go to **Settings**, and then select **Federated search**.
Click **Add federated provider** and fill in the fields:
* For the provider mode, select **Transparent**.
* Enter a provider name, for example `axiom`.
* For the remote host, enter `splunk.portal.axiom.co:443`.
* For the service account username, enter your Axiom organization ID.
* For the service account password, enter your Axiom API token.
* Turn on the use of the search head’s knowledge objects for this provider.
Click **Test connection**, and then save the provider.
The service account password is the token value itself, the string starting with `xaat-`, not the token’s name in the Axiom UI. A mistyped or expired token can still pass **Test connection**, because the connection test verifies the protocol handshake without running a query. The verification search below is the real credential check.
There are no federated indexes to create. Every dataset the token can query is immediately searchable by its Axiom dataset name.
## Knowledge bundle replication [#knowledge-bundle-replication]
After you save the provider, Splunk automatically replicates the search head’s knowledge bundle to the Portal and keeps it up to date with delta updates. The Portal uses the replicated bundle to evaluate lookups and data model definitions during searches, the same way a remote Splunk indexer would. Bundles are stored per organization and are never shared.
Scripted, external, and KV store lookups are the exception: they execute code inside a Splunk instance, so no federated provider can run them. CSV lookups, by far the most common case, work fully. For details, see [SPL command support](/splunk/portal/spl-support#transparent-mode-knowledge-objects).
## Verify the setup [#verify-the-setup]
Search a dataset directly by name:
```spl
index=http-logs | stats count
```
An exact event count confirms authentication and pushdown. If you use lookups, verify one end to end:
```spl
index=http-logs | lookup status_names status OUTPUT status_label | stats count by status_label
```
The lookup table lives on your Splunk search head and is joined against Axiom data through the replicated bundle. If you use data models, verify `tstats`:
```spl
| tstats count from datamodel=Web by Web.status
```
If a search shows an error banner, see [Monitor and troubleshoot](/splunk/portal/troubleshoot).
## What’s next [#whats-next]
* [SPL command support](/splunk/portal/spl-support)
* [Examples](/splunk/portal/examples)
---
# SPL command support in the Axiom Portal for Splunk
Source: https://axiom.co/docs/splunk/portal/spl-support
Every SPL command falls into one of three states when it runs against Axiom data through the Axiom Portal for Splunk. This is the same model Splunk uses between its own deployments.
* **Pushed down.** The command is computed inside Axiom. Results are exact at any dataset size, and only compact results cross the wire.
* **Search head.** Axiom returns the matching events, and the Splunk search head runs the command itself. This is exact whenever the matching events fit the response budget. Beyond that, a WARN banner reports that the command ran over a sample.
* **Caveat.** Supported, with a documented behavioral note.
## Search and retrieval [#search-and-retrieval]
| Command or form | Support | Notes |
| ------------------------------------------------------ | ----------- | ------------------------------------------------------------------------------------------------------------- |
| `search` filters: `=`, `!=`, `<`, `>`, `>=`, `<=` | Pushed down | Schema-aware: numeric-looking literals compare correctly against string and numeric fields |
| Wildcards `foo*`, `*foo`, `*foo*`, `f=*` | Pushed down | |
| `IN (…)`, `AND`, `OR`, `NOT`, implicit AND | Pushed down | |
| Free-text terms | Pushed down | Term-indexed and token-faithful to Splunk’s segmenter: `frontend` matches `frontend-proxy`, not `myfrontendx` |
| Quoted phrases | Pushed down | Substring search |
| Quoted and dotted field names, like `"service.name"=x` | Pushed down | Dotted names take double quotes in SPL, as on any Splunk index |
| Unknown field in a predicate | Pushed down | Returns 0 results with an INFO note, matching Splunk semantics: a field that doesn’t exist matches nothing |
| `fields f1 f2` without wildcards | Pushed down | Smaller events, so more rows fit the response budget |
| `TERM()` | Pushed down | Exact term match |
| `CASE()` | Pushed down | Fully case-sensitive. Phrases with spaces degrade to case-insensitive |
| Wildcard field names, like `status_*=x` | Search head | |
## Aggregations with stats [#aggregations-with-stats]
| Function | Support | Notes |
| ------------------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `count`, `count(f)` | Pushed down | Including the top-N pattern `stats count by X \| sort \| head N` |
| `sum`, `avg`, `mean`, `min`, `max`, `range` | Pushed down | Numeric and string fields. `min` and `max` compare strings lexicographically, matching Splunk |
| `stdev`, `stdevp`, `var`, `varp` | Pushed down | |
| `first`, `last`, `earliest`, `latest` | Pushed down | Events lacking the field are skipped, matching Splunk. `first` and `last` follow stream order, which native Splunk doesn’t guarantee to be time order either. Use `earliest` and `latest` for time-deterministic endpoints |
| `values`, `dc`, `distinct_count`, `estdc`, `mode` | Pushed down | Exact up to 50,000 distinct values per group, with a WARN beyond that. See [Limits](#limits) |
| `exactperc` | Pushed down | Exact and deterministic, computed from the exact value multiset shipped to the search head. Exact up to 50,000 distinct values per group, with a WARN beyond that |
| `median`, `perc`, `upperperc` | Pushed down | Approximate on native Splunk too: Splunk’s percentile estimator is digest-based and order-dependent. The provider ships an exact value histogram, and the search head’s estimator does the rest. Use `exactperc` when exactness matters |
| `list` | Pushed down | Capped like native Splunk. Member order follows stream order, which native Splunk doesn’t guarantee either. Apply `mvsort` when a deterministic order matters |
| Multiple aggregations in one `stats` | Pushed down | Any mix of the above, for example `stats count avg(x) min(kind) median(dur) by user` |
| `by` with multiple fields | Pushed down | Events lacking a group key are excluded, matching Splunk semantics |
## Charts and time series [#charts-and-time-series]
| Command | Support | Notes |
| ---------------------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `timechart [span=X] ` | Pushed down | Automatic spans follow Splunk’s ladder. Same aggregation support as `stats`. Series options `limit`, `useother`, `usenull`, and `cont` are supported. `bins` and `minspan` fall back to the search head |
| `timechart … by K` | Pushed down | Single split field. Null keys become `"NULL"`, matching Splunk |
| `chart by K` | Pushed down | `chart … over X by Y` falls back to the search head |
| `bin _time span=X` before `stats` | Pushed down | The bin folds into the aggregation’s group key, timezone-aligned for spans of one day and longer, like `timechart` |
| `bin` and `bucket` with `span=N` on other fields | Pushed down | Applied per event before the search head finalizes. Numeric bins render Splunk’s `lo-hi` range labels |
| `bin` and `bucket` options `aligntime` and log spans | Search head | |
| `top [N] f`, `rare [N] f` | Pushed down | Forms with a `by` clause fall back to the search head |
| `tstats count WHERE … BY …` | Pushed down | Simple forms. Exotic options fall back to the search head |
| `eventcount` | Pushed down | Transparent mode returns the exact all-time dataset total |
| `metadata` | Pushed down | `type=sourcetypes`, `hosts`, and `sources`. Powers Splunk’s Data Summary dialog |
## Streaming and transforming commands [#streaming-and-transforming-commands]
Everything not listed above runs on the search head over the events Axiom returns, and behaves identically to native Splunk with remote peers: `eval`, `where`, `rename`, `rex`, `regex`, `spath`, `extract`, `dedup`, `sort`, `head`, `tail`, `table`, `fillnull`, `mvexpand`, the `mv*` functions, `eventstats`, `streamstats`, `convert`, `replace`, `fieldformat`, `transaction`, `append`, and more. These commands are exact whenever the matching events fit the response budget described in [Limits](#limits).
Multivalue fields are first-class: Axiom fields that hold arrays of scalar values arrive as real Splunk multivalue fields, so `mvcount`, `mvexpand`, and `mvfilter` behave exactly as on local indexes.
## Machine Learning Toolkit [#machine-learning-toolkit]
The Splunk Machine Learning Toolkit (MLTK) works over the Portal in both federated modes. ML-SPL commands — `fit`, `apply`, `score`, `summary`, `listmodels`, `deletemodel`, `sample`, and `ai` — always execute on your search head, over the events Axiom returns. Nothing is installed on the Axiom side: MLTK and the Python for Scientific Computing add-on live on the search head, exactly as they would for a search over local indexes, and trained models are stored and applied there too.
```spl
index=http-logs | fit LinearRegression latency from bytes into my_model
index=http-logs | apply my_model
```
Any streaming commands before the ML-SPL command, like `eval` or `rex`, are applied to the events before your search head runs the model, and aggregations after it, like `stats`, are computed by the search head as usual. Verified end to end on Splunk Enterprise 9.x and 10.x in both modes: identical results to running MLTK over a local index, in training and in inference.
## Custom search commands from other apps [#custom-search-commands-from-other-apps]
Custom search commands run app code inside a Splunk instance, so no federated provider can execute them remotely — this is Splunk's model, not a Portal limit. What matters is where the command sits in your search:
* **After the first reducing command** (for example after `stats`): the command runs on your search head over the finalized results. Works with any app.
* **Before the first reducing command**, where Splunk ships it to the remote provider: the Portal fails the search with an ERROR banner naming the command, rather than returning events that are silently missing the command's effect. Move the command after a reducing command, or run it over a local index.
MLTK commands are the documented exception: Splunk keeps them on the search head, so they work in every position.
## Fidelity notes [#fidelity-notes]
| Behavior | Detail |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Event timestamps | Full sub-second precision is preserved end to end, so trace-level event ordering is correct, not floored to whole seconds. `_subsecond` is populated alongside `_time` |
| `timechart` bins of one day and longer | Aligned to the provider’s configured time zone, UTC by default, including daylight saving time transitions. Sub-day spans are timezone-independent. This mirrors how a native Splunk provider bins in its own time zone |
| Raw retrieval | Searches bounded by their own `head N` return exact results in a single response, honored up to 100,000 events within the response byte budget. Unbounded raw searches stream, so response size is bounded by your search head rather than by the provider |
## Transparent mode knowledge objects [#transparent-mode-knowledge-objects]
Transparent mode providers replicate the search head’s knowledge bundle to the Portal, which evaluates the objects a provider must. Everything else arrives pre-expanded by Splunk.
| Feature | Support | Notes |
| ------------------------------------------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `\| lookup …` with CSV lookups | Supported | Evaluated by Axiom from the replicated bundle. `OUTPUT`, `OUTPUTNEW`, `AS`, and case-insensitive matching |
| Automatic lookups | Supported | Applied per matching sourcetype, source, or host stanza, invisibly, like a native indexer |
| `\| datamodel X search`, `\| pivot` | Supported | Splunk pre-expands these into plain SPL before dispatch |
| `tag=`, `eventtype=` | Supported | Pre-expanded by the search head |
| `tstats FROM datamodel=X BY X.f` | Pushed down | `count`, `sum`, `avg`, `dc`, `values`, `min`, `max`, and more push down with exact results at any scale. Fields that can’t be mapped fall back to the search head |
| `\| inputlookup` | Search head | Splunk never dispatches it to a provider. It reads the search head’s own lookup tables |
| Data model acceleration with `summariesonly=true` | Pushed down | Treated as live compute. Results are exact, just not read from a pre-built summary |
| OCSF datasets as CIM data models | Supported | Requires the Axiom for Splunk app 1.4.0 or later. See [Search OCSF data as Splunk CIM](/splunk/portal/ocsf-cim) |
| KV store, external, and scripted lookups | Not supported | These execute code inside a Splunk instance, so no federated provider can run them. CSV lookups, the common case, work fully |
## Limits [#limits]
There are two genuine limits, and both come from outside the Portal. Everything else is either a bounded estimate that warns when reached, or standard Splunk behavior.
**Raw event retrieval is size-bounded.** When you pull individual events rather than an aggregation, the response is bounded by what your Splunk search head accepts. The default budget is 20,000 events or about 40 MB per search, and an explicit `head N` is honored beyond the default, up to 100,000 events, with the byte budget applying first. When a search delivers fewer events than requested, a banner names the budget that was reached. This affects raw retrieval only: aggregations are computed inside Axiom and stay exact at any dataset size. Keeping fewer columns with `fields` or narrowing filters lets more events fit.
**Scripted, external, and KV store lookups can’t run.** They execute code inside a Splunk instance. CSV lookups work fully.
Bounded estimates, each flagged with a WARN banner when reached:
* `dc`, `values`, `median`, and `percentile` are exact up to 50,000 distinct values per group. Beyond that, the result becomes an estimate and the search says so. This only bites on pathologically wide distributions.
* `stats … by ` returns the top groups by count when a group-by has more distinct values than the row budget. This is only a real limit for very-high-cardinality group-bys.
## Known Splunk behaviors [#known-splunk-behaviors]
These aren’t provider behaviors, but they’re useful to know because they surprise people on any Splunk index:
* Dotted field names take quotes in SPL: `"service.name"=frontend`, `stats count by "status.code"`.
* A filter on a non-existent field returns no results, not an error. The search shows an INFO note so you know why.
* `case(f>=500, …)` with a numeric comparison on a string field returns nothing on native Splunk too. Use `case(tonumber(f)>=500, …)`.
* Continuously ingesting datasets give slightly different counts seconds apart. That’s freshness, not an error. Compare with identical, closed time ranges.
---
# Monitor and troubleshoot the Axiom Portal for Splunk
Source: https://axiom.co/docs/splunk/portal/troubleshoot
The Axiom Portal for Splunk never degrades silently. Every degraded path surfaces a visible banner on the search job, and every search reports Axiom-side metrics in Splunk’s Job Inspector. Start there.
## Inspect a search [#inspect-a-search]
On any federated search, click **Job**, and then select **Inspect Job**. The Execution costs section includes `axiom.*` components that show what happened on the Axiom side:
* Events scanned in Axiom. For pushed-down aggregations, this reflects the full scan, even though only compact result rows crossed the wire.
* Axiom query time and end-to-end time.
* Rows in and rows out.
If the `axiom.*` components are missing, the response was served from the provider’s short-lived cache. Run a fresh query to see them.
## Banners [#banners]
Banners on federated searches are prefixed with `[axiom,]`.
| Banner | Meaning | What to do |
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Axiom: aggregation pushed down (N events aggregated at the source)` | INFO. The aggregation ran inside Axiom, and results are exact regardless of size. | Nothing. This is the good path. |
| `Axiom: aggregation computed over sampled events…` | WARN. A command that runs on the search head needed more events than the response budget, so it ran over a sample. | Narrow the time range or filters, or use a pushed-down function. See [SPL command support](/splunk/portal/spl-support). |
| `Axiom: results limited to N of the M requested events…` | INFO. Raw event retrieval reached the provider’s response budget before satisfying `head N`. | Narrow the search, or keep fewer columns with `fields`, to fit more events. |
| `Axiom: one or more fields are not present in the dataset…` | INFO. A filter referenced a field the dataset doesn’t have. Splunk semantics: no matches. | Check the field name against the dataset schema. |
| `Axiom authentication failed…` | FATAL. Axiom rejected the credential. | Set the provider’s service account password to the token value, the string starting with `xaat-`, not the token’s name. Check the token isn’t expired or revoked. |
| `Axiom Portal: no credentials received…` | FATAL. The request arrived without a service account password. | Set the provider’s service account password to your Axiom API token, with your Axiom organization ID as the username. |
| `Axiom rate limit exceeded…` | ERROR. The Axiom organization hit its query rate limit. | Retry, or reduce dashboard refresh frequency. |
## Common issues [#common-issues]
**Test connection succeeds, but searches report an authentication failure.**
Splunk’s **Test connection** verifies DNS, TLS, protocol compatibility, and that a credential reached the Portal, but it doesn’t run a query. A well-formed but expired, revoked, or mistyped token can pass the test. Run `index=federated: | stats count` as the real credential check. If it shows the authentication banner, replace the service account password with the token value. The most common cause is entering the token’s name instead of the `xaat-` token string.
**A search returns 0 rows, but the data exists.**
Check the time range first: the search’s `earliest` and `latest` are applied to the Axiom query as-is. Then check the field name. Dotted names must be quoted in SPL: `"service.name"=frontend`. A bare `index=` search with a bad credential can also look like an empty result. Run `| stats count` to surface any authentication banner.
**Counts differ between two runs of the same search.**
Continuously ingesting datasets see new data between runs. Compare with identical, closed time ranges.
**Daily timechart bars look shifted by a few hours.**
Bins of one day and longer align to the provider’s configured time zone, UTC by default. This mirrors native Splunk, where a provider bins in its own time zone and the search head doesn’t re-bin. Sub-day spans are timezone-independent and never need attention. [Contact Axiom](https://axiom.co/contact) to align daily bins to your users’ time zone.
**A lookup or data model doesn’t work.**
Lookups and data models require [transparent mode](/splunk/portal/set-up-transparent). Scripted, external, and KV store lookups can’t run on any federated provider. CSV lookups work fully.
**Results look inconsistent across searches.**
Check that only one mode is registered. Pointing a standard and a transparent provider at the same endpoint yields inconsistent results. Use one mode per deployment.
**`case(f>=500, …)` returns nothing.**
This is native Splunk behavior when the field holds string values. The same search fails on local indexes. Use `case(tonumber(f)>=500, …)`.
## Get help [#get-help]
Visit [axiom.co/support](https://axiom.co/support) or email [support@axiom.co](mailto:support@axiom.co). Include the Splunk version, the mode, the search you ran, and the text of any banner.
---
# Instrumentation with Axiom AI SDK
Source: https://axiom.co/docs/use-cases/llm-observability/axiom-ai-sdk-instrumentation
This page explains how to set up instrumentation in your TypeScript generative AI app using Axiom AI SDK.
Axiom AI SDK is an open-source project and welcomes your contributions. For more information, see the [GitHub repository](https://github.com/axiomhq/ai).
Alternatively, [instrument your app manually](/use-cases/llm-observability/manual-instrumentation). For more information on instrumentation approaches, see [LLM observability](/use-cases/llm-observability).
## Prerequisite [#prerequisite]
Install the Axiom AI SDK by running the following:
```sh
npm i @axiomhq/ai
```
Set the `AXIOM_TOKEN` and `AXIOM_DATASET` environment variables using an [API token](/reference/tokens) and the name of a dataset you want to send telemetry to.
## Instrument AI SDK calls [#instrument-ai-sdk-calls]
Axiom AI SDK provides helper functions for [Vercel AI SDK](https://ai-sdk.dev/docs) to wrap your existing AI model client. The `wrapAISDKModel` function takes an existing AI model object and returns an instrumented version that automatically generates trace data for every call.
Choose one of the following common Vercel AI SDK providers. For the full list of providers, see the [Vercel documentation](https://ai-sdk.dev/providers/ai-sdk-providers).
1. Run the following in your terminal to install the Vercel AI SDK and the OpenAI provider.
```sh
npm i ai @ai-sdk/openai
```
2. Create the file `src/shared/openai.ts` with the following content:
```ts /src/shared/openai.ts
import { createOpenAI } from '@ai-sdk/openai';
import { wrapAISDKModel } from 'axiom/ai';
const openaiProvider = createOpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
// Wrap the model to enable automatic tracing
export const gpt4o = wrapAISDKModel(openaiProvider('gpt-4o'));
export const gpt4oMini = wrapAISDKModel(openaiProvider('gpt-4o-mini'));
```
1. Run the following in your terminal to install the Vercel AI SDK and the Anthropic provider.
```sh
npm i ai @ai-sdk/anthropic
```
2. Create the file `src/shared/anthropic.ts` with the following content:
```ts /src/shared/anthropic.ts
import { createAnthropic } from '@ai-sdk/anthropic';
import { wrapAISDKModel } from 'axiom/ai';
const anthropicProvider = createAnthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
// Wrap the model to enable automatic tracing
export const claude35Sonnet = wrapAISDKModel(anthropicProvider('claude-3-5-sonnet-20241022'));
export const claude35Haiku = wrapAISDKModel(anthropicProvider('claude-3-5-haiku-20241022'));
```
1. Run the following in your terminal to install the Vercel AI SDK and the Gemini provider.
```sh
npm i ai @ai-sdk/google
```
2. Create the file `src/shared/gemini.ts` with the following content:
```ts /src/shared/gemini.ts
import { createGoogleGenerativeAI } from '@ai-sdk/google';
import { wrapAISDKModel } from 'axiom/ai';
const geminiProvider = createGoogleGenerativeAI({
apiKey: process.env.GEMINI_API_KEY,
});
// Wrap the model to enable automatic tracing
export const gemini20Flash = wrapAISDKModel(geminiProvider('gemini-2.0-flash-exp'));
export const gemini15Pro = wrapAISDKModel(geminiProvider('gemini-1.5-pro'));
```
1. Run the following in your terminal to install the Vercel AI SDK and the Grok provider.
```sh
npm i ai @ai-sdk/xai
```
2. Create the file `src/shared/grok.ts` with the following content:
```ts /src/shared/grok.ts
import { createXai } from '@ai-sdk/xai';
import { wrapAISDKModel } from 'axiom/ai';
const grokProvider = createXai({
apiKey: process.env.XAI_API_KEY,
});
// Wrap the model to enable automatic tracing
export const grokBeta = wrapAISDKModel(grokProvider('grok-beta'));
export const grok2Mini = wrapAISDKModel(grokProvider('grok-2-mini'));
```
To instrument calls without a Vercel AI SDK provider, use the generic Vercel AI Gateway provider.
To instrument calls without a Vercel AI SDK provider, use the generic Vercel AI Gateway provider. For more information, see the [Vercel documentation](https://ai-sdk.dev/providers/ai-sdk-providers/ai-gateway).
1. Run the following in your terminal to install the Vercel AI SDK:
```sh
npm i ai
```
2. Create the file `src/shared/openai.ts` with the following content:
```ts /src/shared/openai.ts
import { createGateway } from 'ai';
import { wrapAISDKModel } from 'axiom';
const gateway = createGateway({
apiKey: process.env.OPENAI_API_KEY,
});
// Wrap the model to enable automatic tracing
export const gpt4o = wrapAISDKModel(gateway('openai/gpt-4o'));
```
The rest of the page explains how to work with OpenAI. The process is similar for other LLMs.
## Add context [#add-context]
The `withSpan` function allows you to add crucial business context to your traces. It creates a parent span around your LLM call and attaches metadata about the `capability` and `step` that you execute.
```ts /src/app/page.tsx
import { withSpan } from 'axiom/ai';
import { generateText } from 'ai';
import { gpt4o } from '@/shared/openai';
export default async function Page() {
const userId = 123;
// Use withSpan to define the capability and step
const res = await withSpan({ capability: 'get_capital', step: 'generate_answer' }, (span) => {
// You have access to the OTel span to add custom attributes
span.setAttribute('user_id', userId);
return generateText({
model: gpt4o, // Use the wrapped model
messages: [
{
role: 'user',
content: 'What is the capital of Spain?',
},
],
});
});
return {res.text}
;
}
```
## Instrument tool calls [#instrument-tool-calls]
For many AI capabilities, the LLM call is only part of the story. If your capability uses tools to interact with external data or services, observing the performance and outcome of those tools is critical. Axiom AI SDK provides the `wrapTool` and `wrapTools` functions to automatically instrument your Vercel AI SDK tool definitions.
The `wrapTool` helper takes your tool’s name and its definition and returns an instrumented version. This wrapper creates a dedicated child span for every tool execution, capturing its arguments, output, and any errors.
```ts /src/app/generate-text/page.tsx
import { tool } from 'ai';
import { z } from 'zod';
import { wrapTool } from 'axiom/ai';
import { generateText } from 'ai';
import { gpt4o } from '@/shared/openai';
// In your generateText call, provide wrapped tools
const { text, toolResults } = await generateText({
model: gpt4o,
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'How do I get from Paris to Berlin?' },
],
tools: {
// Wrap each tool with its name
findDirections: wrapTool(
'findDirections', // The name of the tool
tool({
description: 'Find directions to a location',
inputSchema: z.object({
from: z.string(),
to: z.string(),
}),
execute: async (params) => {
// Your tool logic here...
return { directions: `To get from ${params.from} to ${params.to}, use a teleporter.` };
},
})
)
}
});
```
## Complete example [#complete-example]
Example of how all three instrumentation functions work together in a single, real-world example:
```ts /src/app/page.tsx expandable
import { withSpan, wrapAISDKModel, wrapTool } from 'axiom/ai';
import { generateText, tool } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
import { z } from 'zod';
// 1. Create and wrap the AI model client
const openaiProvider = createOpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const gpt4o = wrapAISDKModel(openaiProvider('gpt-4o'));
// 2. Define and wrap your tool(s)
const findDirectionsTool = wrapTool(
'findDirections', // The tool name must be passed to the wrapper
tool({
description: 'Find directions to a location',
inputSchema: z.object({ from: z.string(), to: z.string() }),
execute: async ({ from, to }) => ({
directions: `To get from ${from} to ${to}, use a teleporter.`,
}),
})
);
// 3. In your application logic, use `withSpan` to add context
// and call the AI model with your wrapped tools.
export default async function Page() {
const userId = 123;
const { text } = await withSpan({ capability: 'get_directions', step: 'generate_ai_response' }, async (span) => {
// You have access to the OTel span to add custom attributes
span.setAttribute('user_id', userId);
return generateText({
model: gpt4o, // Use the wrapped model
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'How do I get from Paris to Berlin?' },
],
tools: {
findDirections: findDirectionsTool, // Use the wrapped tool
},
});
});
return {text}
;
}
```
This demonstrates the three key steps to rich observability:
1. **`wrapAISDKModel`**: Automatically captures telemetry for the LLM provider call
2. **`wrapTool`**: Instruments the tool execution with detailed spans
3. **`withSpan`**: Creates a parent span that ties everything together under a business capability
## What’s next? [#whats-next]
After sending traces to Axiom:
* View your [traces](/query-data/traces) in Console
* Set up [monitors and alerts](/monitor-data/monitors) based on your AI telemetry data
* Learn about the [GenAI APL functions](/apl/scalar-functions/genai-functions) for querying AI telemetry
---
# Generative AI attributes
Source: https://axiom.co/docs/use-cases/llm-observability/gen-ai-attributes
After you instrument your app, every LLM call sends a detailed span to your Axiom dataset. The spans are enriched with standardized `gen_ai.*` attributes that make your AI interactions easy to query and analyze.
Key attributes include the following:
## Span identification [#span-identification]
* `gen_ai.capability.name`: The high-level capability name you defined in `withSpan`.
* `gen_ai.step.name`: The specific step within the capability.
* `gen_ai.operation.name`: The operation type. For example: `chat`, `execute_tool`.
## Model information [#model-information]
* `gen_ai.provider.name`: The model provider. For example: `openai`, `anthropic`.
* `gen_ai.request.model`: The model requested for the completion.
* `gen_ai.response.model`: The model that actually fulfilled the request.
* `gen_ai.output.type`: The output type. For example: `text`, `json`.
## Token usage [#token-usage]
* `gen_ai.usage.input_tokens`: The number of tokens in the prompt.
* `gen_ai.usage.output_tokens`: The number of tokens in the generated response.
## Messages [#messages]
* `gen_ai.input.messages`: The full, rendered prompt or message history sent to the model (as a JSON string).
* `gen_ai.output.messages`: The full response from the model (as a JSON string).
* `gen_ai.response.finish_reasons`: The reason the model stopped generating tokens. For example: `stop`, `tool-calls`.
* `gen_ai.response.id`: The unique identifier for the model response.
## Tool attributes [#tool-attributes]
* `gen_ai.tool.name`: The name of the executed tool.
* `gen_ai.tool.call.arguments`: The arguments passed to the tool (as a JSON string).
* `gen_ai.tool.call.result`: The result returned by the tool (as a JSON string).
## Additional attributes [#additional-attributes]
For a more thorough list of attributes, see the [OpenTelemetry Semantic Conventions for Generative AI](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/).
## What’s next? [#whats-next]
After capturing and analyzing production telemetry:
* [Visualize traces](/query-data/traces) in Console.
* Use [GenAI APL functions](/apl/scalar-functions/genai-functions) to query and analyze your AI telemetry.
---
# Manual instrumentation
Source: https://axiom.co/docs/use-cases/llm-observability/manual-instrumentation
Manually instrumenting your generative AI apps using language-agnostic OpenTelemetry tooling gives you full control over your instrumentation while ensuring compatibility with Axiom’s LLM observability features.
Alternatively, instrument your app with Axiom AI SDK. For more information on instrumentation approaches, see [LLM observability](/use-cases/llm-observability).
For more information on sending OpenTelemetry data to Axiom, see [Send OpenTelemetry data to Axiom](/send-data/opentelemetry#send-opentelemetry-data-to-axiom) for examples in multiple languages.
## Required attributes [#required-attributes]
Axiom’s conventions for AI spans are based on version 1.37 of the [OpenTelemetry semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/) for generative client AI spans.
Axiom requires the following attributes in your data to properly recognize your spans:
* `gen_ai.operation.name` identifies AI spans. It’s also a required attribute in the OpenTelemetry specification.
* `gen_ai.capability.name` provides context about the specific capability being used within the AI operation.
* `gen_ai.step.name` allows you to break down the AI operation into individual steps for more granular tracking.
### `gen_ai.operation.name` [#gen_aioperationname]
Axiom currently provides custom UI for the following operations related to the `gen_ai.operation.name` attribute:
* `chat`: Chat completion
* `execute_tool`: Tool execution
Other possible values include:
* `generate_content`: Multimodal content generation
* `embeddings`: Vector embeddings
* `create_agent`: Create AI agents
* `invoke_agent`: Invoke existing agents
* `text_completion`: Text completion. This is a legacy value and has been deprecated by OpenAI and many other providers.
For more information, see the OpenTelemetry documentation on [GenAI Attributes](https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-operation-name).
## Recommended attributes [#recommended-attributes]
Axiom recommends the following attributes to get the most out of Axiom’s AI telemetry features:
### `axiom.gen_ai` attributes [#axiomgen_ai-attributes]
* `axiom.gen_ai.schema_url`: Schema URL for the Axiom AI conventions. For example: `https://axiom.co/ai/schemas/0.0.2`
* `axiom.gen_ai.sdk.name`: Name of the SDK. For example: `my-ai-instrumentation-sdk`
* `axiom.gen_ai.sdk.version`: Version of the SDK. For example: `1.2.3`
### Chat spans [#chat-spans]
| Attribute | Type | Required | Description |
| :------------------------------- | :------------------------ | :------------- | :---------------------------------------------- |
| `gen_ai.provider.name` | string | Required | Provider (openai, anthropic, aws.bedrock, etc.) |
| `gen_ai.request.model` | string | When available | Model requested (gpt-4, claude-3, etc.) |
| `gen_ai.response.model` | string | When available | Model that fulfilled the request |
| `gen_ai.input.messages` | Messages\[] (stringified) | Recommended | Input conversation history |
| `gen_ai.output.messages` | Messages\[] (stringified) | Recommended | Model response messages |
| `gen_ai.usage.input_tokens` | integer | Recommended | Input token count |
| `gen_ai.usage.output_tokens` | integer | Recommended | Output token count |
| `gen_ai.request.choice_count` | integer | When >1 | Number of completion choices requested |
| `gen_ai.response.id` | string | Recommended | Unique response identifier |
| `gen_ai.response.finish_reasons` | string\[] | Recommended | Why generation stopped |
| `gen_ai.conversation.id` | string | When available | Conversation/session identifier |
### Tool spans [#tool-spans]
For tool operations (`execute_tool`), include these additional attributes:
| Attribute | Type | Required | Description |
| :------------------------ | :----- | :------------- | :----------------------------------------- |
| `gen_ai.tool.name` | string | Required | Name of the executed tool |
| `gen_ai.tool.call.id` | string | When available | Tool call identifier |
| `gen_ai.tool.type` | string | When available | Tool type (function, extension, datastore) |
| `gen_ai.tool.description` | string | When available | Tool description |
| `gen_ai.tool.arguments` | string | When available | Tool arguments |
| `gen_ai.tool.message` | string | When available | Tool message |
For more information, see [GenAI Attributes](https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#genai-attributes).
### Agent spans [#agent-spans]
For agent operations (`create_agent`, `invoke_agent`), include these additional attributes:
| Attribute | Type | Required | Description |
| :------------------------- | :----- | :------------- | :------------------------------ |
| `gen_ai.agent.id` | string | When available | Unique agent identifier |
| `gen_ai.agent.name` | string | When available | Human-readable agent name |
| `gen_ai.agent.description` | string | When available | Agent description/purpose |
| `gen_ai.conversation.id` | string | When available | Conversation/session identifier |
## Span naming [#span-naming]
Ensure span names follow the OpenTelemetry conventions for generative AI spans. For example, the suggested span names for common values of `gen_ai.operation.name` are the following:
* `chat {gen_ai.request.model}`
* `execute_tool {gen_ai.tool.name}`
* `embeddings {gen_ai.request.model}`
* `generate_content {gen_ai.request.model}`
* `text_completion {gen_ai.request.model}`
* `create_agent {gen_ai.agent.name}`
* `invoke_agent {gen_ai.agent.name}`
For more information, see the OpenTelemetry documentation on span naming:
* [AI spans](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/#spans)
* [Agent spans](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-agent-spans/)
* [Tool span](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/#execute-tool-span)
## Messages [#messages]
Messages support four different roles, each with specific content formats. They follow OpenTelemetry’s structured format:
### System messages [#system-messages]
System messages are messages that the system adds to set the behavior of the assistant. They typically contain instructions or context for the AI model.
```json
{
"role": "system",
"parts": [
{"type": "text", "content": "You are a helpful assistant"}
]
}
```
### User messages [#user-messages]
User messages are messages that users send to the AI model. They typically contain questions, commands, or other input from the user.
```json
{
"role": "user",
"parts": [
{"type": "text", "content": "Weather in Paris?"}
]
}
```
### Assistant messages [#assistant-messages]
Assistant messages are messages that the AI model sends back to the user. They typically contain responses, answers, or other output from the model.
```json
{
"role": "assistant",
"parts": [
{"type": "text", "content": "Hi there!"},
{"type": "tool_call", "id": "call_123", "name": "get_weather", "arguments": {"location": "Paris"}}
],
"finish_reason": "stop"
}
```
### Tool messages [#tool-messages]
Tool messages are messages that contain the results of tool calls made by the AI model. They typically contain the output or response from the tool.
```json
{
"role": "tool",
"parts": [
{"type": "tool_call_response", "id": "call_123", "response": "rainy, 57°F"}
]
}
```
### Content part types [#content-part-types]
* `text`: Text content with `content` field
* `tool_call`: Tool invocation with `id`, `name`, `arguments`
* `tool_call_response`: Tool result with `id`, `response`
For more information, see the OpenTelemetry documentation:
* [Recording content on attributes](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/#recording-content-on-attributes)
* JSON schema for [inputs](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-input-messages.json) and [outputs](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-output-messages.json)
## Example trace structure [#example-trace-structure]
### Chat completion [#chat-completion]
Example of a properly structured chat completion trace:
```typescript TypeScript expandable
import { trace, SpanKind, SpanStatusCode } from '@opentelemetry/api';
const tracer = trace.getTracer('my-app');
// Create a span for the AI operation
return tracer.startActiveSpan('chat gpt-4', {
kind: SpanKind.CLIENT
}, (span) => {
try {
// (Your AI operation logic here...)
span.setAttributes({
// Set operation name
'gen_ai.operation.name': 'chat',
// Set capability and step
'gen_ai.capability.name': 'customer_support',
'gen_ai.step.name': 'respond_to_greeting',
// Set other attributes
'gen_ai.provider.name': 'openai',
'gen_ai.request.model': 'gpt-4',
'gen_ai.response.model': 'gpt-4',
'gen_ai.usage.input_tokens': 150,
'gen_ai.usage.output_tokens': 75,
'gen_ai.input.messages': JSON.stringify([
{ role: 'user', parts: [{ type: 'text', content: 'Hello, how are you?' }] }
]),
'gen_ai.output.messages': JSON.stringify([
{ role: 'assistant', parts: [{ type: 'text', content: 'I\'m doing well, thank you!' }], finish_reason: 'stop' }
])
});
return /* your result */;
} catch (error) {
span.recordException(error);
span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
throw error; // rethrow if you want upstream to see it
} finally {
span.end();
}
});
```
```python Python expandable
from opentelemetry import trace
from opentelemetry.trace import SpanKind
import json
tracer = trace.get_tracer("my-app")
# Create a span for the AI operation
with tracer.start_as_current_span("chat gpt-4", kind=SpanKind.CLIENT) as span:
# (Your AI operation logic here...)
span.set_attributes({
# Set operation name
"gen_ai.operation.name": "chat",
# Set capability and step
"gen_ai.capability.name": "customer_support",
"gen_ai.step.name": "respond_to_greeting",
# Set other attributes
"gen_ai.provider.name": "openai",
"gen_ai.request.model": "gpt-4",
"gen_ai.response.model": "gpt-4",
"gen_ai.usage.input_tokens": 150,
"gen_ai.usage.output_tokens": 75,
"gen_ai.input.messages": json.dumps([
{"role": "user", "parts": [{"type": "text", "content": "Hello, how are you?"}]}
]),
"gen_ai.output.messages": json.dumps([
{"role": "assistant", "parts": [{"type": "text", "content": "I'm doing well, thank you!"}], "finish_reason": "stop"}
])
})
```
### Tool execution [#tool-execution]
Example of a tool execution within an agent:
```typescript TypeScript expandable
import { trace, SpanKind, SpanStatusCode } from '@opentelemetry/api';
const tracer = trace.getTracer('my-agent-app');
// Create a span for tool execution
return tracer.startActiveSpan('execute_tool get_weather', {
kind: SpanKind.CLIENT
}, (span) => {
try {
// (Your tool call logic here...)
span.setAttributes({
// Set operation name
'gen_ai.operation.name': 'execute_tool',
// Set capability and step
'gen_ai.capability.name': 'weather_assistance',
'gen_ai.step.name': 'fetch_current_weather',
// Set other attributes
'gen_ai.tool.name': 'get_weather',
'gen_ai.tool.type': 'function',
'gen_ai.tool.call.id': 'call_abc123',
'gen_ai.tool.arguments': JSON.stringify({ location: 'New York', units: 'celsius' }),
'gen_ai.tool.message': JSON.stringify({ temperature: 22, condition: 'sunny', humidity: 65 }),
});
return /* your result */;
} catch (error) {
span.recordException(error);
span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
throw error; // rethrow if you want upstream to see it
} finally {
span.end();
}
});
```
```python Python expandable
from opentelemetry import trace
from opentelemetry.trace import SpanKind
import json
tracer = trace.get_tracer("my-agent-app")
# Create a span for tool execution
with tracer.start_as_current_span("execute_tool get_weather", kind=SpanKind.CLIENT) as span:
span.set_attributes({
# Set operation name
"gen_ai.operation.name": "execute_tool",
# Set capability and step
"gen_ai.step.name": "fetch_current_weather",
"gen_ai.capability.name": "weather_assistance",
# Set other attributes
"gen_ai.tool.name": "get_weather",
"gen_ai.tool.type": "function",
"gen_ai.tool.call.id": "call_abc123",
"gen_ai.tool.arguments": json.dumps({"location": "New York", "units": "celsius"}),
"gen_ai.tool.message": json.dumps({"temperature": 22, "condition": "sunny", "humidity": 65}),
})
```
## What’s next? [#whats-next]
After sending traces with the proper semantic conventions:
* View your [traces](/query-data/traces) in Console
* Set up [monitors and alerts](/monitor-data/monitors) based on your AI telemetry data
* Learn about the [GenAI APL functions](/apl/scalar-functions/genai-functions) for querying AI telemetry
---
# Redaction policies
Source: https://axiom.co/docs/use-cases/llm-observability/redaction-policies
Axiom AI SDK provides flexible redaction policies to control what data is captured in OpenTelemetry spans. This allows you to balance observability needs with privacy and compliance requirements.
## Built-in redaction policies [#built-in-redaction-policies]
Axiom AI SDK provides two built-in redaction policies:
| Policy | What gets captured | What gets excluded | When to use |
| :--------------------------------------------------- | :-------------------------------------- | :----------------------------------------------- | :----------------- |
| [AxiomDefault](#axiomdefault-policy) | Full data | – | Full observability |
| [OpenTelemetryDefault](#opentelemetrydefault-policy) | Model metadata, token usage, error info | Prompt text, AI responses, tool args and results | Privacy-first |
If you don’t specify a redaction policy, Axiom AI SDK applies `AxiomDefault`.
To determine which redaction policy fits your needs, see the following comparison:
### AxiomDefault policy [#axiomdefault-policy]
By default, Axiom AI SDK captures all data for maximum observability.
**What gets captured:**
* Full prompt text and AI responses in chat spans
* Complete tool arguments and return values on tool spans
* All standard OpenTelemetry attributes (model name, token usage, etc.)
Capturing full message content increases span size and storage costs.
**When to use:**
* You need full visibility into AI interactions
* Data privacy isn’t a concern
* Debugging complex AI workflows
### OpenTelemetryDefault policy [#opentelemetrydefault-policy]
The OpenTelemetry default policy excludes sensitive content.
**What gets captured:**
* Model metadata (name, provider, version)
* Token usage and performance metrics
* Error information and status codes
**What gets excluded:**
* Prompt text and AI responses
* Tool arguments and return values
**When to use:**
* Handling sensitive or personal data
* Compliance requirements restrict data capture
* You only need performance and error metrics
### What gets captured [#what-gets-captured]
To determine which redaction policy fits your needs, see the following examples about what gets captured with each defaultpolicy:
```json
{
"gen_ai.operation.name": "chat",
"gen_ai.request.model": "gpt-4o-mini",
"gen_ai.input.messages": "[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"Hello, how are you?\"}]}]",
"gen_ai.output.messages": "[{\"role\":\"assistant\",\"content\":\"I'm doing well, thank you for asking!\"}]",
"gen_ai.usage.input_tokens": 12,
"gen_ai.usage.output_tokens": 15,
"gen_ai.usage.total_tokens": 27
}
```
```json
{
"gen_ai.tool.name": "weather_lookup",
"gen_ai.tool.description": "Get current weather for a location",
"gen_ai.tool.arguments": "{\"location\":\"San Francisco\",\"units\":\"celsius\"}",
"gen_ai.tool.message": "{\"temperature\":18,\"condition\":\"partly cloudy\"}"
}
```
```json
{
"gen_ai.operation.name": "chat",
"gen_ai.request.model": "gpt-4o-mini",
"gen_ai.usage.input_tokens": 12,
"gen_ai.usage.output_tokens": 15,
"gen_ai.usage.total_tokens": 27
}
```
Message content (`gen_ai.input.messages` and `gen_ai.output.messages`) is excluded for privacy.
```json
{
"gen_ai.tool.name": "weather_lookup",
"gen_ai.tool.description": "Get current weather for a location"
}
```
Tool arguments and results (`gen_ai.tool.arguments` and `gen_ai.tool.message`) are excluded for privacy.
## Global configuration [#global-configuration]
Set a default redaction policy for your entire app using `initAxiomAI`:
```ts Full data capture
import { trace } from '@opentelemetry/api';
import { initAxiomAI, RedactionPolicy } from 'axiom/ai';
const tracer = trace.getTracer("my-tracer");
initAxiomAI({ tracer, redactionPolicy: RedactionPolicy.AxiomDefault });
```
```ts Privacy-first
import { trace } from '@opentelemetry/api';
import { initAxiomAI, RedactionPolicy } from 'axiom/ai';
const tracer = trace.getTracer("my-tracer");
initAxiomAI({ tracer, redactionPolicy: RedactionPolicy.OpenTelemetryDefault });
```
`initAxiomAI` is called in your instrumentation file (`/src/instrumentation.ts`). For setup instructions, see [Instrumentation with Axiom AI SDK](/use-cases/llm-observability/axiom-ai-sdk-instrumentation).
## Per-operation override [#per-operation-override]
You can configure different policies for each operation. Axiom resolves redaction policies in the following order (from highest to lowest precedence):
1. Per-operation policy
2. Global policy
3. Default policy
Override the global or default policy for specific operations by passing a `redactionPolicy` to `withSpan`:
```ts
import { withSpan, RedactionPolicy } from 'axiom/ai';
import { generateText } from 'ai';
const result = await withSpan(
{ capability: 'customer_support', step: 'handle_sensitive_query' },
async (span) => {
span.setAttribute('user.id', userId);
return generateText({
model: wrappedModel,
prompt: 'Process this sensitive customer data...'
});
},
{ redactionPolicy: RedactionPolicy.OpenTelemetryDefault }
);
```
## Custom redaction policies [#custom-redaction-policies]
Create custom policies by defining an `AxiomAIRedactionPolicy` object:
```ts
import { trace } from '@opentelemetry/api';
import { initAxiomAI, AxiomAIRedactionPolicy } from 'axiom/ai';
const tracer = trace.getTracer("my-tracer");
// Custom policy: capture messages but not tool payloads
const customPolicy: AxiomAIRedactionPolicy = {
captureMessageContent: 'full',
mirrorToolPayloadOnToolSpan: false
};
initAxiomAI({ tracer, redactionPolicy: customPolicy });
```
The `AxiomAIRedactionPolicy` object has two properties:
Controls whether prompt and response text is included in chat spans.
* `'full'`: Include complete message content
* `'off'`: Exclude all message content
Controls whether tool arguments and results are duplicated on tool spans.
* `true`: Mirror tool data for easier querying
* `false`: Only capture tool metadata (name, description)
The [built-in policies](#built-in-redaction-policies) configure the `AxiomAIRedactionPolicy` object in the following way:
| Default policy | captureMessageContent | mirrorToolPayloadOnToolSpan |
| :------------------- | :-------------------- | :-------------------------- |
| AxiomDefault | `'full'` | `true` |
| OpenTelemetryDefault | `'off'` | `false` |
## Related documentation [#related-documentation]
Learn how to instrument your AI applications with Axiom AI SDK
Understand the OpenTelemetry attributes captured by Axiom AI SDK
---
# Query OCSF data
Source: https://axiom.co/docs/use-cases/ocsf/query
This page shows how to query an OCSF dataset with APL. It covers the end of the OCSF flow in Axiom: the dataset is prepared and receives conformed events, as described in [Send OCSF data to Axiom](/use-cases/ocsf/send-data). To search the same data from Splunk, see [Search OCSF data from Splunk](/splunk/portal/ocsf).
The examples run against the 100 synthetic events in the OCSF for Axiom pack’s `axiom_normalize_post_processor` sample after conforming. The outputs show what each query returns for that sample. Replace `ocsf` with the name of your dataset.
## Choose the right reference [#choose-the-right-reference]
Every OCSF attribute lives in exactly one place. The place determines how you reference it in APL:
| Attribute | Stored as | APL reference |
| ------------------------------ | --------------------------- | -------------------------------------- |
| `class_uid`, `severity_id` | Promoted column | `class_uid` |
| `user.name`, `src_endpoint.ip` | Promoted column | `['user.name']` |
| `attacks`, `observables` | Map field, array of objects | `['attacks'][0]['technique']['uid']` |
| `device.os.name` | Under `unmapped` | `['unmapped']['device']['os']['name']` |
Column names that contain dots must be quoted with brackets, for example `['src_endpoint.ip']`. For more information, see [Entity names](/apl/entities/entity-names#quote-identifiers). Inside map fields, use index notation for each level. For more information, see [Map fields](/apl/data-types/map-fields#access-properties-of-nested-maps).
To see which columns your dataset actually contains, use `getschema`. If an attribute isn’t a column, it’s either inside a map field or under `unmapped`:
```kusto
['ocsf']
| getschema
```
Filter and group on numeric `*_id` columns rather than their string siblings. For example, use `status_id == 2` rather than `status == 'Failure'`. Producers spell the strings differently, but the IDs are fixed by OCSF. The [OCSF schema browser](https://schema.ocsf.io) lists the meaning of every ID.
## Count events by class [#count-events-by-class]
Start with an inventory of the classes in the dataset:
```kusto
['ocsf']
| summarize events = count() by class_uid, class_name
| sort by events desc
```
| class\_uid | class\_name | events |
| ---------- | ----------------- | ------ |
| 4001 | Network Activity | 40 |
| 4003 | DNS Activity | 15 |
| 3002 | Authentication | 15 |
| 1007 | Process Activity | 10 |
| 4002 | HTTP Activity | 10 |
| 2004 | Detection Finding | 5 |
| 6003 | API Activity | 5 |
## Filter on promoted columns [#filter-on-promoted-columns]
Failed logons by user and source address. In the Authentication class (`3002`), `activity_id` `1` is a logon, `status_id` `2` is a failure, and `user` is the account that tried to log on:
```kusto
['ocsf']
| where class_uid == 3002 and activity_id == 1 and status_id == 2
| summarize failures = count() by ['user.name'], ['src_endpoint.ip'], status_detail
| sort by failures desc
```
| user.name | src\_endpoint.ip | status\_detail | failures |
| --------- | ---------------- | ---------------------------------- | -------- |
| heidi | 10.24.111.174 | Unknown user name or bad password. | 1 |
| dave | 10.30.177.45 | Unknown user name or bad password. | 1 |
| alice | 10.25.217.127 | Unknown user name or bad password. | 1 |
Promoted columns are typed, so numeric comparisons and sums need no conversion. Top destinations by bytes in Network Activity (`4001`):
```kusto
['ocsf']
| where class_uid == 4001
| summarize bytes = sum(['traffic.bytes']) by ['dst_endpoint.ip']
| top 3 by bytes
```
| dst\_endpoint.ip | bytes |
| ---------------- | ------ |
| 198.51.100.182 | 441038 |
| 192.0.2.51 | 405202 |
| 198.51.100.193 | 403470 |
## Read fields from `unmapped` [#read-fields-from-unmapped]
`unmapped` keeps the original OCSF nesting, so you read a field with one index per level. Values inside a map field are dynamic, so convert them with `tostring`, `toint`, or a similar function before you group or compare. The operating system of the device that recorded each logon is under `unmapped` because `device.os` is an object inside an object:
```kusto
['ocsf']
| where class_uid == 3002
| extend os = tostring(['unmapped']['device']['os']['name'])
| summarize events = count() by os
```
| os | events |
| ------------------- | ------ |
| Windows Server 2022 | 15 |
To find which keys each class carries under `unmapped`, list the top-level keys with [`bag_keys`](/apl/scalar-functions/array-functions/bag-keys) and expand them into rows:
```kusto
['ocsf']
| where isnotnull(unmapped)
| extend keys = bag_keys(unmapped)
| mv-expand keys
| summarize events = count() by class_name, key = tostring(keys)
| sort by class_name asc, key asc
```
| class\_name | key | events |
| ----------------- | ------------- | ------ |
| API Activity | actor | 5 |
| API Activity | api | 5 |
| API Activity | cloud | 5 |
| API Activity | metadata | 5 |
| Authentication | device | 15 |
| Authentication | metadata | 15 |
| Detection Finding | evidences | 5 |
| Detection Finding | finding\_info | 5 |
| Network Activity | metadata | 40 |
| Process Activity | device | 10 |
The Detection Finding events also show an array of objects under `unmapped`. Index into it like any other array:
```kusto
['ocsf']
| where class_uid == 2004
| project ['device.hostname'],
rule = tostring(['unmapped']['finding_info']['analytic']['name']),
process = tostring(['unmapped']['evidences'][0]['process']['name'])
```
| device.hostname | rule | process |
| -------------------------- | ---------------- | ------------ |
| wks-014.corp.example.com | Rare destination | rundll32.exe |
| srv-db-02.corp.example.com | Rare destination | rundll32.exe |
| … | … | … |
Querying a map field uses more query-hours than querying a column. If you query an `unmapped` field often, define a [virtual field](/query-data/virtual-fields) for it so your team can reuse it by name.
## Query arrays of objects [#query-arrays-of-objects]
The six promoted arrays, `observables`, `vulnerabilities`, `answers`, `attacks`, `file.hashes`, and `process.file.hashes`, are each stored whole in their own map field. Every element keeps its own attributes, so an observable’s value stays next to its type and a technique stays next to its tactic.
To read one element, index it:
```kusto
['ocsf']
| where class_uid == 2004
| project ['finding_info.title'], ['device.hostname'],
technique = tostring(['attacks'][0]['technique']['uid']),
tactic = tostring(['attacks'][0]['tactic']['name'])
```
| finding\_info.title | device.hostname | technique | tactic |
| ------------------------------ | -------------------------- | --------- | ------------------- |
| Suspicious outbound connection | wks-014.corp.example.com | T1071 | Command and Control |
| Suspicious outbound connection | srv-db-02.corp.example.com | T1071 | Command and Control |
| … | … | … | … |
To work with every element, expand the array into rows with [`mv-expand`](/apl/tabular-operators/mv-expand). For example, list every IP address observable in Detection Findings. In observables, `type_id` `2` is an IP address:
```kusto
['ocsf']
| where class_uid == 2004
| mv-expand observables
| where toint(observables['type_id']) == 2
| summarize findings = count() by ip = tostring(observables['value'])
```
| ip | findings |
| ------------- | -------- |
| 192.0.2.145 | 1 |
| 198.51.100.15 | 1 |
| 192.0.2.221 | 1 |
| 192.0.2.199 | 1 |
| 203.0.113.35 | 1 |
To pull one attribute from every element without expanding rows, use [`array_extract`](/apl/scalar-functions/array-functions/array-extract). It returns an array per event:
```kusto
['ocsf']
| where class_uid == 2004
| extend techniques = array_extract(['attacks'], @'$[*].technique.uid')
| project ['device.hostname'], techniques
```
## Investigate an entity across classes [#investigate-an-entity-across-classes]
Because all classes share one dataset and one vocabulary, one query can follow an entity across event types. Everything the sample recorded about one workstation:
```kusto
['ocsf']
| where ['device.hostname'] == 'wks-014.corp.example.com'
or ['src_endpoint.hostname'] == 'wks-014.corp.example.com'
or ['dst_endpoint.hostname'] == 'wks-014.corp.example.com'
| summarize events = count() by class_name
```
| class\_name | events |
| ----------------- | ------ |
| Detection Finding | 2 |
| Process Activity | 2 |
Events are sparse: each class fills only its own columns. In cross-class queries, expect empty values in columns that a class doesn’t use, and guard with `isnotnull` or `isnotempty` where it matters.
## What’s next [#whats-next]
* [Search OCSF data from Splunk](/splunk/portal/ocsf)
* [Map fields](/apl/data-types/map-fields)
* [APL overview](/apl/introduction)
---
# Send OCSF data to Axiom
Source: https://axiom.co/docs/use-cases/ocsf/send-data
This page explains how to get OCSF events into an Axiom dataset in the shape that the [Axiom OCSF schema](/use-cases/ocsf#the-axiom-ocsf-schema) describes. It covers the middle of the OCSF flow: installing the OCSF for Axiom pack in Cribl Stream, preparing the dataset once, and sending events.
Axiom supports sending OCSF data through Cribl Stream with the OCSF for Axiom pack.
## Prerequisites [#prerequisites]
* [Create an Axiom account](https://app.axiom.co/register).
* A Cribl Stream deployment that receives your OCSF events.
* [Create an advanced API token](/reference/tokens#create-advanced-api-token) that can create datasets and ingest data into them. You can use a separate token with only ingest permission for the Cribl destination.
* Find the [edge deployment](/reference/edge-deployments) of your organization. You send data to its base domain.
## Prepare the dataset [#prepare-the-dataset]
An OCSF dataset needs 23 map fields registered before the first event arrives: the `unmapped` overflow map, the 16 OCSF attributes whose type is a free-form JSON object, and the six promoted arrays of objects, such as `observables` and `attacks`. Without them, Axiom flattens these fields at ingest and their structure is lost. Registering a map field affects only events ingested afterwards, so prepare the dataset before you send data. For more information, see [Map fields](/apl/data-types/map-fields).
The OCSF for Axiom pack ships a script, `scripts/setup-dataset.sh`, that creates the dataset and registers all 23 map fields. It needs only `sh` and `curl`.
1. Download the `.crbl` file of OCSF for Axiom from the [Cribl Packs Dispensary](https://packs.cribl.io/).
2. The `.crbl` file is a gzipped tarball. Extract the script and run it:
```bash
tar -xzf PACK_FILE.crbl scripts/setup-dataset.sh
AXIOM_TOKEN=API_TOKEN DATASET=DATASET_NAME sh scripts/setup-dataset.sh
```
Replace `PACK_FILE` with the name of the downloaded `.crbl` file, for example `cc-stream-axiom-ocsf-1.0.2`.
The script prints one line per map field and ends with:
```
dataset DATASET_NAME created
map field access_result registered
map field application.data registered
…
map field file.hashes registered
map field process.file.hashes registered
dataset DATASET_NAME ready (23 map fields)
```
The script is idempotent and safe to re-run. If the dataset already exists, it prints `dataset DATASET_NAME exists`. Fields already registered print `map field already registered` and are skipped. The script calls `https://api.axiom.co` by default. Set `AXIOM_API` to call another API base URL.
To check the result, go to the Datasets tab, select the dataset, and check that the fields are labeled as map fields. For more information, see [View map fields](/apl/data-types/map-fields#view-map-fields).
A new version of the schema can add map fields. When the pack’s release notes say so, re-run the script from the new version. It registers only the missing fields.
## Send OCSF data from Cribl Stream [#send-ocsf-data-from-cribl-stream]
The OCSF for Axiom pack (pack ID `cc-stream-axiom-ocsf`) takes the OCSF events you already produce in Cribl Stream, for example with the OCSF Post Processor or other OCSF mapping packs, and conforms them to the Axiom OCSF schema. It works with OCSF 1.9.0 and with older producers, such as the OCSF 1.0 and 1.1 events that Amazon Security Lake packs emit. If you already send OCSF to Amazon Security Lake from Cribl, you can route a copy of the same stream to Axiom.
The pack contains routes, one pipeline, global variables, and sample data. It doesn’t contain sources, destinations, credentials, or lookups.
The pack’s `axiom_normalize` route sends every event that has a `class_uid` to the `axiom_normalize` pipeline. All other events go through Cribl’s built-in `passthru` pipeline unchanged. The pipeline has three function groups:
1. **Timestamp normalization.** Detects whether `time` is in seconds, milliseconds, microseconds, or nanoseconds by its magnitude and rewrites it to epoch milliseconds, as OCSF requires. Events without a usable numeric `time` take it from Cribl’s `_time`.
2. **Carrier-field cleanup.** Drops `raw_data`, which Security Lake-oriented packs fill with the whole original event. Strips the transport fields `_raw`, `sourcetype`, `source`, `host`, `index`, and `cribl_*`.
3. **Conform to Axiom schema.** Keeps the 1,636 schema column paths, captures map fields and promoted arrays of objects whole, and moves every other path under `unmapped` with its nesting preserved. Sets `_time` to the event time as an ISO 8601 string.
To see the result on a real event, see [What happens to one event](/use-cases/ocsf#what-happens-to-one-event).
Install **OCSF for Axiom** (`cc-stream-axiom-ocsf`) 1.0.2 or later from the Cribl Packs Dispensary. In Cribl Stream, go to **Processing > Packs**, click **Add Pack > Add from Dispensary**, search for **OCSF for Axiom**, and then click **Add Pack**.
Extract `scripts/setup-dataset.sh` from the pack’s `.crbl` file and run it, as described in [Prepare the dataset](#prepare-the-dataset).
Cribl Stream has no dedicated Axiom destination. The stock Webhook destination sends batched, compressed NDJSON straight to Axiom’s ingest API. In Cribl Stream, create a **Webhook** destination with the following settings.
In **Processing Settings > Post-Processing**, clear **System fields**. By default, Cribl adds `cribl_pipe` to every event, which would land in `unmapped`.
On the Webhook destination, set **Processing Settings > Post-Processing > Pipeline** to the OCSF for Axiom pack. Alternatively, in QuickConnect, connect your source to the destination with the pack as the pipeline. You don’t need a route filter: the pack’s own routes send OCSF events through `axiom_normalize` and pass everything else through unchanged.
Attach the pack to the Axiom destination only, not to a processing pipeline that other destinations share. The pack rewrites events for Axiom, for example it turns `_time` into a string and removes transport fields, and other destinations would receive the same Axiom-shaped events.
In the pack’s pipeline preview, load the shipped samples to see the normalization before data flows:
* `axiom_normalize_post_processor`: 100 synthetic OCSF events across seven classes in the shape the OCSF Post Processor produces, with microsecond `time`, `raw_data` populated, and Splunk carrier fields present.
* `axiom_normalize_time_units`: 42 synthetic events whose `time` is in seconds, milliseconds, microseconds, nanoseconds, numeric strings, ISO strings, or missing. Some carry vendor extension fields that move under `unmapped`.
After data flows, count events by OCSF class:
```kusto
['DATASET_NAME']
| summarize count() by class_uid, class_name
```
`_time` should match the event time, not the ingest time. If events land in 1970 or far in the future, a producer emits an unusual time unit. Report it with a sanitized sample event to [support@axiom.co](mailto:support@axiom.co) or on [Cribl Community Slack](https://cribl-community.slack.com/).
### Optional pipeline settings [#optional-pipeline-settings]
* **Keep `raw_data`.** In the **Carrier-field cleanup** group, turn off the Eval function whose description starts with “Drop `raw_data`”. The value is then stored under `unmapped.raw_data`.
* **Upgrade a modified pack.** Cribl Stream blocks upgrades of a pack you changed locally, for example by turning off the `raw_data` drop. Install the new version under a new ID, re-apply your changes, point the destination’s post-processing pipeline at the new pack, preview the samples, and remove the old pack.
### Why these settings [#why-these-settings]
The pack’s maintainers tested the Webhook settings in Cribl Stream 4.19.2, with one Worker Process on 2 CPUs, against a local mock of Axiom’s ingest API that counts every event it accepts. The events were synthetic OCSF of about 700 bytes each after conforming. These are local results, not Axiom production measurements.
* **Batching.** Requests carried up to about 6,000 of these events, 4 MB uncompressed, within Axiom’s 10,000-event limit. With very small events and no events-per-request limit, Cribl sent requests of over 29,000 events. A limit of `10000` kept requests within Axiom’s 10,000-event limit.
* **Compression.** gzip reduced the bytes sent from 707 to 79 per event, about 9 times fewer. Throughput with and without gzip differed by less than the run-to-run variation.
* **Retries.** With the `430` row, batches answered with `429`, `430`, or `503` were retried, and each of 3,000 events arrived exactly once. Without the `430` row, both rejected batches, 2,000 events in total, were dropped.
* **Persistent Queue.** During a sustained `503` outage, 400,000 events spilled about 795 MB to disk. After recovery, all 400,000 were delivered, with 2 duplicates, in each of 2 runs.
* **Pipeline cost.** In 3 runs of 100,000 events each, the pack roughly doubled CPU time per event for the whole container: 80 to 93 microseconds, against 40 to 48 without it. End-to-end throughput with one Worker Process averaged 10,000 to 12,000 events per second, against about 19,000 without the pack. Add Worker Processes for higher volume.
## What’s next [#whats-next]
* [Query OCSF data](/use-cases/ocsf/query)
* [Search OCSF data from Splunk](/splunk/portal/ocsf)
---
# arg_max
Source: https://axiom.co/docs/apl/aggregation-function/arg-max
The `arg_max` aggregation in APL helps you identify the row with the maximum value for an expression and return additional fields from that record. Use `arg_max` when you want to determine key details associated with a row where the expression evaluates to the maximum value. If you group your data, `arg_max` finds the row within each group where a particular expression evaluates to the maximum value.
This aggregation is particularly useful in scenarios like the following:
* Pinpoint the slowest HTTP requests in log data and retrieve associated details (like URL, status code, and user agent) for the same row.
* Identify the longest span durations in OpenTelemetry traces with additional context (like span name, trace ID, and attributes) for the same row.
* Highlight the highest severity security alerts in logs along with relevant metadata (such as alert type, source, and timestamp) for the same row.
## Usage [#usage]
### Syntax [#syntax]
```kusto
| summarize arg_max(expression, field1[, field2, ...])
```
### Parameters [#parameters]
| Parameter | Description |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `expression` | The expression whose maximum value determines the selected record. |
| `field1, field2` | The additional fields to retrieve from the record with the maximum numeric value. Use `*` as a wildcard to return all fields from the row. |
The wildcard `*` is useful to return all fields from the row with the maximum value, but it increases query complexity and decreases performance.
### Returns [#returns]
Returns a row where the expression evaluates to the maximum value for each group (or the entire dataset if no grouping is specified), containing the fields specified in the query.
### Name fields [#name-fields]
You can name fields in the parameters of `arg_max` using the syntax `arg_max(name1=expression, name2=field1)`. This specifies the field names that appear in the output.
**Query**
```kusto
['otel-demo-traces']
| summarize arg_max(duration, longestSpan=span_id), arg_max(numEvents=array_length(events), spanWithMostEvents=span_id)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20arg_max\(duration%2C%20longestSpan%3Dspan_id\)%2C%20arg_max\(numEvents%3Darray_length\(events\)%2C%20spanWithMostEvents%3Dspan_id\)%22%7D)
**Output**
| duration | longestSpan | numEvents | spanWithMostEvents |
| ---------------- | ---------------- | --------- | ------------------ |
| `5m0.004487127s` | 1a9f979bb25f6bbd | 408 | db13ffc3394905b5 |
## Use case examples [#use-case-examples]
Find the slowest path for each HTTP method in the `['sample-http-logs']` dataset.
**Query**
```kusto
['sample-http-logs']
| summarize arg_max(req_duration_ms, uri) by method
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20arg_max\(req_duration_ms%2C%20uri\)%20by%20method%22%7D)
**Output**
| uri | method | req\_duration\_ms |
| ------------- | ------ | ----------------- |
| /home | GET | 1200 |
| /api/products | POST | 2500 |
This query identifies the slowest path for each HTTP method.
Identify the span with the longest duration for each service in the `['otel-demo-traces']` dataset.
**Query**
```kusto
['otel-demo-traces']
| summarize arg_max(duration, span_id, trace_id) by ['service.name']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20arg_max\(duration%2C%20span_id%2C%20trace_id\)%20by%20%5B'service.name'%5D%22%7D)
**Output**
| service.name | span\_id | trace\_id | duration |
| --------------- | -------- | --------- | -------- |
| frontend | span123 | trace456 | 3s |
| checkoutservice | span789 | trace012 | 5s |
This query identifies the span with the longest duration for each service, returning the `span_id`, `trace_id`, and `duration`.
Find the highest status code for each country in the `['sample-http-logs']` dataset.
**Query**
```kusto
['sample-http-logs']
| summarize arg_max(toint(status), uri) by ['geo.country']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20arg_max\(toint\(status\)%2C%20uri\)%20by%20%5B'geo.country'%5D%22%7D)
**Output**
| geo.country | uri | status |
| ----------- | ---------- | ------ |
| USA | /admin | 500 |
| Canada | /dashboard | 503 |
This query identifies the URI with the highest status code for each country.
## List of related aggregations [#list-of-related-aggregations]
* [arg\_min](/apl/aggregation-function/arg-min): Retrieves the record with the minimum value for a numeric field.
* [max](/apl/aggregation-function/max): Retrieves the maximum value for a numeric field but doesn’t return additional fields.
* [percentile](/apl/aggregation-function/percentile): Provides the value at a specific percentile of a numeric field.
## Other query languages [#other-query-languages]
Splunk SPL doesn’t have an equivalent to `arg_max`. You can use `stats` with a combination of `max` and `by` clauses to evaluate the maximum value of a single numberic field. APL provides a dedicated `arg_max` aggregation that evaluates expressions.
```sql Splunk example
| stats max(req_duration_ms) as max_duration by id, uri
```
```kusto APL equivalent
['sample-http-logs']
| summarize arg_max(req_duration_ms, id, uri)
```
In ANSI SQL, you typically use a subquery to find the maximum value and then join it back to the original table to retrieve additional fields. APL’s `arg_max` provides a more concise and efficient alternative.
```sql SQL example
WITH MaxValues AS (
SELECT id, MAX(req_duration_ms) as max_duration
FROM sample_http_logs
GROUP BY id
)
SELECT logs.id, logs.uri, MaxValues.max_duration
FROM sample_http_logs logs
JOIN MaxValues
ON logs.id = MaxValues.id;
```
```kusto APL equivalent
['sample-http-logs']
| summarize arg_max(req_duration_ms, id, uri)
```
---
# arg_min
Source: https://axiom.co/docs/apl/aggregation-function/arg-min
The `arg_min` aggregation in APL allows you to identify the row in a dataset where an expression evaluates to the minimum value. You can use this to retrieve other associated fields in the same row, making it particularly useful for pinpointing details about the smallest value in large datasets. If you group your data, `arg_min` finds the row within each group where a particular expression evaluates to the minimum value.
This aggregation is particularly useful in scenarios like the following:
* Pinpoint the shortest HTTP requests in log data and retrieve associated details (like URL, status code, and user agent) for the same row.
* Identify the fastest span durations in OpenTelemetry traces with additional context (like span name, trace ID, and attributes) for the same row.
* Highlight the lowest severity security alerts in logs along with relevant metadata (such as alert type, source, and timestamp) for the same row.
## Usage [#usage]
### Syntax [#syntax]
```kusto
| summarize arg_min(expression, field1, ..., fieldN)
```
### Parameters [#parameters]
* `expression`: The expression to evaluate for the minimum value.
* `field1, ..., fieldN`: Additional fields to return from the row with the minimum value. Use `*` as a wildcard to return all fields from the row.
The wildcard `*` is useful to return all fields from the row with the minimum value, but it increases query complexity and decreases performance.
### Returns [#returns]
Returns a row where the expression evaluates to the minimum value for each group (or the entire dataset if no grouping is specified), containing the fields specified in the query.
### Name fields [#name-fields]
You can name fields in the parameters of `arg_min` using the syntax `arg_min(name1=expression, name2=field1)`. This specifies the field names that appear in the output.
**Query**
```kusto
['otel-demo-traces']
| summarize arg_min(duration, longestSpan=span_id), arg_min(numEvents=array_length(events), spanWithMostEvents=span_id)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20arg_min\(duration%2C%20longestSpan%3Dspan_id\)%2C%20arg_min\(numEvents%3Darray_length\(events\)%2C%20spanWithMostEvents%3Dspan_id\)%22%7D)
**Output**
| duration | longestSpan | numEvents | spanWithMostEvents |
| -------- | ---------------- | --------- | ------------------ |
| `190ns` | 1a9f979bb25f6bbd | 1 | db13ffc3394905b5 |
## Use case examples [#use-case-examples]
You can use `arg_min` to identify the path with the shortest duration and its associated details for each method.
**Query**
```kusto
['sample-http-logs']
| summarize arg_min(req_duration_ms, uri) by method
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20arg_min\(req_duration_ms%2C%20uri\)%20by%20method%22%7D)
**Output**
| req\_duration\_ms | uri | method |
| ----------------- | ---------- | ------ |
| 0.1 | /api/login | POST |
This query identifies the paths with the shortest duration for each method and provides details about the path.
Use `arg_min` to find the span with the shortest duration for each service and retrieve its associated details.
**Query**
```kusto
['otel-demo-traces']
| summarize arg_min(duration, trace_id, span_id, kind) by ['service.name']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20arg_min\(duration%2C%20trace_id%2C%20span_id%2C%20kind\)%20by%20%5B'service.name'%5D%22%7D)
**Output**
| duration | trace\_id | span\_id | service.name | kind |
| -------- | --------- | -------- | ------------ | ------ |
| 00:00:01 | abc123 | span456 | frontend | server |
This query identifies the span with the shortest duration for each service along with its metadata.
Find the lowest status code for each country in the `['sample-http-logs']` dataset.
**Query**
```kusto
['sample-http-logs']
| summarize arg_min(toint(status), uri) by ['geo.country']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20arg_min\(toint\(status\)%2C%20uri\)%20by%20%5B'geo.country'%5D%22%7D)
**Output**
| geo.country | uri | status |
| ----------- | ---------- | ------ |
| USA | /admin | 200 |
| Canada | /dashboard | 201 |
This query identifies the URI with the lowest status code for each country.
## List of related aggregations [#list-of-related-aggregations]
* [arg\_max](/apl/aggregation-function/arg-max): Returns the row with the maximum value for a numeric field, useful for finding peak metrics.
* [min](/apl/aggregation-function/min): Returns only the minimum value of a numeric field without additional fields.
* [percentile](/apl/aggregation-function/percentile): Provides the value at a specific percentile of a numeric field.
## Other query languages [#other-query-languages]
Splunk SPL doesn’t have an equivalent to `arg_min`. You can use `stats` with a combination of `values` and `first` clauses to evaluate the minimum value of a single numberic field. APL provides a dedicated `arg_min` aggregation that evaluates expressions.
```sql Splunk example
| stats min(req_duration_ms) as minDuration by id
| where req_duration_ms=minDuration
```
```kusto APL equivalent
['sample-http-logs']
| summarize arg_min(req_duration_ms, id, uri)
```
In ANSI SQL, achieving similar functionality often requires a combination of `MIN`, `GROUP BY`, and `JOIN` to retrieve the associated fields. APL's `arg_min` eliminates the need for multiple steps by directly returning the row with the minimum value.
```sql SQL example
SELECT id, uri
FROM sample_http_logs
WHERE req_duration_ms = (
SELECT MIN(req_duration_ms)
FROM sample_http_logs
);
```
```kusto APL equivalent
['sample-http-logs']
| summarize arg_min(req_duration_ms, id, uri)
```
---
# avg
Source: https://axiom.co/docs/apl/aggregation-function/avg
The `avg` aggregation in APL calculates the average value of a numeric field across a set of records. You can use this aggregation when you need to determine the mean value of numerical data, such as request durations, response times, or other performance metrics. It’s useful in scenarios such as performance analysis, trend identification, and general statistical analysis.
When to use `avg`:
* When you want to analyze the average of numeric values over a specific time range or set of data.
* For comparing trends, like average request duration or latency across HTTP requests.
* To provide insight into system or user performance, such as the average duration of transactions in a service.
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize avg(ColumnName) [by GroupingColumn]
```
### Parameters [#parameters]
* **ColumnName**: The numeric field you want to calculate the average of.
* **GroupingColumn** (optional): A column to group the results by. If not specified, the average is calculated over all records.
### Returns [#returns]
* A table with the average value for the specified field, optionally grouped by another column.
## Use case examples [#use-case-examples]
This example calculates the average request duration for HTTP requests, grouped by status.
**Query**
```kusto
['sample-http-logs']
| summarize avg(req_duration_ms) by status
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20summarize%20avg\(req_duration_ms\)%20by%20status%22%7D)
**Output**
| status | avg\_req\_duration\_ms |
| ------ | ---------------------- |
| 200 | 350.4 |
| 404 | 150.2 |
This query calculates the average request duration (in milliseconds) for each HTTP status code.
This example calculates the average span duration for each service to analyze performance across services.
**Query**
```kusto
['otel-demo-traces']
| summarize avg(duration) by ['service.name']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%5Cn%7C%20summarize%20avg\(duration\)%20by%20%5B'service.name'%5D%22%7D)
**Output**
| service.name | avg\_duration |
| ------------ | ------------- |
| frontend | 500ms |
| cartservice | 250ms |
This query calculates the average duration of spans for each service.
In security logs, you can calculate the average request duration by country to analyze regional performance trends.
**Query**
```kusto
['sample-http-logs']
| summarize avg(req_duration_ms) by ['geo.country']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20summarize%20avg\(req_duration_ms\)%20by%20%5B'geo.country'%5D%22%7D)
**Output**
| geo.country | avg\_req\_duration\_ms |
| ----------- | ---------------------- |
| US | 400.5 |
| DE | 250.3 |
This query calculates the average request duration for each country from where the requests originated.
## List of related aggregations [#list-of-related-aggregations]
* [**sum**](/apl/aggregation-function/sum): Use `sum` to calculate the total of a numeric field. This is useful when you want the total of values rather than their average.
* [**count**](/apl/aggregation-function/count): The `count` function returns the total number of records. It’s useful when you want to count occurrences rather than averaging numerical values.
* [**min**](/apl/aggregation-function/min): The `min` function returns the minimum value of a numeric field. Use this when you’re interested in the smallest value in your dataset.
* [**max**](/apl/aggregation-function/max): The `max` function returns the maximum value of a numeric field. This is useful for finding the largest value in the data.
* [**stdev**](/apl/aggregation-function/stdev): This function calculates the standard deviation of a numeric field, providing insight into how spread out the data is around the mean.
## Other query languages [#other-query-languages]
In Splunk SPL, the `avg` function works similarly, but the syntax differs slightly. Here’s how to write the equivalent query in APL.
```sql Splunk example
| stats avg(req_duration_ms) by status
```
```kusto APL equivalent
['sample-http-logs']
| summarize avg(req_duration_ms) by status
```
In ANSI SQL, the `avg` aggregation is used similarly, but APL has a different syntax for structuring the query.
```sql SQL example
SELECT status, AVG(req_duration_ms)
FROM sample_http_logs
GROUP BY status
```
```kusto APL equivalent
['sample-http-logs']
| summarize avg(req_duration_ms) by status
```
---
# avgif
Source: https://axiom.co/docs/apl/aggregation-function/avgif
The `avgif` aggregation function in APL allows you to calculate the average value of a field, but only for records that satisfy a given condition. This function is particularly useful when you need to perform a filtered aggregation, such as finding the average response time for requests that returned a specific status code or filtering by geographic regions. The `avgif` function is highly valuable in scenarios like log analysis, performance monitoring, and anomaly detection, where focusing on subsets of data can provide more accurate insights.
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize avgif(expr, predicate) by grouping_field
```
### Parameters [#parameters]
* **`expr`**: The field for which you want to calculate the average.
* **`predicate`**: A boolean condition that filters which records are included in the calculation.
* **`grouping_field`**: (Optional) A field by which you want to group the results.
### Returns [#returns]
The function returns the average of the values from the `expr` field for the records that satisfy the `predicate`. If no records match the condition, the result is `null`.
## Use case examples [#use-case-examples]
In this example, you calculate the average request duration for HTTP status 200 in different cities.
**Query**
```kusto
['sample-http-logs']
| summarize avgif(req_duration_ms, status == "200") by ['geo.city']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20summarize%20avgif%28req_duration_ms%2C%20status%20%3D%3D%20%22200%22%29%20by%20%5B%27geo.city%27%5D%22%7D)
**Output**
| geo.city | avg\_req\_duration\_ms |
| -------- | ---------------------- |
| New York | 325 |
| London | 400 |
| Tokyo | 275 |
This query calculates the average request duration (`req_duration_ms`) for HTTP requests that returned a status of 200 (`status == "200"`), grouped by the city where the request originated (`geo.city`).
In this example, you calculate the average span duration for traces that ended with HTTP status 500.
**Query**
```kusto
['otel-demo-traces']
| summarize avgif(duration, status == "500") by ['service.name']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27otel-demo-traces%27%5D%20%7C%20summarize%20avgif%28duration%2C%20status%20%3D%3D%20%22500%22%29%20by%20%5B%27service.name%27%5D%22%7D)
**Output**
| service.name | avg\_duration |
| --------------- | ------------- |
| checkoutservice | 500ms |
| frontend | 600ms |
| cartservice | 475ms |
This query calculates the average span duration (`duration`) for traces where the status code is 500 (`status == "500"`), grouped by the service name (`service.name`).
In this example, you calculate the average request duration for failed HTTP requests (status code 400 or higher) by country.
**Query**
```kusto
['sample-http-logs']
| summarize avgif(req_duration_ms, toint(status) >= 400) by ['geo.country']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20summarize%20avgif%28req_duration_ms%2C%20toint%28status%29%20%3E%3D%20400%29%20by%20%5B%27geo.country%27%5D%22%7D)
**Output**
| geo.country | avg\_req\_duration\_ms |
| ----------- | ---------------------- |
| USA | 450 |
| Canada | 500 |
| Germany | 425 |
This query calculates the average request duration (`req_duration_ms`) for failed HTTP requests (`status >= 400`), grouped by the country of origin (`geo.country`).
## List of related aggregations [#list-of-related-aggregations]
* [**minif**](/apl/aggregation-function/minif): Returns the minimum value of an expression, filtered by a predicate. Use when you want to find the smallest value for a subset of data.
* [**maxif**](/apl/aggregation-function/maxif): Returns the maximum value of an expression, filtered by a predicate. Use when you are looking for the largest value within specific conditions.
* [**countif**](/apl/aggregation-function/countif): Counts the number of records that match a condition. Use when you want to know how many records meet a specific criterion.
* [**sumif**](/apl/aggregation-function/sumif): Sums the values of a field that match a given condition. Ideal for calculating the total of a subset of data.
## Other query languages [#other-query-languages]
In Splunk, you achieve similar functionality using the combination of a `stats` function with conditional filtering. In APL, `avgif` provides this filtering inline as part of the aggregation function, which can simplify your queries.
```sql Splunk example
| stats avg(req_duration_ms) by id where status = "200"
```
```kusto APL equivalent
['sample-http-logs']
| summarize avgif(req_duration_ms, status == "200") by id
```
In ANSI SQL, you can use a `CASE` statement inside an `AVG` function to achieve similar behavior. APL simplifies this with `avgif`, allowing you to specify the condition directly.
```sql SQL example
SELECT id, AVG(CASE WHEN status = '200' THEN req_duration_ms ELSE NULL END)
FROM sample_http_logs
GROUP BY id
```
```kusto APL equivalent
['sample-http-logs']
| summarize avgif(req_duration_ms, status == "200") by id
```
---
# count
Source: https://axiom.co/docs/apl/aggregation-function/count
The `count` aggregation in APL returns the total number of records in a dataset or the total number of records that match specific criteria. This function is useful when you need to quantify occurrences, such as counting log entries, user actions, or security events.
When to use `count`:
* To count the total number of events in log analysis, such as the number of HTTP requests or errors.
* To monitor system usage, such as the number of transactions or API calls.
* To identify security incidents by counting failed login attempts or suspicious activities.
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize count() [by GroupingColumn]
```
### Parameters [#parameters]
* **GroupingColumn** (optional): A column to group the count results by. If not specified, the total number of records across the dataset is returned.
### Returns [#returns]
* A table with the count of records for the entire dataset or grouped by the specified column.
## Use case examples [#use-case-examples]
In log analysis, you can count the number of HTTP requests by status to get a sense of how many requests result in different HTTP status codes.
**Query**
```kusto
['sample-http-logs']
| summarize count() by status
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20summarize%20count\(\)%20by%20status%22%7D)
**Output**
| status | count |
| ------ | ----- |
| 200 | 1500 |
| 404 | 200 |
This query counts the total number of HTTP requests for each status code in the logs.
For OpenTelemetry traces, you can count the total number of spans for each service, which helps you monitor the distribution of requests across services.
**Query**
```kusto
['otel-demo-traces']
| summarize count() by ['service.name']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%5Cn%7C%20summarize%20count\(\)%20by%20%5B'service.name'%5D%22%7D)
**Output**
| service.name | count |
| ------------ | ----- |
| frontend | 1000 |
| cartservice | 500 |
This query counts the number of spans for each service in the OpenTelemetry traces dataset.
In security logs, you can count the number of requests by country to identify where the majority of traffic or suspicious activity originates.
**Query**
```kusto
['sample-http-logs']
| summarize count() by ['geo.country']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20summarize%20count\(\)%20by%20%5B'geo.country'%5D%22%7D)
**Output**
| geo.country | count |
| ----------- | ----- |
| US | 3000 |
| DE | 500 |
This query counts the number of requests originating from each country.
## List of related aggregations [#list-of-related-aggregations]
* [**sum**](/apl/aggregation-function/sum): Use `sum` to calculate the total sum of a numeric field, as opposed to counting the number of records.
* [**avg**](/apl/aggregation-function/avg): The `avg` function calculates the average of a numeric field. Use it when you want to determine the mean value of data instead of the count.
* [**min**](/apl/aggregation-function/min): The `min` function returns the minimum value of a numeric field, helping to identify the smallest value in a dataset.
* [**max**](/apl/aggregation-function/max): The `max` function returns the maximum value of a numeric field, useful for identifying the largest value.
* [**countif**](/apl/aggregation-function/countif): The `countif` function allows you to count only records that meet specific conditions, giving you more flexibility in your count queries.
## Other query languages [#other-query-languages]
In Splunk SPL, the `count` function works similarly to APL, but the syntax differs slightly.
```sql Splunk example
| stats count by status
```
```kusto APL equivalent
['sample-http-logs']
| summarize count() by status
```
In ANSI SQL, the `count` function works similarly, but APL uses different syntax for querying.
```sql SQL example
SELECT status, COUNT(*)
FROM sample_http_logs
GROUP BY status
```
```kusto APL equivalent
['sample-http-logs']
| summarize count() by status
```
---
# countif
Source: https://axiom.co/docs/apl/aggregation-function/countif
The `countif` aggregation function in Axiom Processing Language (APL) counts the number of records that meet a specified condition. You can use this aggregation to filter records based on a specific condition and return a count of matching records. This is particularly useful for log analysis, security audits, and tracing events when you need to isolate and count specific data subsets.
Use `countif` when you want to count occurrences of certain conditions, such as HTTP status codes, errors, or actions in telemetry traces.
## Usage [#usage]
### Syntax [#syntax]
```kusto
countif(condition)
```
### Parameters [#parameters]
* **condition**: A boolean expression that filters the records based on a condition. Only records where the condition evaluates to `true` are counted.
### Returns [#returns]
The function returns the number of records that match the specified condition.
## Use case examples [#use-case-examples]
In log analysis, you might want to count how many HTTP requests returned a 500 status code to detect server errors.
**Query**
```kusto
['sample-http-logs']
| summarize countif(status == '500')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20countif\(status%20%3D%3D%20'500'\)%22%7D)
**Output**
| count\_errors |
| ------------- |
| 72 |
This query counts the number of HTTP requests with a `500` status, helping you identify how many server errors occurred.
In OpenTelemetry traces, you might want to count how many requests were initiated by the client service kind.
**Query**
```kusto
['otel-demo-traces']
| summarize countif(kind == 'client')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20countif\(kind%20%3D%3D%20'client'\)%22%7D)
**Output**
| count\_client\_kind |
| ------------------- |
| 345 |
This query counts how many requests were initiated by the `client` service kind, providing insight into the volume of client-side traffic.
In security logs, you might want to count how many HTTP requests originated from a specific city, such as New York.
**Query**
```kusto
['sample-http-logs']
| summarize countif(['geo.city'] == 'New York')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20countif\(%5B'geo.city'%5D%20%3D%3D%20'New%20York'\)%22%7D)
**Output**
| count\_nyc\_requests |
| -------------------- |
| 87 |
This query counts how many HTTP requests originated from New York, which can help detect traffic from a particular location for security analysis.
## List of related aggregations [#list-of-related-aggregations]
* [**count**](/apl/aggregation-function/count): Counts all records in a dataset without applying a condition. Use this when you need the total count of records, regardless of any specific condition.
* [**sumif**](/apl/aggregation-function/sumif): Adds up the values of a field for records that meet a specific condition. Use `sumif` when you want to sum values based on a filter.
* [**dcountif**](/apl/aggregation-function/dcountif): Counts distinct values of a field for records that meet a condition. This is helpful when you need to count unique occurrences.
* [**avgif**](/apl/aggregation-function/avgif): Calculates the average value of a field for records that match a condition, useful for performance monitoring.
* [**maxif**](/apl/aggregation-function/maxif): Returns the maximum value of a field for records that meet a condition. Use this when you want to find the highest value in filtered data.
## Other query languages [#other-query-languages]
In Splunk SPL, conditional counting is typically done using the `eval` function combined with `stats`. APL provides a more streamlined approach with the `countif` function, which performs conditional counting directly.
```sql Splunk example
| stats count(eval(status="500")) AS error_count
```
```kusto APL equivalent
['sample-http-logs']
| summarize countif(status == '500')
```
In ANSI SQL, conditional counting is achieved by using the `COUNT` function with a `CASE` statement. In APL, `countif` simplifies this process by offering a direct approach to conditional counting.
```sql SQL example
SELECT COUNT(CASE WHEN status = '500' THEN 1 END) AS error_count
FROM sample_http_logs
```
```kusto APL equivalent
['sample-http-logs']
| summarize countif(status == '500')
```
---
# dcount
Source: https://axiom.co/docs/apl/aggregation-function/dcount
The `dcount` aggregation function in Axiom Processing Language (APL) counts the distinct values in a column. This function is essential when you need to know the number of unique values, such as counting distinct users, unique requests, or distinct error codes in log files.
Use `dcount` for analyzing datasets where it’s important to identify the number of distinct occurrences, such as unique IP addresses in security logs, unique user IDs in app logs, or unique trace IDs in OpenTelemetry traces.
The `dcount` aggregation in APL is a statistical aggregation that returns estimated results. The estimation comes with the benefit of speed at the expense of accuracy. This means that `dcount` is fast and light on resources even on a large or high-cardinality dataset, but it doesn’t provide precise results.
## Usage [#usage]
### Syntax [#syntax]
```kusto
dcount(column_name)
```
### Parameters [#parameters]
* **column\_name**: The name of the column for which you want to count distinct values.
### Returns [#returns]
The function returns the count of distinct values found in the specified column.
## Use case examples [#use-case-examples]
In log analysis, you can count how many distinct users accessed the service.
**Query**
```kusto
['sample-http-logs']
| summarize dcount(id)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20dcount\(id\)%22%7D)
**Output**
| distinct\_users |
| --------------- |
| 45 |
This query counts the distinct values in the `id` field, representing the number of unique users who accessed the system.
In OpenTelemetry traces, you can count how many unique trace IDs are recorded.
**Query**
```kusto
['otel-demo-traces']
| summarize dcount(trace_id)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20dcount\(trace_id\)%22%7D)
**Output**
| distinct\_traces |
| ---------------- |
| 321 |
This query counts the distinct trace IDs in the dataset, helping you determine how many unique traces are being captured.
In security logs, you can count how many distinct IP addresses were logged.
**Query**
```kusto
['sample-http-logs']
| summarize dcount(['geo.city'])
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20dcount\(%5B'geo.city'%5D\)%22%7D)
**Output**
| distinct\_cities |
| ---------------- |
| 35 |
This query counts the number of distinct cities recorded in the logs, which helps analyze the geographic distribution of traffic.
## List of related aggregations [#list-of-related-aggregations]
* [**count**](/apl/aggregation-function/count): Counts the total number of records in the dataset, including duplicates. Use it when you need to know the overall number of records.
* [**countif**](/apl/aggregation-function/countif): Counts records that match a specific condition. Use `countif` when you want to count records based on a filter or condition.
* [**dcountif**](/apl/aggregation-function/dcountif): Counts the distinct values in a column but only for records that meet a condition. It’s useful when you need a filtered distinct count.
* [**sum**](/apl/aggregation-function/sum): Sums the values in a column. Use this when you need to add up values rather than counting distinct occurrences.
* [**avg**](/apl/aggregation-function/avg): Calculates the average value for a column. Use this when you want to find the average of a specific numeric field.
## Other query languages [#other-query-languages]
In Splunk SPL, you can count distinct values using the `dc` function within the `stats` command. In APL, the `dcount` function offers similar functionality.
```sql Splunk example
| stats dc(user_id) AS distinct_users
```
```kusto APL equivalent
['sample-http-logs']
| summarize dcount(id)
```
In ANSI SQL, distinct counting is typically done using `COUNT` with the `DISTINCT` keyword. In APL, `dcount` provides a direct and efficient way to count distinct values.
```sql SQL example
SELECT COUNT(DISTINCT user_id) AS distinct_users
FROM sample_http_logs
```
```kusto APL equivalent
['sample-http-logs']
| summarize dcount(id)
```
---
# dcountif
Source: https://axiom.co/docs/apl/aggregation-function/dcountif
The `dcountif` aggregation function in Axiom Processing Language (APL) counts the distinct values in a column that meet a specific condition. This is useful when you want to filter records and count only the unique occurrences that satisfy a given criterion.
Use `dcountif` in scenarios where you need a distinct count but only for a subset of the data, such as counting unique users from a specific region, unique error codes for specific HTTP statuses, or distinct traces that match a particular service type.
## Usage [#usage]
### Syntax [#syntax]
```kusto
dcountif(column_name, condition)
```
### Parameters [#parameters]
* **column\_name**: The name of the column for which you want to count distinct values.
* **condition**: A boolean expression that filters the records. Only records that meet the condition will be included in the distinct count.
### Returns [#returns]
The function returns the count of distinct values that meet the specified condition.
## Use case examples [#use-case-examples]
In log analysis, you might want to count how many distinct users accessed the service and received a successful response (HTTP status 200).
**Query**
```kusto
['sample-http-logs']
| summarize dcountif(id, status == '200')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20dcountif\(id%2C%20status%20%3D%3D%20'200'\)%22%7D)
**Output**
| distinct\_successful\_users |
| --------------------------- |
| 50 |
This query counts the distinct users (`id` field) who received a successful HTTP response (status 200), helping you understand how many unique users had successful requests.
In OpenTelemetry traces, you might want to count how many unique trace IDs are recorded for a specific service, such as `frontend`.
**Query**
```kusto
['otel-demo-traces']
| summarize dcountif(trace_id, ['service.name'] == 'frontend')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20dcountif\(trace_id%2C%20%5B'service.name'%5D%20%3D%3D%20'frontend'\)%22%7D)
**Output**
| distinct\_frontend\_traces |
| -------------------------- |
| 123 |
This query counts the number of distinct trace IDs that belong to the `frontend` service, providing insight into the volume of unique traces for that service.
In security logs, you might want to count how many unique IP addresses were logged for requests that resulted in a 403 status (forbidden access).
**Query**
```kusto
['sample-http-logs']
| summarize dcountif(['geo.city'], status == '403')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20dcountif\(%5B'geo.city'%5D%2C%20status%20%3D%3D%20'403'\)%22%7D)
**Output**
| distinct\_cities\_forbidden |
| --------------------------- |
| 20 |
This query counts the number of distinct cities (`geo.city` field) where requests resulted in a `403` status, helping you identify potential unauthorized access attempts from different regions.
## List of related aggregations [#list-of-related-aggregations]
* [**dcount**](/apl/aggregation-function/dcount): Counts distinct values without applying any condition. Use this when you need to count unique values across the entire dataset.
* [**countif**](/apl/aggregation-function/countif): Counts records that match a specific condition, without focusing on distinct values. Use this when you need to count records based on a filter.
* [**dcountif**](/apl/aggregation-function/dcountif): Use this function to get a distinct count for records that meet a condition. It combines both filtering and distinct counting.
* [**sumif**](/apl/aggregation-function/sumif): Sums values in a column for records that meet a condition. This is useful when you need to sum data points after filtering.
* [**avgif**](/apl/aggregation-function/avgif): Calculates the average value of a column for records that match a condition. Use this when you need to find the average based on a filter.
## Other query languages [#other-query-languages]
In Splunk SPL, counting distinct values conditionally is typically achieved using a combination of `eval` and `dc` in the `stats` function. APL simplifies this with the `dcountif` function, which handles both filtering and distinct counting in a single step.
```sql Splunk example
| stats dc(eval(status="200")) AS distinct_successful_users
```
```kusto APL equivalent
['sample-http-logs']
| summarize dcountif(id, status == '200')
```
In ANSI SQL, conditional distinct counting can be done using a combination of `COUNT(DISTINCT)` and `CASE`. APL's `dcountif` function provides a more concise and readable way to handle conditional distinct counting.
```sql SQL example
SELECT COUNT(DISTINCT CASE WHEN status = '200' THEN user_id END) AS distinct_successful_users
FROM sample_http_logs
```
```kusto APL equivalent
['sample-http-logs']
| summarize dcountif(id, status == '200')
```
---
# histogram
Source: https://axiom.co/docs/apl/aggregation-function/histogram
The `histogram` aggregation in APL allows you to create a histogram that groups numeric values into intervals or “bins.” This is useful for visualizing the distribution of data, such as the frequency of response times, request durations, or other continuous numerical fields. You can use it to analyze patterns and trends in datasets like logs, traces, or metrics. It’s especially helpful when you need to summarize a large volume of data into a digestible form, providing insights on the distribution of values.
The `histogram` aggregation is ideal for identifying peaks, valleys, and outliers in your data. For example, you can analyze the distribution of request durations in web server logs or span durations in OpenTelemetry traces to understand performance bottlenecks.
The `histogram` aggregation in APL is a statistical aggregation that returns estimated results. The estimation comes with the benefit of speed at the expense of accuracy. This means that `histogram` is fast and light on resources even on a large or high-cardinality dataset, but it doesn’t provide precise results.
## Usage [#usage]
### Syntax [#syntax]
```kusto
histogram(numeric_field, number_of_bins)
```
### Parameters [#parameters]
* `numeric_field`: The numeric field to create a histogram for. For example, request duration or span duration.
* `number_of_bins`: The number of bins (intervals) to use for grouping the numeric values.
### Returns [#returns]
The `histogram` aggregation returns a table where each row represents a bin, along with the number of occurrences (counts) that fall within each bin.
## Use case examples [#use-case-examples]
You can use the `histogram` aggregation to analyze the distribution of request durations in web server logs.
**Query**
```kusto
['sample-http-logs']
| summarize histogram(req_duration_ms, 100) by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20histogram\(req_duration_ms%2C%20100\)%20by%20bin_auto\(_time\)%22%7D)
**Output**
| req\_duration\_ms\_bin | count |
| ---------------------- | ----- |
| 0 | 50 |
| 100 | 200 |
| 200 | 120 |
This query creates a histogram that groups request durations into bins of 100 milliseconds and shows the count of requests in each bin. It helps you visualize how frequently requests fall within certain duration ranges.
In OpenTelemetry traces, you can use the `histogram` aggregation to analyze the distribution of span durations.
**Query**
```kusto
['otel-demo-traces']
| summarize histogram(duration, 100) by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20histogram\(duration%2C%20100\)%20by%20bin_auto\(_time\)%22%7D)
**Output**
| duration\_bin | count |
| ------------- | ----- |
| 0.1s | 30 |
| 0.2s | 120 |
| 0.3s | 50 |
This query groups the span durations into 100ms intervals, making it easier to spot latency issues in your traces.
In security logs, the `histogram` aggregation helps you understand the frequency distribution of request durations to detect anomalies or attacks.
**Query**
```kusto
['sample-http-logs']
| where status == '200'
| summarize histogram(req_duration_ms, 50) by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20where%20status%20%3D%3D%20'200'%20%7C%20summarize%20histogram\(req_duration_ms%2C%2050\)%20by%20bin_auto\(_time\)%22%7D)
**Output**
| req\_duration\_ms\_bin | count |
| ---------------------- | ----- |
| 0 | 150 |
| 50 | 400 |
| 100 | 100 |
This query analyzes the request durations for HTTP 200 (Success) responses, helping you identify patterns in security-related events.
## List of related aggregations [#list-of-related-aggregations]
* [**percentile**](/apl/aggregation-function/percentile): Use `percentile` when you need to find the specific value below which a percentage of observations fall, which can provide more precise distribution analysis.
* [**avg**](/apl/aggregation-function/avg): Use `avg` for calculating the average value of a numeric field, useful when you are more interested in the central tendency rather than distribution.
* [**sum**](/apl/aggregation-function/sum): The `sum` function adds up the total values in a numeric field, helpful for determining overall totals.
* [**count**](/apl/aggregation-function/count): Use `count` when you need a simple tally of rows or events, often in conjunction with `histogram` for more basic summarization.
## Other query languages [#other-query-languages]
In Splunk SPL, a similar operation to APL's `histogram` is the `timechart` or `histogram` command, which groups events into time buckets. However, in APL, the `histogram` function focuses on numeric values, allowing you to control the number of bins precisely.
```splunk Splunk example
| stats count by duration | timechart span=10 count
```
```kusto APL equivalent
['sample-http-logs']
| summarize count() by histogram(req_duration_ms, 10)
```
In ANSI SQL, you can use the `GROUP BY` clause combined with range calculations to achieve a similar result to APL’s `histogram`. However, APL’s `histogram` function simplifies the process by automatically calculating bin intervals.
```sql SQL example
SELECT COUNT(*), FLOOR(req_duration_ms/10)*10 as duration_bin
FROM sample_http_logs
GROUP BY duration_bin
```
```kusto APL equivalent
['sample-http-logs']
| summarize count() by histogram(req_duration_ms, 10)
```
---
# histogramif
Source: https://axiom.co/docs/apl/aggregation-function/histogramif
The `histogramif` aggregation in APL creates a histogram that groups numeric values into intervals (bins) for rows where a specified condition evaluates to true. This is useful when you want to visualize the distribution of data conditionally—for example, analyzing response times only for successful requests or examining span durations only for specific services.
You use `histogramif` when you need to combine filtering and distribution analysis in a single operation, making your queries more efficient and expressive.
Like the `histogram` aggregation, `histogramif` returns estimated results. The estimation provides speed benefits at the expense of precision, making it fast and resource-efficient even on large or high-cardinality datasets.
## Usage [#usage]
### Syntax [#syntax]
```kusto
histogramif(numeric_field, number_of_bins, condition)
```
### Parameters [#parameters]
| Name | Type | Description |
| ---------------- | ------ | --------------------------------------------------------------------------------------- |
| `numeric_field` | `real` | The numeric field to create a histogram for, such as request duration or response size. |
| `number_of_bins` | `long` | The number of intervals (bins) to use for grouping the numeric values. |
| `condition` | `bool` | A boolean expression that determines which rows to include in the histogram. |
### Returns [#returns]
A table where each row represents a bin, along with the number of occurrences (counts) that fall within each bin for rows where the condition evaluates to true.
## Use case examples [#use-case-examples]
Use `histogramif` to analyze the distribution of request durations only for successful HTTP requests.
**Query**
```kusto
['sample-http-logs']
| summarize histogramif(req_duration_ms, 100, status == '200') by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20histogramif\(req_duration_ms%2C%20100%2C%20status%20%3D%3D%20'200'\)%20by%20bin_auto\(_time\)%22%7D)
This query creates a histogram of request durations grouped into 100ms bins, but only includes requests with a `200` HTTP status code. This helps you understand the performance characteristics of successful requests.
Use `histogramif` to analyze span duration distributions for specific services in your OpenTelemetry traces.
**Query**
```kusto
['otel-demo-traces']
| summarize histogramif(duration, 50, ['service.name'] == 'frontend') by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20histogramif\(duration%2C%2050%2C%20%5B'service.name'%5D%20%3D%3D%20'frontend'\)%20by%20bin_auto\(_time\)%22%7D)
This query groups span durations into 50ms intervals, focusing only on the frontend service. This helps you identify performance patterns specific to that service.
Use `histogramif` to examine the distribution of request durations for specific geographic regions, helping you identify regional performance issues or anomalies.
**Query**
```kusto
['sample-http-logs']
| summarize histogramif(req_duration_ms, 50, ['geo.country'] == 'United States') by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20histogramif\(req_duration_ms%2C%2050%2C%20%5B'geo.country'%5D%20%3D%3D%20'United%20States'\)%20by%20bin_auto\(_time\)%22%7D)
This query analyzes request duration patterns for traffic originating from the US, helping you identify geographic performance variations or security patterns.
## List of related aggregations [#list-of-related-aggregations]
* [histogram](/apl/aggregation-function/histogram): Use `histogram` when you want to create a distribution without a condition. Use `histogramif` when you need to filter rows first.
* [countif](/apl/aggregation-function/countif): Use `countif` for simple conditional counting. Use `histogramif` when you need distribution analysis with a condition.
* [avgif](/apl/aggregation-function/avgif): Use `avgif` when you need the average of values matching a condition. Use `histogramif` for full distribution analysis.
* [percentileif](/apl/aggregation-function/percentileif): Use `percentileif` to find specific percentile values conditionally. Use `histogramif` for a complete distribution overview.
* [sumif](/apl/aggregation-function/sumif): Use `sumif` for conditional sums. Use `histogramif` when you need to understand the distribution of conditional values.
## Other query languages [#other-query-languages]
In Splunk SPL, you typically combine filtering with histogram operations using separate commands. APL's `histogramif` consolidates this into a single aggregation, simplifying your query logic.
```sql Splunk example
| where status='200'
| timechart span=10 count by duration
```
```kusto APL equivalent
['sample-http-logs']
| summarize histogramif(req_duration_ms, 10, status == '200')
```
In ANSI SQL, you combine `WHERE` clauses with `CASE` statements and `GROUP BY` to achieve conditional histograms. APL's `histogramif` provides a more concise syntax for this pattern.
```sql SQL example
SELECT FLOOR(req_duration_ms/10)*10 as duration_bin, COUNT(*)
FROM sample_http_logs
WHERE status = '200'
GROUP BY duration_bin
```
```kusto APL equivalent
['sample-http-logs']
| summarize histogramif(req_duration_ms, 10, status == '200')
```
---
# make_list_if
Source: https://axiom.co/docs/apl/aggregation-function/make-list-if
The `make_list_if` aggregation function in APL creates a list of values from a given field, conditioned on a Boolean expression. This function is useful when you need to gather values from a column that meet specific criteria into a single array. By using `make_list_if`, you can aggregate data based on dynamic conditions, making it easier to perform detailed analysis.
This aggregation is ideal in scenarios where filtering at the aggregation level is required, such as gathering only the successful requests or collecting trace spans of a specific service in OpenTelemetry data. It’s particularly useful when analyzing logs, tracing information, or security events, where conditional aggregation is essential for understanding trends or identifying issues.
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize make_list_if(expression, condition)
```
### Parameters [#parameters]
* `expression`: The field or expression whose values will be included in the list.
* `condition`: A Boolean condition that determines which values from `expression` are included in the result.
### Returns [#returns]
The function returns an array containing all values from `expression` that meet the specified `condition`.
## Use case examples [#use-case-examples]
In this example, we will gather a list of request durations for successful HTTP requests.
**Query**
```kusto
['sample-http-logs']
| summarize make_list_if(req_duration_ms, status == '200') by id
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D+%7C+summarize+make_list_if%28req_duration_ms%2C+status+%3D%3D+%27200%27%29+by+id%22%7D)
**Output**
| id | req\_duration\_ms\_list |
| --- | ----------------------- |
| 123 | \[100, 150, 200] |
| 456 | \[300, 350, 400] |
This query aggregates request durations for HTTP requests that returned a status of ‘200’ for each user ID.
Here, we will aggregate the span durations for `cartservice` where the status code indicates success.
**Query**
```kusto
['otel-demo-traces']
| summarize make_list_if(duration, status_code == '200' and ['service.name'] == 'cartservice') by trace_id
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27otel-demo-traces%27%5D+%7C+summarize+make_list_if%28duration%2C+status_code+%3D%3D+%27200%27+and+%5B%27service.name%27%5D+%3D%3D+%27cartservice%27%29+by+trace_id%22%7D)
**Output**
| trace\_id | duration\_list |
| --------- | --------------------- |
| abc123 | \[00:01:23, 00:01:45] |
| def456 | \[00:02:12, 00:03:15] |
This query collects span durations for successful requests to the `cartservice` by `trace_id`.
In this case, we gather a list of IP addresses from security logs where the HTTP status is `403` (Forbidden) and group them by the country of origin.
**Query**
```kusto
['sample-http-logs']
| summarize make_list_if(uri, status == '403') by ['geo.country']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D+%7C+summarize+make_list_if%28uri%2C+status+%3D%3D+%27403%27%29+by+%5B%27geo.country%27%5D%22%7D)
**Output**
| geo.country | uri\_list |
| ----------- | ---------------------- |
| USA | \['/login', '/admin'] |
| Canada | \['/admin', '/secure'] |
This query collects a list of URIs that resulted in a `403` error, grouped by the country where the request originated.
## List of related aggregations [#list-of-related-aggregations]
* [**make\_list**](/apl/aggregation-function/make-list): Aggregates all values into a list without any conditions. Use `make_list` when you don’t need to filter the values based on a condition.
* [**countif**](/apl/aggregation-function/countif): Counts the number of records that satisfy a specific condition. Use `countif` when you need a count of occurrences rather than a list of values.
* [**avgif**](/apl/aggregation-function/avgif): Calculates the average of values that meet a specified condition. Use `avgif` for numerical aggregations where you want a conditional average instead of a list.
## Other query languages [#other-query-languages]
In Splunk, you would typically use the `eval` and `stats` commands to create conditional lists. In APL, the `make_list_if` function serves a similar purpose by allowing you to aggregate data into a list based on a condition.
```sql Splunk example
| stats list(field) as field_list by condition
```
```kusto APL equivalent
summarize make_list_if(field, condition)
```
In ANSI SQL, conditional aggregation often involves the use of `CASE` statements combined with aggregation functions such as `ARRAY_AGG`. In APL, `make_list_if` directly applies a condition to the aggregation.
```sql SQL example
SELECT ARRAY_AGG(CASE WHEN condition THEN field END) FROM table
```
```kusto APL equivalent
summarize make_list_if(field, condition)
```
---
# make_list
Source: https://axiom.co/docs/apl/aggregation-function/make-list
The `make_list` aggregation function in Axiom Processing Language (APL) collects all values from a specified column into a dynamic array for each group of rows in a dataset. This aggregation is particularly useful when you want to consolidate multiple values from distinct rows into a single grouped result.
For example, if you have multiple log entries for a particular user, you can use `make_list` to gather all request URIs accessed by that user into a single list. You can also apply `make_list` to various contexts, such as trace aggregation, log analysis, or security monitoring, where collating related events into a compact form is needed.
Key uses of `make_list`:
* Consolidating values from multiple rows into a list per group.
* Summarizing activity (for example, list all HTTP requests by a user).
* Generating traces or timelines from distributed logs.
## Usage [#usage]
### Syntax [#syntax]
```kusto
make_list(column)
```
### Parameters [#parameters]
* `column`: The name of the column to collect into a list.
### Returns [#returns]
The `make_list` function returns a dynamic array that contains all values of the specified column for each group of rows.
## Use case examples [#use-case-examples]
In log analysis, `make_list` is useful for collecting all URIs a user has accessed in a session. This can help in identifying browsing patterns or tracking user activity.
**Query**
```kusto
['sample-http-logs']
| summarize uris=make_list(uri) by id
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20summarize%20uris%3Dmake_list%28uri%29%20by%20id%22%7D)
**Output**
| id | uris |
| ------- | --------------------------------- |
| user123 | \[‘/home’, ‘/profile’, ‘/cart’] |
| user456 | \[‘/search’, ‘/checkout’, ‘/pay’] |
This query collects all URIs accessed by each user, providing a compact view of user activity in the logs.
In OpenTelemetry traces, `make_list` can help in gathering the list of services involved in a trace by consolidating all service names related to a trace ID.
**Query**
```kusto
['otel-demo-traces']
| summarize services=make_list(['service.name']) by trace_id
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27otel-demo-traces%27%5D%20%7C%20summarize%20services%3Dmake_list%28%5B%27service.name%27%5D%29%20by%20trace_id%22%7D)
**Output**
| trace\_id | services |
| --------- | ----------------------------------------------- |
| trace\_a | \[‘frontend’, ‘cartservice’, ‘checkoutservice’] |
| trace\_b | \[‘productcatalogservice’, ‘loadgenerator’] |
This query aggregates all service names associated with a particular trace, helping trace spans across different services.
In security logs, `make_list` is useful for collecting all IPs or cities from where a user has initiated requests, aiding in detecting anomalies or patterns.
**Query**
```kusto
['sample-http-logs']
| summarize cities=make_list(['geo.city']) by id
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20summarize%20cities%3Dmake_list%28%5B%27geo.city%27%5D%29%20by%20id%22%7D)
**Output**
| id | cities |
| ------- | ---------------------------- |
| user123 | \[‘New York’, ‘Los Angeles’] |
| user456 | \[‘Berlin’, ‘London’] |
This query collects the cities from which each user has made HTTP requests, useful for geographical analysis or anomaly detection.
## List of related aggregations [#list-of-related-aggregations]
* [**make\_set**](/apl/aggregation-function/make-set): Similar to `make_list`, but only unique values are collected in the set. Use `make_set` when duplicates aren’t relevant.
* [**count**](/apl/aggregation-function/count): Returns the count of rows in each group. Use this instead of `make_list` when you’re interested in row totals rather than individual values.
* [**max**](/apl/aggregation-function/max): Aggregates values by returning the maximum value from each group. Useful for numeric comparison across rows.
* [**dcount**](/apl/aggregation-function/dcount): Returns the distinct count of values for each group. Use this when you need unique value counts instead of listing them.
## Other query languages [#other-query-languages]
In Splunk SPL, the `make_list` equivalent is `values` or `mvlist`, which gathers multiple values into a multivalue field. In APL, `make_list` behaves similarly by collecting values from rows into a dynamic array.
```sql Splunk example
index=logs | stats values(uri) by user
```
```kusto APL equivalent
['sample-http-logs']
| summarize uris=make_list(uri) by id
```
In ANSI SQL, the `make_list` function is similar to `ARRAY_AGG`, which aggregates column values into an array for each group. In APL, `make_list` performs the same role, grouping the column values into a dynamic array.
```sql SQL example
SELECT ARRAY_AGG(uri) AS uris FROM sample_http_logs GROUP BY id;
```
```kusto APL equivalent
['sample-http-logs']
| summarize uris=make_list(uri) by id
```
---
# make_set_if
Source: https://axiom.co/docs/apl/aggregation-function/make-set-if
The `make_set_if` aggregation function in APL allows you to create a set of distinct values from a column based on a condition. You can use this function to aggregate values that meet specific criteria, helping you filter and reduce data to unique entries while applying a conditional filter. This is especially useful when analyzing large datasets to extract relevant, distinct information without duplicates.
You can use `make_set_if` in scenarios where you need to aggregate conditional data points, such as log analysis, tracing information, or security logs, to summarize distinct occurrences based on particular conditions.
## Usage [#usage]
### Syntax [#syntax]
```kusto
make_set_if(column, predicate, [max_size])
```
### Parameters [#parameters]
* `column`: The column from which distinct values will be aggregated.
* `predicate`: A condition that filters the values to be aggregated.
* `[max_size]`: (Optional) Specifies the maximum number of elements in the resulting set. If omitted, the default is 1048576.
### Returns [#returns]
The `make_set_if` function returns a dynamic array of distinct values from the specified column that satisfy the given condition.
## Use case examples [#use-case-examples]
In this use case, you’re analyzing HTTP logs and want to get the distinct cities from which requests originated, but only for requests that took longer than 500 ms.
**Query**
```kusto
['sample-http-logs']
| summarize make_set_if(['geo.city'], req_duration_ms > 500) by ['method']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20summarize%20make_set_if%28%5B%27geo.city%27%5D%2C%20req_duration_ms%20%3E%20500%29%20by%20%5B%27method%27%5D%22%7D)
**Output**
| method | make\_set\_if\_geo.city |
| ------ | ------------------------------ |
| GET | \[‘New York’, ‘San Francisco’] |
| POST | \[‘Berlin’, ‘Tokyo’] |
This query returns the distinct cities from which requests took more than 500 ms, grouped by HTTP request method.
Here, you’re analyzing OpenTelemetry traces and want to identify the distinct services that processed spans with a duration greater than 1 second, grouped by trace ID.
**Query**
```kusto
['otel-demo-traces']
| summarize make_set_if(['service.name'], duration > 1s) by ['trace_id']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27otel-demo-traces%27%5D%20%7C%20summarize%20make_set_if%28%5B%27service.name%27%5D%2C%20duration%20%3E%201s%29%20by%20%5B%27trace_id%27%5D%22%7D)
**Output**
| trace\_id | make\_set\_if\_service.name |
| --------- | ------------------------------------- |
| abc123 | \[‘frontend’, ‘cartservice’] |
| def456 | \[‘checkoutservice’, ‘loadgenerator’] |
This query extracts distinct services that have processed spans longer than 1 second for each trace.
In security log analysis, you may want to find out which HTTP status codes were encountered for each city, but only for POST requests.
**Query**
```kusto
['sample-http-logs']
| summarize make_set_if(status, method == 'POST') by ['geo.city']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20summarize%20make_set_if%28status%2C%20method%20%3D%3D%20%27POST%27%29%20by%20%5B%27geo.city%27%5D%22%7D)
**Output**
| geo.city | make\_set\_if\_status |
| -------- | --------------------- |
| Berlin | \[‘200’, ‘404’] |
| Tokyo | \[‘500’, ‘403’] |
This query identifies the distinct HTTP status codes for POST requests grouped by the originating city.
## List of related aggregations [#list-of-related-aggregations]
* [**make\_list\_if**](/apl/aggregation-function/make-list-if): Similar to `make_set_if`, but returns a list that can include duplicates instead of a distinct set.
* [**make\_set**](/apl/aggregation-function/make-set): Aggregates distinct values without a conditional filter.
* [**countif**](/apl/aggregation-function/countif): Counts rows that satisfy a specific condition, useful for when you need to count rather than aggregate distinct values.
## Other query languages [#other-query-languages]
In Splunk SPL, you may use `values` with a `where` condition to achieve similar functionality to `make_set_if`. However, in APL, the `make_set_if` function is explicitly designed to create a distinct set of values based on a conditional filter within the aggregation step itself.
```sql Splunk example
| stats values(field) by another_field where condition
```
```kusto APL equivalent
summarize make_set_if(field, condition) by another_field
```
In ANSI SQL, you would typically use `GROUP BY` in combination with conditional aggregation, such as using `CASE WHEN` inside aggregate functions. In APL, the `make_set_if` function directly aggregates distinct values conditionally without requiring a `CASE WHEN`.
```sql SQL example
SELECT DISTINCT CASE WHEN condition THEN field END
FROM table
GROUP BY another_field
```
```kusto APL equivalent
summarize make_set_if(field, condition) by another_field
```
---
# make_set
Source: https://axiom.co/docs/apl/aggregation-function/make-set
The `make_set` aggregation in APL (Axiom Processing Language) is used to collect unique values from a specific column into an array. It’s useful when you want to reduce your data by grouping it and then retrieving all unique values for each group. This aggregation is valuable for tasks such as grouping logs, traces, or events by a common attribute and retrieving the unique values of a specific field for further analysis.
You can use `make_set` when you need to collect non-repeating values across rows within a group, such as finding all the unique HTTP methods in web server logs or unique trace IDs in telemetry data.
## Usage [#usage]
### Syntax [#syntax]
```kusto
make_set(column, [limit])
```
### Parameters [#parameters]
* `column`: The column from which unique values are aggregated.
* `limit`: (Optional) The maximum number of unique values to return. Defaults to 128 if not specified.
### Returns [#returns]
An array of unique values from the specified column.
## Use case examples [#use-case-examples]
In this use case, you want to collect all unique HTTP methods used by each user in the log data.
**Query**
```kusto
['sample-http-logs']
| summarize make_set(method) by id
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D+%7C+summarize+make_set%28method%29+by+id%22%7D)
**Output**
| id | make\_set\_method |
| ------- | ----------------- |
| user123 | \['GET', 'POST'] |
| user456 | \['GET'] |
This query groups the log entries by `id` and returns all unique HTTP methods used by each user.
In this use case, you want to gather the unique service names involved in a trace.
**Query**
```kusto
['otel-demo-traces']
| summarize make_set(['service.name']) by trace_id
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27otel-demo-traces%27%5D+%7C+summarize+make_set%28%5B%27service.name%27%5D%29+by+trace_id%22%7D)
**Output**
| trace\_id | make\_set\_service.name |
| --------- | -------------------------------- |
| traceA | \['frontend', 'checkoutservice'] |
| traceB | \['cartservice'] |
This query groups the telemetry data by `trace_id` and collects the unique services involved in each trace.
In this use case, you want to collect all unique HTTP status codes for each country where the requests originated.
**Query**
```kusto
['sample-http-logs']
| summarize make_set(status) by ['geo.country']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D+%7C+summarize+make_set%28status%29+by+%5B%27geo.country%27%5D%22%7D)
**Output**
| geo.country | make\_set\_status |
| ----------- | ----------------- |
| USA | \['200', '404'] |
| UK | \['200'] |
This query collects all unique HTTP status codes returned for each country from which requests were made.
## List of related aggregations [#list-of-related-aggregations]
* [**make\_list**](/apl/aggregation-function/make-list): Similar to `make_set`, but returns all values, including duplicates, in a list. Use `make_list` if you want to preserve duplicates.
* [**count**](/apl/aggregation-function/count): Counts the number of records in each group. Use `count` when you need the total count rather than the unique values.
* [**dcount**](/apl/aggregation-function/dcount): Returns the distinct count of values in a column. Use `dcount` when you need the number of unique values, rather than an array of them.
* [**max**](/apl/aggregation-function/max): Finds the maximum value in a group. Use `max` when you are interested in the largest value rather than collecting values.
## Other query languages [#other-query-languages]
In Splunk SPL, the `values` function is similar to `make_set` in APL. The main difference is that while `values` returns all non-null values, `make_set` specifically returns only unique values and stores them in an array.
```sql Splunk example
| stats values(method) by id
```
```kusto APL equivalent
['sample-http-logs']
| summarize make_set(method) by id
```
In ANSI SQL, the `GROUP_CONCAT` or `ARRAY_AGG(DISTINCT)` functions are commonly used to aggregate unique values in a column. `make_set` in APL works similarly by aggregating distinct values from a specific column into an array, but it offers better performance for large datasets.
```sql SQL example
SELECT id, ARRAY_AGG(DISTINCT method)
FROM sample_http_logs
GROUP BY id;
```
```kusto APL equivalent
['sample-http-logs']
| summarize make_set(method) by id
```
---
# max
Source: https://axiom.co/docs/apl/aggregation-function/max
The `max` aggregation in APL allows you to find the highest value in a specific column of your dataset. This is useful when you need to identify the maximum value of numerical data, such as the longest request duration, highest sales figures, or the latest timestamp in logs. The `max` function is ideal when you are working with large datasets and need to quickly retrieve the largest value, ensuring you’re focusing on the most critical or recent data point.
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize max(ColumnName)
```
### Parameters [#parameters]
* `ColumnName`: The column or field from which you want to retrieve the maximum value. The column should contain numerical data, timespans, or dates.
### Returns [#returns]
The maximum value from the specified column.
## Use case examples [#use-case-examples]
In log analysis, you might want to find the longest request duration to diagnose performance issues.
**Query**
```kusto
['sample-http-logs']
| summarize max(req_duration_ms)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20max\(req_duration_ms\)%22%7D)
**Output**
| max\_req\_duration\_ms |
| ---------------------- |
| 5400 |
This query returns the highest request duration from the `req_duration_ms` field, which helps you identify the slowest requests.
When analyzing OpenTelemetry traces, you can find the longest span duration to determine performance bottlenecks in distributed services.
**Query**
```kusto
['otel-demo-traces']
| summarize max(duration)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20max\(duration\)%22%7D)
**Output**
| max\_duration |
| ------------- |
| 00:00:07.234 |
This query returns the longest trace span from the `duration` field, helping you pinpoint the most time-consuming operations.
In security log analysis, you may want to identify the most recent event for monitoring threats or auditing activities.
**Query**
```kusto
['sample-http-logs']
| summarize max(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20max\(_time\)%22%7D)
**Output**
| max\_time |
| ------------------- |
| 2024-09-25 12:45:01 |
This query returns the most recent timestamp from your logs, allowing you to monitor the latest security events.
## List of related aggregations [#list-of-related-aggregations]
* [**min**](/apl/aggregation-function/min): Retrieves the minimum value from a column, which is useful when you need to find the smallest or earliest value, such as the lowest request duration or first event in a log.
* [**avg**](/apl/aggregation-function/avg): Calculates the average value of a column. This function helps when you want to understand the central tendency, such as the average response time for requests.
* [**sum**](/apl/aggregation-function/sum): Sums all values in a column, making it useful when calculating totals, such as total sales or total number of requests over a period.
* [**count**](/apl/aggregation-function/count): Counts the number of records or non-null values in a column. It’s useful for finding the total number of log entries or transactions.
* [**percentile**](/apl/aggregation-function/percentile): Finds a value below which a specified percentage of data falls. This aggregation is helpful when you need to analyze performance metrics like latency at the 95th percentile.
## Other query languages [#other-query-languages]
In Splunk SPL, the `max` function works similarly, used to find the maximum value in a given field. The syntax in APL, however, requires you to specify the column to aggregate within a query and make use of APL's structured flow.
```sql Splunk example
| stats max(req_duration_ms)
```
```kusto APL equivalent
['sample-http-logs']
| summarize max(req_duration_ms)
```
In ANSI SQL, `MAX` works similarly to APL’s `max`. In SQL, you aggregate over a column using the `MAX` function in a `SELECT` statement. In APL, you achieve the same result using the `summarize` operator followed by the `max` function.
```sql SQL example
SELECT MAX(req_duration_ms) FROM sample_http_logs;
```
```kusto APL equivalent
['sample-http-logs']
| summarize max(req_duration_ms)
```
---
# maxif
Source: https://axiom.co/docs/apl/aggregation-function/maxif
# maxif aggregation in APL [#maxif-aggregation-in-apl]
## Introduction [#introduction]
The `maxif` aggregation function in APL is useful when you want to return the maximum value from a dataset based on a conditional expression. This allows you to filter the dataset dynamically and only return the maximum for rows that satisfy the given condition. It’s particularly helpful for scenarios where you want to find the highest value of a specific metric, like response time or duration, but only for a subset of the data (for example, successful responses, specific users, or requests from a particular geographic location).
You can use the `maxif` function when analyzing logs, monitoring system traces, or inspecting security-related data to get insights into the maximum value under certain conditions.
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize maxif(column, condition)
```
### Parameters [#parameters]
* `column`: The column containing the values to aggregate.
* `condition`: The condition that must be true for the values to be considered in the aggregation.
### Returns [#returns]
The maximum value from `column` for rows that meet the `condition`. If no rows match the condition, it returns `null`.
## Use case examples [#use-case-examples]
In log analysis, you might want to find the maximum request duration, but only for successful requests.
**Query**
```kusto
['sample-http-logs']
| summarize maxif(req_duration_ms, status == "200")
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20maxif\(req_duration_ms,%20status%20%3D%3D%20'200'\)%22%7D)
**Output**
| max\_req\_duration |
| ------------------ |
| 1250 |
This query returns the maximum request duration (`req_duration_ms`) for HTTP requests with a `200` status.
In OpenTelemetry traces, you might want to find the longest span duration for a specific service type.
**Query**
```kusto
['otel-demo-traces']
| summarize maxif(duration, ['service.name'] == "checkoutservice" and kind == "server")
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20maxif\(duration,%20%5B'service.name'%5D%20%3D%3D%20'checkoutservice'%20and%20kind%20%3D%3D%20'server'\)%22%7D)
**Output**
| max\_duration |
| ------------- |
| 2.05s |
This query returns the maximum span duration (`duration`) for server spans in the `checkoutservice`.
For security logs, you might want to identify the longest request duration for any requests originating from a specific country, such as the United States.
**Query**
```kusto
['sample-http-logs']
| summarize maxif(req_duration_ms, ['geo.country'] == "United States")
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20maxif\(req_duration_ms,%20%5B'geo.country'%5D%20%3D%3D%20'United%20States'\)%22%7D)
**Output**
| max\_req\_duration |
| ------------------ |
| 980 |
This query returns the maximum request duration for requests coming from the United States (`geo.country`).
## List of related aggregations [#list-of-related-aggregations]
* [**minif**](/apl/aggregation-function/minif): Returns the minimum value from a column for rows that satisfy a condition. Use `minif` when you’re interested in the lowest value under specific conditions.
* [**max**](/apl/aggregation-function/max): Returns the maximum value from a column without filtering. Use `max` when you want the highest value across the entire dataset without conditions.
* [**sumif**](/apl/aggregation-function/sumif): Returns the sum of values for rows that satisfy a condition. Use `sumif` when you want the total value of a column under specific conditions.
* [**avgif**](/apl/aggregation-function/avgif): Returns the average of values for rows that satisfy a condition. Use `avgif` when you want to calculate the mean value based on a filter.
* [**countif**](/apl/aggregation-function/countif): Returns the count of rows that satisfy a condition. Use `countif` when you want to count occurrences that meet certain criteria.
## Other query languages [#other-query-languages]
In Splunk SPL, you might use the `stats max()` function alongside a conditional filtering step to achieve a similar result. APL’s `maxif` function combines both operations into one, streamlining the query.
```splunk
| stats max(req_duration_ms) as max_duration where status="200"
```
```kusto
['sample-http-logs']
| summarize maxif(req_duration_ms, status == "200")
```
In ANSI SQL, you typically use the `MAX` function in conjunction with a `WHERE` clause. APL’s `maxif` allows you to perform the same operation with a single aggregation function.
```sql
SELECT MAX(req_duration_ms)
FROM logs
WHERE status = '200';
```
```kusto
['sample-http-logs']
| summarize maxif(req_duration_ms, status == "200")
```
---
# min
Source: https://axiom.co/docs/apl/aggregation-function/min
The `min` aggregation function in APL returns the minimum value from a set of input values. You can use this function to identify the smallest numeric or comparable value in a column of data. This is useful when you want to find the quickest response time, the lowest transaction amount, or the earliest date in log data. It’s ideal for analyzing performance metrics, filtering out abnormal low points in your data, or discovering outliers.
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize min(Expression)
```
### Parameters [#parameters]
* `Expression`: The expression from which to calculate the minimum value. Typically, this is a numeric or date/time field.
### Returns [#returns]
The function returns the smallest value found in the specified column or expression.
## Use case examples [#use-case-examples]
In this use case, you analyze HTTP logs to find the minimum request duration for each unique user.
**Query**
```kusto
['sample-http-logs']
| summarize min(req_duration_ms) by id
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20min\(req_duration_ms\)%20by%20id%22%7D)
**Output**
| id | min\_req\_duration\_ms |
| --------- | ---------------------- |
| user\_123 | 32 |
| user\_456 | 45 |
This query returns the minimum request duration for each user, helping you identify the fastest responses.
Here, you analyze OpenTelemetry trace data to find the minimum span duration per service.
**Query**
```kusto
['otel-demo-traces']
| summarize min(duration) by ['service.name']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20min\(duration\)%20by%20%5B'service.name'%5D%22%7D)
**Output**
| service.name | min\_duration |
| --------------- | ------------- |
| frontend | 2ms |
| checkoutservice | 5ms |
This query returns the minimum span duration for each service in the trace logs.
In this example, you analyze security logs to find the minimum request duration for each HTTP status code.
**Query**
```kusto
['sample-http-logs']
| summarize min(req_duration_ms) by status
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20min\(req_duration_ms\)%20by%20status%22%7D)
**Output**
| status | min\_req\_duration\_ms |
| ------ | ---------------------- |
| 200 | 10 |
| 404 | 40 |
This query returns the minimum request duration for each HTTP status code, helping you identify if certain statuses are associated with faster or slower response times.
## List of related aggregations [#list-of-related-aggregations]
* [**max**](/apl/aggregation-function/max): Returns the maximum value from a set of values. Use `max` when you need to find the highest value instead of the lowest.
* [**avg**](/apl/aggregation-function/avg): Calculates the average of a set of values. Use `avg` to find the mean value instead of the minimum.
* [**count**](/apl/aggregation-function/count): Counts the number of records or distinct values. Use `count` when you need to know how many records or unique values exist, rather than calculating the minimum.
* [**sum**](/apl/aggregation-function/sum): Adds all values together. Use `sum` when you need the total of a set of values rather than the minimum.
* [**percentile**](/apl/aggregation-function/percentile): Returns the value at a specified percentile. Use `percentile` if you need a value that falls at a certain point in the distribution of your data, rather than the minimum.
## Other query languages [#other-query-languages]
In Splunk, the `min` function works similarly to APL's `min` aggregation, allowing you to find the minimum value in a field across your dataset. The main difference is in the query structure and syntax between the two.
```sql Splunk example
| stats min(duration) by id
```
```kusto APL equivalent
['sample-http-logs']
| summarize min(req_duration_ms) by id
```
In ANSI SQL, the `MIN` function works almost identically to the APL `min` aggregation. You use it to return the smallest value in a column of data, grouped by one or more fields.
```sql SQL example
SELECT MIN(duration), id FROM sample_http_logs GROUP BY id;
```
```kusto APL equivalent
['sample-http-logs']
| summarize min(req_duration_ms) by id
```
---
# minif
Source: https://axiom.co/docs/apl/aggregation-function/minif
## Introduction [#introduction]
The `minif` aggregation in Axiom Processing Language (APL) allows you to calculate the minimum value of a numeric expression, but only for records that meet a specific condition. This aggregation is useful when you want to find the smallest value in a subset of data that satisfies a given predicate. For example, you can use `minif` to find the shortest request duration for successful HTTP requests, or the minimum span duration for a specific service in your OpenTelemetry traces.
The `minif` aggregation is especially useful in scenarios where you need conditional aggregations, such as log analysis, monitoring distributed systems, or examining security-related events.
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize minif(Expression, Predicate)
```
### Parameters [#parameters]
| Parameter | Description |
| ------------ | ------------------------------------------------------------ |
| `Expression` | The numeric expression whose minimum value you want to find. |
| `Predicate` | The condition that determines which records to include. |
### Returns [#returns]
The `minif` aggregation returns the minimum value of the specified `Expression` for the records that satisfy the `Predicate`.
## Use case examples [#use-case-examples]
In log analysis, you might want to find the minimum request duration for successful HTTP requests.
**Query**
```kusto
['sample-http-logs']
| summarize minif(req_duration_ms, status == '200') by ['geo.city']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20minif\(req_duration_ms,%20status%20%3D%3D%20'200'\)%20by%20%5B'geo.city'%5D%22%7D)
**Output**
| geo.city | min\_duration |
| --------- | ------------- |
| San Diego | 120 |
| New York | 95 |
This query finds the minimum request duration for HTTP requests with a `200` status code, grouped by city.
For distributed tracing, you can use `minif` to find the minimum span duration for a specific service.
**Query**
```kusto
['otel-demo-traces']
| summarize minif(duration, ['service.name'] == 'frontend') by trace_id
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20minif\(duration,%20%5B'service.name'%5D%20%3D%3D%20'frontend'\)%20by%20trace_id%22%7D)
**Output**
| trace\_id | min\_duration |
| --------- | ------------- |
| abc123 | 50ms |
| def456 | 40ms |
This query returns the minimum span duration for traces from the `frontend` service, grouped by `trace_id`.
In security logs, you can use `minif` to find the minimum request duration for HTTP requests from a specific country.
**Query**
```kusto
['sample-http-logs']
| summarize minif(req_duration_ms, ['geo.country'] == 'US') by status
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20minif\(req_duration_ms,%20%5B'geo.country'%5D%20%3D%3D%20'US'\)%20by%20status%22%7D)
**Output**
| status | min\_duration |
| ------ | ------------- |
| 200 | 95 |
| 404 | 120 |
This query returns the minimum request duration for HTTP requests originating from the United States, grouped by HTTP status code.
## List of related aggregations [#list-of-related-aggregations]
* [**maxif**](/apl/aggregation-function/maxif): Finds the maximum value of an expression that satisfies a condition. Use `maxif` when you need the maximum value under a condition, rather than the minimum.
* [**avgif**](/apl/aggregation-function/avgif): Calculates the average value of an expression that meets a specified condition. Useful when you want an average instead of a minimum.
* [**countif**](/apl/aggregation-function/countif): Counts the number of records that satisfy a given condition. Use this for counting records rather than calculating a minimum.
* [**sumif**](/apl/aggregation-function/sumif): Sums the values of an expression for records that meet a condition. Helpful when you’re interested in the total rather than the minimum.
## Other query languages [#other-query-languages]
In Splunk, you might use the `min` function in combination with `where` to filter results. In APL, the `minif` function combines both the filtering condition and the minimum calculation into one step.
```sql Splunk example
| stats min(req_duration_ms) as min_duration where status="200"
```
```kusto APL equivalent
['sample-http-logs']
| summarize minif(req_duration_ms, status == "200") by id
```
In ANSI SQL, you would typically use a `CASE` statement with `MIN` to apply conditional logic for aggregation. In APL, the `minif` function simplifies this by combining both the condition and the aggregation.
```sql SQL example
SELECT MIN(CASE WHEN status = '200' THEN req_duration_ms ELSE NULL END) as min_duration
FROM sample_http_logs
GROUP BY id;
```
```kusto APL equivalent
['sample-http-logs']
| summarize minif(req_duration_ms, status == "200") by id
```
---
# percentile
Source: https://axiom.co/docs/apl/aggregation-function/percentile
The `percentile` aggregation function in Axiom Processing Language (APL) allows you to calculate the value below which a given percentage of data points fall. It’s particularly useful when you need to analyze distributions and want to summarize the data using specific thresholds, such as the 90th or 95th percentile. This function can be valuable in performance analysis, trend detection, or identifying outliers across large datasets.
You can apply the `percentile` function to various use cases, such as analyzing log data for request durations, OpenTelemetry traces for service latencies, or security logs to assess risk patterns.
The `percentile` aggregation in APL is a statistical aggregation that returns estimated results. The estimation comes with the benefit of speed at the expense of accuracy. This means that `percentile` is fast and light on resources even on a large or high-cardinality dataset, but it doesn’t provide precise results.
## Usage [#usage]
### Syntax [#syntax]
```kusto
percentile(column, percentile)
```
### Parameters [#parameters]
* **column**: The name of the column to calculate the percentile on. This must be a numeric field.
* **percentile**: The target percentile value (between 0 and 100).
### Returns [#returns]
The function returns the value from the specified column that corresponds to the given percentile.
## Use case examples [#use-case-examples]
In log analysis, you can use the `percentile` function to identify the 95th percentile of request durations, which gives you an idea of the tail-end latencies of requests in your system.
**Query**
```kusto
['sample-http-logs']
| summarize percentile(req_duration_ms, 95)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20summarize%20percentile%28req_duration_ms%2C%2095%29%22%7D)
**Output**
| percentile\_req\_duration\_ms |
| ----------------------------- |
| 1200 |
This query calculates the 95th percentile of request durations, showing that 95% of requests take less than or equal to 1200ms.
For OpenTelemetry traces, you can use the `percentile` function to identify the 90th percentile of span durations for specific services, which helps to understand the performance of different services.
**Query**
```kusto
['otel-demo-traces']
| where ['service.name'] == 'checkoutservice'
| summarize percentile(duration, 90)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27otel-demo-traces%27%5D%20%7C%20where%20%5B%27service.name%27%5D%20%3D%3D%20%27checkoutservice%27%20%7C%20summarize%20percentile%28duration%2C%2090%29%22%7D)
**Output**
| percentile\_duration |
| -------------------- |
| 300ms |
This query calculates the 90th percentile of span durations for the `checkoutservice`, helping to assess high-latency spans.
In security logs, you can use the `percentile` function to calculate the 99th percentile of response times for a specific set of status codes, helping you focus on outliers.
**Query**
```kusto
['sample-http-logs']
| where status == '500'
| summarize percentile(req_duration_ms, 99)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20where%20status%20%3D%3D%20%27500%27%20%7C%20summarize%20percentile%28req_duration_ms%2C%2099%29%22%7D)
**Output**
| percentile\_req\_duration\_ms |
| ----------------------------- |
| 2500 |
This query identifies that 99% of requests resulting in HTTP 500 errors take less than or equal to 2500ms.
## List of related aggregations [#list-of-related-aggregations]
* [**avg**](/apl/aggregation-function/avg): Use `avg` to calculate the average of a column, which gives you the central tendency of your data. In contrast, `percentile` provides more insight into the distribution and tail values.
* [**min**](/apl/aggregation-function/min): The `min` function returns the smallest value in a column. Use this when you need the absolute lowest value instead of a specific percentile.
* [**max**](/apl/aggregation-function/max): The `max` function returns the highest value in a column. It’s useful for finding the upper bound, while `percentile` allows you to focus on a specific point in the data distribution.
* [**stdev**](/apl/aggregation-function/stdev): `stdev` calculates the standard deviation of a column, which helps measure data variability. While `stdev` provides insight into overall data spread, `percentile` focuses on specific distribution points.
## Other query languages [#other-query-languages]
In Splunk SPL, the `percentile` function is referred to as `perc` or `percentile`. APL's `percentile` function works similarly, but the syntax is different. The main difference is that APL requires you to explicitly define the column on which you want to apply the percentile and the target percentile value.
```sql Splunk example
| stats perc95(req_duration_ms)
```
```kusto APL equivalent
['sample-http-logs']
| summarize percentile(req_duration_ms, 95)
```
In ANSI SQL, you might use the `PERCENTILE_CONT` or `PERCENTILE_DISC` functions to compute percentiles. In APL, the `percentile` function provides a simpler syntax while offering similar functionality.
```sql SQL example
SELECT PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY req_duration_ms) FROM sample_http_logs;
```
```kusto APL equivalent
['sample-http-logs']
| summarize percentile(req_duration_ms, 95)
```
---
# percentileif
Source: https://axiom.co/docs/apl/aggregation-function/percentileif
The `percentileif` aggregation function calculates the percentile of a numeric column, conditional on a specified boolean predicate. This function is useful for filtering data dynamically and determining percentile values based only on relevant subsets of data.
You can use `percentileif` to gain insights in various scenarios, such as:
* Identifying response time percentiles for HTTP requests from specific regions.
* Calculating percentiles of span durations for specific service types in OpenTelemetry traces.
* Analyzing security events by percentile within defined risk categories.
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize percentileif(Field, Percentile, Predicate)
```
### Parameters [#parameters]
| Parameter | Description |
| ------------ | ---------------------------------------------------------------------- |
| `Field` | The numeric field from which to calculate the percentile. |
| `Percentile` | A number between 0 and 100 that specifies the percentile to calculate. |
| `Predicate` | A Boolean expression that filters rows to include in the calculation. |
### Returns [#returns]
The function returns a single numeric value representing the specified percentile of the `Field` for rows where the `Predicate` evaluates to `true`.
## Use case examples [#use-case-examples]
You can use `percentileif` to analyze request durations for specific HTTP methods.
**Query**
```kusto
['sample-http-logs']
| summarize post_p90 = percentileif(req_duration_ms, 90, method == "POST"), get_p90 = percentileif(req_duration_ms, 90, method == "GET") by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20post_p90%20%3D%20percentileif\(req_duration_ms%2C%2090%2C%20method%20%3D%3D%20'POST'\)%2C%20get_p90%20%3D%20percentileif\(req_duration_ms%2C%2090%2C%20method%20%3D%3D%20'GET'\)%20by%20bin_auto\(_time\)%22%7D)
**Output**
| post\_p90 | get\_p90 |
| --------- | -------- |
| 1.691 ms | 1.453 ms |
This query calculates the 90th percentile of request durations for HTTP POST and GET methods.
You can use `percentileif` to measure span durations for specific services and operation kinds.
**Query**
```kusto
['otel-demo-traces']
| summarize percentileif(duration, 95, ['service.name'] == 'frontend' and kind == 'server')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27otel-demo-traces%27%5D%20%7C%20summarize%20percentileif%28duration%2C%2095%2C%20%5B%27service.name%27%5D%20%3D%3D%20%27frontend%27%20and%20kind%20%3D%3D%20%27server%27%29%22%7D)
**Output**
| Percentile95 |
| ------------ |
| 1.2s |
This query calculates the 95th percentile of span durations for server spans in the `frontend` service.
You can use `percentileif` to calculate response time percentiles for specific HTTP status codes.
**Query**
```kusto
['sample-http-logs']
| summarize percentileif(req_duration_ms, 75, status == '404')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20summarize%20percentileif%28req_duration_ms%2C%2075%2C%20status%20%3D%3D%20%27404%27%29%22%7D)
**Output**
| Percentile75 |
| ------------ |
| 350 |
This query calculates the 75th percentile of request durations for HTTP 404 errors.
## List of related aggregations [#list-of-related-aggregations]
* [percentile](/apl/aggregation-function/percentile): Calculates the percentile for all rows without any filtering. Use `percentile` when you don’t need conditional filtering.
* [avgif](/apl/aggregation-function/avgif): Calculates the average of a numeric column based on a condition. Use `avgif` for mean calculations instead of percentiles.
* [minif](/apl/aggregation-function/minif): Returns the minimum value of a numeric column where a condition is true. Use `minif` for identifying the lowest values within subsets.
* [maxif](/apl/aggregation-function/maxif): Returns the maximum value of a numeric column where a condition is true. Use `maxif` for identifying the highest values within subsets.
* [sumif](/apl/aggregation-function/sumif): Sums a numeric column based on a condition. Use `sumif` for conditional total calculations.
## Other query languages [#other-query-languages]
The `percentileif` aggregation in APL works similarly to `percentile` combined with conditional filtering in SPL. However, APL integrates the condition directly into the aggregation for simplicity.
```sql Splunk example
stats perc95(req_duration_ms) as p95 where geo.country="US"
```
```kusto APL equivalent
['sample-http-logs']
| summarize percentileif(req_duration_ms, 95, geo.country == 'US')
```
In SQL, you typically calculate percentiles using window functions or aggregate functions combined with a `WHERE` clause. APL simplifies this by embedding the condition directly in the `percentileif` aggregation.
```sql SQL example
SELECT PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY req_duration_ms)
FROM sample_http_logs
WHERE geo_country = 'US'
```
```kusto APL equivalent
['sample-http-logs']
| summarize percentileif(req_duration_ms, 95, geo.country == 'US')
```
---
# percentiles_array
Source: https://axiom.co/docs/apl/aggregation-function/percentiles-array
Use the `percentiles_array` aggregation function in APL to calculate multiple percentile values over a numeric expression in one pass. This function is useful when you want to understand the distribution of numeric data points, such as response times or durations, by summarizing them at several key percentiles like the 25th, 50th, and 95th.
You can use `percentiles_array` to:
* Analyze latency or duration metrics across requests or operations.
* Identify performance outliers.
* Visualize percentile distributions in dashboards.
## Usage [#usage]
### Syntax [#syntax]
```kusto
percentiles_array(Field, Percentile1, Percentile2, ...)
```
### Parameters [#parameters]
* `Field` is the name of the field for which you want to compute percentile values.
* `Percentile1`, `Percentile2`, `...` are numeric percentile values between 0 and 100.
### Returns [#returns]
An array of numbers where each element is the value at the corresponding percentile.
## Use case examples [#use-case-examples]
Use `percentiles_array` to understand the spread of request durations per HTTP method, highlighting performance variability.
**Query**
```kusto
['sample-http-logs']
| summarize percentiles_array(req_duration_ms, 25, 50, 95) by method
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20percentiles_array\(req_duration_ms%2C%2025%2C%2050%2C%2095\)%20by%20method%22%7D)
**Output**
| method | P25 | P50 | P95 |
| ------ | --------- | --------- | -------- |
| GET | 0.3981 ms | 0.7352 ms | 1.981 ms |
| POST | 0.3261 ms | 0.7162 ms | 2.341 ms |
| PUT | 0.3324 ms | 0.7772 ms | 1.341 ms |
| DELETE | 0.2332 ms | 0.4652 ms | 1.121 ms |
This query calculates the 25th, 50th, and 95th percentiles of request durations for each HTTP method. It helps identify performance differences between different methods.
Use `percentiles_array` to analyze the distribution of span durations by service to detect potential bottlenecks.
**Query**
```kusto
['otel-demo-traces']
| summarize percentiles_array(duration, 50, 90, 99) by ['service.name']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20percentiles_array\(duration%2C%2050%2C%2090%2C%2099\)%20by%20%5B'service.name'%5D%22%7D)
**Output**
| service.name | P50 | P90 | P99 | P99 |
| --------------------- | -------- | --------- | --------- | --------- |
| recommendationservice | 1.96 ms | 2.965 ms | 3.477 ms | 3.477 ms |
| frontendproxy | 3.767 ms | 13.101 ms | 39.735 ms | 39.735 ms |
| shippingservice | 2.119 ms | 3.085 ms | 9.739 ms | 9.739 ms |
| checkoutservice | 1.454 ms | 12.342 ms | 29.542 ms | 29.542 ms |
This query shows latency patterns across services by computing the median, 90th, and 99th percentile of span durations.
Use `percentiles_array` to assess outlier response times per status code, which can reveal abnormal activity or service issues.
**Query**
```kusto
['sample-http-logs']
| summarize percentiles_array(req_duration_ms, 50, 95, 99) by status
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20percentiles_array\(req_duration_ms%2C%2050%2C%2095%2C%2099\)%20by%20status%22%7D)
**Output**
| status | P50 | P95 | P99 |
| ------ | --------- | -------- | -------- |
| 200 | 0.7352 ms | 1.981 ms | 2.612 ms |
| 201 | 0.7856 ms | 1.356 ms | 2.234 ms |
| 301 | 0.8956 ms | 1.547 ms | 2.546 ms |
| 500 | 0.6587 ms | 1.856 ms | 2.856 ms |
This query helps identify whether requests resulting in errors (like 500) are significantly slower than successful ones.
## List of related functions [#list-of-related-functions]
* [avg](/apl/aggregation-function/avg): Returns the average value. Use it when a single central tendency is sufficient.
* [percentile](/apl/aggregation-function/percentile): Returns a single percentile value. Use it when you only need one percentile.
* [percentile\_if](/apl/aggregation-function/percentileif): Returns a single percentile value for the records that satisfy a condition.
* [percentiles\_arrayif](/apl/aggregation-function/percentiles-arrayif): Returns an array of percentile values for the records that satisfy a condition.
* [sum](/apl/aggregation-function/sum): Returns the sum of a numeric column.
## Other query languages [#other-query-languages]
In Splunk, you typically calculate percentiles one at a time using the `perc` function. To get multiple percentiles, you repeat the function with different percentile values. In APL, `percentiles_array` lets you specify multiple percentiles in a single function call and returns them as an array.
```sql Splunk example
... | stats perc95(duration), perc50(duration), perc25(duration) by service
```
```kusto APL equivalent
['otel-demo-traces']
| summarize percentiles_array(duration, 25, 50, 95) by ['service.name']
```
Standard SQL typically lacks a built-in function to calculate multiple percentiles in a single operation. Instead, you use `PERCENTILE_CONT` or `PERCENTILE_DISC` with `WITHIN GROUP`, repeated for each desired percentile. In APL, `percentiles_array` simplifies this with a single function call that returns all requested percentiles as an array.
```sql SQL example
SELECT
service,
PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY duration) AS p25,
PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY duration) AS p50,
PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY duration) AS p95
FROM traces
GROUP BY service
```
```kusto APL equivalent
['otel-demo-traces']
| summarize percentiles_array(duration, 25, 50, 95) by ['service.name']
```
---
# percentiles_arrayif
Source: https://axiom.co/docs/apl/aggregation-function/percentiles-arrayif
Use `percentiles_arrayif` to calculate approximate percentile values for a numeric expression when a certain condition evaluates to true. This function is useful when you want an array of percentiles instead of a single percentile. You can use it to understand data distributions in scenarios such as request durations, event processing times, or security alert severities, while filtering on specific criteria.
## Syntax [#syntax]
```kusto
percentiles_arrayif(Field, Array, Condition)
```
## Parameters [#parameters]
* `Field` is the name of the field for which you want to compute percentile values.
* `Array` is a dynamic array of one or more numeric percentile values (between 0 and 100).
* `Condition` is a Boolean expression that indicates which records to include in the calculation.
## Returns [#returns]
The function returns an array of percentile values for the records that satisfy the condition. The position of each returned percentile in the array matches the order in which it appears in the function call.
## Use case examples [#use-case-examples]
You can use `percentiles_arrayif` to analyze request durations in HTTP logs while filtering for specific criteria, such as certain HTTP statuses or geographic locations.
**Query**
```kusto
['sample-http-logs']
| summarize percentiles_arrayif(req_duration_ms, dynamic([50, 90, 95, 99]), status == '200') by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20percentiles_arrayif\(req_duration_ms%2C%20dynamic\(%5B50%2C%2090%2C%2095%2C%2099%5D\)%2C%20status%20%3D%3D%20'200'\)%20by%20bin_auto\(_time\)%22%7D)
**Output**
| percentiles\_req\_duration\_ms |
| ------------------------------ |
| 0.7352 ms |
| 1.691 ms |
| 1.981 ms |
| 2.612 ms |
This query filters records to those with a status of 200 and returns the percentile values for the request durations.
Use `percentiles_arrayif` to track performance of spans and filter on a specific service operation. This lets you quickly gauge how request durations differ for incoming traffic.
**Query**
```kusto
['otel-demo-traces']
| summarize percentiles_arrayif(duration, dynamic([50, 90, 99, 99]), ['method'] == "POST") by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20percentiles_arrayif\(duration%2C%20dynamic\(%5B50%2C%2090%2C%2099%2C%2099%5D\)%2C%20%5B'method'%5D%20%3D%3D%20'POST'\)%20by%20bin_auto\(_time\)%22%7D)
**Output**
| percentiles\_duration |
| --------------------- |
| 5.166 ms |
| 25.18 ms |
| 71.996 ms |
This query returns the percentile values for span durations for requests with the POST method.
You can focus on server issues by filtering for specific status codes, then see how request durations are distributed in those scenarios.
**Query**
```kusto
['sample-http-logs']
| summarize percentiles_arrayif(req_duration_ms, dynamic([50, 90, 95, 99]), status startswith '5') by bin_auto(_time)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20percentiles_arrayif\(req_duration_ms%2C%20dynamic\(%5B50%2C%2090%2C%2095%2C%2099%5D\)%2C%20status%20startswith%20'5'\)%20by%20bin_auto\(_time\)%22%7D)
**Output**
| percentiles\_req\_duration\_ms |
| ------------------------------ |
| 0.7352 ms |
| 1.691 ms |
| 1.981 ms |
| 2.612 ms |
This query calculates percentile values for request durations that return a status code starting with 5 which means server error.
## List of related functions [#list-of-related-functions]
* [avg](/apl/aggregation-function/avg): Returns the average of a numeric column.
* [percentile](/apl/aggregation-function/percentile): Returns a single percentile value.
* [percentile\_if](/apl/aggregation-function/percentileif): Returns a single percentile value for the records that satisfy a condition.
* [percentiles\_array](/apl/aggregation-function/percentiles-array): Returns an array of percentile values for all rows.
* [sum](/apl/aggregation-function/sum): Returns the sum of a numeric column.
## Other query languages [#other-query-languages]
In Splunk SPL, you often use statistical functions such as `perc` or `percN()` to compute percentile estimates. In APL, you use `percentiles_arrayif` and provide a predicate to define which records to include in the computation.
```sql Splunk example
index=main sourcetype=access_combined
| stats perc90(req_duration_ms) AS p90, perc99(req_duration_ms) AS p99
```
```kusto APL equivalent
['sample-http-logs']
| summarize Dist=percentiles_arrayif(req_duration_ms, dynamic([90, 99]), status == '200')
```
In ANSI SQL, you often use window functions like `PERCENTILE_DISC` or `PERCENTILE_CONT` or write multiple `CASE` expressions for conditional aggregation. In APL, you can achieve similar functionality with `percentiles_arrayif` by passing the numeric field and condition to the function.
```sql SQL example
SELECT
PERCENTILE_DISC(0.90) WITHIN GROUP (ORDER BY req_duration_ms) AS p90,
PERCENTILE_DISC(0.99) WITHIN GROUP (ORDER BY req_duration_ms) AS p99
FROM sample_http_logs
WHERE status = '200';
```
```kusto APL equivalent
['sample-http-logs']
| summarize Dist=percentiles_arrayif(req_duration_ms, dynamic([90, 99]), status == '200')
```
# Usage [#usage]
---
# phrases
Source: https://axiom.co/docs/apl/aggregation-function/phrases
The `phrases` aggregation extracts and counts common phrases or word sequences from text fields across a dataset. It analyzes text content to identify frequently occurring phrases, helping you discover patterns, trends, and common topics in your data.
You can use this aggregation to identify common user queries, discover trending topics, extract key phrases from logs, or analyze conversation patterns in AI applications.
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize phrases(column, max_phrases)
```
### Parameters [#parameters]
| Name | Type | Required | Description |
| ------------- | ------ | -------- | -------------------------------------------------------------- |
| `column` | string | Yes | The column containing text data from which to extract phrases. |
| `max_phrases` | long | Yes | The maximum number of top phrases to return. |
### Returns [#returns]
Returns a dynamic array containing the most common phrases found in the specified column, ordered by frequency.
## Example [#example]
Extract common phrases from GenAI conversation text to identify trending topics and patterns.
**Query**
```kusto
['otel-demo-genai']
| extend conversation_text = genai_concat_contents(['attributes.gen_ai.input.messages'], ' | ')
| summarize common_phrases = phrases(conversation_text, 20)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27otel-demo-genai%27%5D%20%7C%20extend%20conversation_text%20%3D%20genai_concat_contents\(%5B%27attributes.gen_ai.input.messages%27%5D%2C%20%27%20%7C%20%27\)%20%7C%20summarize%20common_phrases%20%3D%20phrases\(conversation_text%2C%2020\)%22%7D)
**Output**
| Count | common\_phrases |
| ----- | ---------------------------- |
| 3 | first query |
| 3 | cover related future queries |
| 3 | use title case |
This query identifies the most common phrases in GenAI conversations, helping you discover trending topics and user needs.
## List of related functions [#list-of-related-functions]
* [make\_list](/apl/aggregation-function/make-list): Creates an array of all values. Use this when you need all occurrences rather than common phrases.
* [make\_set](/apl/aggregation-function/make-set): Creates an array of unique values. Use this for distinct values without frequency analysis.
* [topk](/apl/aggregation-function/topk): Returns top K values by a specific aggregation. Use this for numerical top values rather than phrase extraction.
* [count](/apl/aggregation-function/count): Counts occurrences. Combine with group by for manual phrase counting if you need more control.
* [dcount](/apl/aggregation-function/dcount): Counts distinct values. Use this to understand the variety of phrases before extracting top ones.
## Other query languages [#other-query-languages]
In Splunk SPL, there’s no built-in phrases function, but you might use the `rare` or `top` commands on tokenized text.
```sql Splunk example
| rex field=message "(?\w+)"
| top words
```
```kusto APL equivalent
['sample-http-logs']
| summarize phrases(uri, 10)
```
In ANSI SQL, you would need complex string manipulation and grouping to extract common phrases.
```sql SQL example
SELECT
phrase,
COUNT(*) as frequency
FROM (
SELECT UNNEST(SPLIT(message, ' ')) as phrase
FROM logs
)
GROUP BY phrase
ORDER BY frequency DESC
LIMIT 10
```
```kusto APL equivalent
['sample-http-logs']
| summarize phrases(uri, 10)
```
---
# rate
Source: https://axiom.co/docs/apl/aggregation-function/rate
The `rate` aggregation function in APL (Axiom Processing Language) helps you calculate the rate of change over a specific time interval. This is especially useful for scenarios where you need to monitor how frequently an event occurs or how a value changes over time. For example, you can use the `rate` function to track request rates in web logs or changes in metrics like CPU usage or memory consumption.
The `rate` function is useful for analyzing trends in time series data and identifying unusual spikes or drops in activity. It can help you understand patterns in logs, metrics, and traces over specific intervals, such as per minute, per second, or per hour.
## Usage [#usage]
### Syntax [#syntax]
```kusto
rate(field)
```
### Parameters [#parameters]
* `field`: The numeric field for which you want to calculate the rate.
### Returns [#returns]
Returns the rate of change or occurrence of the specified `field` over the time interval specified in the query.
Specify the time interval in the query in the following way:
* `| summarize rate(field)` calculates the rate value of the field over the entire query window.
* `| summarize rate(field) by bin(_time, 1h)` calculates the rate value of the field over a one-hour time window.
* `| summarize rate(field) by bin_auto(_time)` calculates the rate value of the field bucketed by an automatic time window computed by `bin_auto()`.
Use two `summarize` statements to visualize the average rate over one minute per hour. For example:
```kusto
['sample-http-logs']
| summarize respBodyRate = rate(resp_body_size_bytes) by bin(_time, 1m)
| summarize avg(respBodyRate) by bin(_time, 1h)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20respBodyRate%20%3D%20rate\(resp_body_size_bytes\)%20by%20bin\(_time%2C%201m\)%20%7C%20summarize%20avg\(respBodyRate\)%20by%20bin\(_time%2C%201h\)%22%2C%20%22queryOptions%22%3A%7B%22quickRange%22%3A%226h%22%7D%7D)
## Use case examples [#use-case-examples]
In this example, the `rate` aggregation calculates the rate of HTTP response sizes per second.
**Query**
```kusto
['sample-http-logs']
| summarize rate(resp_body_size_bytes) by bin(_time, 1s)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20rate\(resp_body_size_bytes\)%20by%20bin\(_time%2C%201s\)%22%7D)
**Output**
| rate | \_time |
| ------ | ------------------- |
| 854 kB | 2024-01-01 12:00:00 |
| 635 kB | 2024-01-01 12:00:01 |
This query calculates the rate of HTTP response sizes per second.
This example calculates the rate of span duration per second.
**Query**
```kusto
['otel-demo-traces']
| summarize rate(toint(duration)) by bin(_time, 1s)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20rate\(toint\(duration\)\)%20by%20bin\(_time%2C%201s\)%22%7D)
**Output**
| rate | \_time |
| ---------- | ------------------- |
| 26,393,768 | 2024-01-01 12:00:00 |
| 19,303,456 | 2024-01-01 12:00:01 |
This query calculates the rate of span duration per second.
In this example, the `rate` aggregation calculates the rate of HTTP request duration per second which can be useful to detect an increate in malicious requests.
**Query**
```kusto
['sample-http-logs']
| summarize rate(req_duration_ms) by bin(_time, 1s)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20rate\(req_duration_ms\)%20by%20bin\(_time%2C%201s\)%22%7D)
**Output**
| rate | \_time |
| ---------- | ------------------- |
| 240.668 ms | 2024-01-01 12:00:00 |
| 264.17 ms | 2024-01-01 12:00:01 |
This query calculates the rate of HTTP request duration per second.
## List of related aggregations [#list-of-related-aggregations]
* [**count**](/apl/aggregation-function/count): Returns the total number of records. Use `count` when you want an absolute total instead of a rate over time.
* [**sum**](/apl/aggregation-function/sum): Returns the sum of values in a field. Use `sum` when you want to aggregate the total value, not its rate of change.
* [**avg**](/apl/aggregation-function/avg): Returns the average value of a field. Use `avg` when you want to know the mean value rather than how it changes over time.
* [**max**](/apl/aggregation-function/max): Returns the maximum value of a field. Use `max` when you need to find the peak value instead of how often or quickly something occurs.
* [**min**](/apl/aggregation-function/min): Returns the minimum value of a field. Use `min` when you’re looking for the lowest value rather than a rate.
## Other query languages [#other-query-languages]
In Splunk SPL, the equivalent of the `rate` function can be achieved using the `timechart` command with a `per_second` option or by calculating the difference between successive values over time. In APL, the `rate` function simplifies this process by directly calculating the rate over a specified time interval.
```splunk Splunk example
| timechart per_second count by resp_body_size_bytes
```
```kusto APL equivalent
['sample-http-logs']
| summarize rate(resp_body_size_bytes) by bin(_time, 1s)
```
In ANSI SQL, calculating rates typically involves using window functions like `LAG` or `LEAD` to calculate the difference between successive rows in a time series. In APL, the `rate` function abstracts this complexity by allowing you to directly compute the rate over time without needing window functions.
```sql SQL example
SELECT resp_body_size_bytes, COUNT(*) / TIMESTAMPDIFF(SECOND, MIN(_time), MAX(_time)) AS rate
FROM http_logs;
```
```kusto APL equivalent
['sample-http-logs']
| summarize rate(resp_body_size_bytes) by bin(_time, 1s)
```
---
# spotlight
Source: https://axiom.co/docs/apl/aggregation-function/spotlight
Spotlight lets you set up an analysis inside a query. You define a comparison set of events and compare it to the implicit baseline (the rest of the events in scope). Spotlight evaluates every field you pass in, scores differences, and returns the most informative contrasts. You use it when you want fast root-cause analysis, anomaly investigation, or pattern discovery without hand-rolling many ad-hoc aggregations.
Spotlight is useful when you:
* Investigate spikes or dips in a time series and want to know what changed
* Explain why a subset of traces is slow or error-prone
* Find which attributes distinguish suspicious requests from normal traffic
This page explains the Spotlight APL function. For more information about how Spotlight works in the Axiom Console, see [Spotlight](/console/intelligence/spotlight).
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize spotlight(SelectionPredicate, Field1, Field2, ..., FieldN)
```
You use `spotlight` inside `summarize`. The first argument defines the comparison set. The remaining arguments list the fields to analyze.
### Parameters [#parameters]
| Name | Type | Description |
| -------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SelectionPredicate` | Boolean expression | Defines the comparison set (selected cohort). Spotlight compares events where the predicate evaluates to `true` against the baseline (events where it evaluates to `false`) within the current query scope. |
| `Field1 ... FieldN` | field references | One or more fields to analyze. Include string or categorical fields (for proportions) and numeric or timespan fields (for distributional differences). Use `*` as a wildcard to analyze all fields. |
The wildcard `*` is useful to analyze all fields in the current row, but it increases query complexity and decreases performance. Specify only relevant fields when possible.
### Returns [#returns]
* Bar charts for categorical fields (strings, Booleans)
* Boxplots for numeric fields (integers, floats, timespans) with many distinct values
## Use case examples [#use-case-examples]
Find what distinguishes error responses from normal traffic in the last 15 minutes.
**Query**
```kusto
['sample-http-logs']
| where _time >= now(-15m)
| summarize spotlight(status startswith "5", ['geo.country'], ['geo.city'], method, uri, req_duration_ms)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20spotlight\(status%20startswith%20'5'%2C%20%5B'geo.country'%5D%2C%20%5B'geo.city'%5D%2C%20method%2C%20uri%2C%20req_duration_ms\)%22%7D)
This query keeps the last 15 minutes of traffic in scope and compares error responses to everything else. Spotlight ranks the strongest differences, pointing to endpoints, regions, and latency ranges associated with the errors.
Explain why some spans are slow or erroring in the last 30 minutes.
**Query**
```kusto
['otel-demo-traces']
| where _time >= now(-30m)
| summarize spotlight(duration > 500ms, ['service.name'], kind, status_code, duration)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20where%20_time%20%3E%3D%20now\(-30m\)%20%7C%20summarize%20spotlight\(duration%20%3E%20500ms%2C%20%5B'service.name'%5D%2C%20kind%2C%20status_code%2C%20duration\)%22%7D)
The query compares spans that ran longer than 500 ms to all other spans in the time window. Spotlight highlights the service, kind, and duration range that most distinguish the selected spans.
## Best practices [#best-practices]
* Keep the `where` scope broad enough that the baseline remains meaningful. Over-filtering reduces contrast.
* Pass only fields that carry signal. Very high-cardinality identifiers can drown out more actionable attributes.
* Include numeric fields like `req_duration_ms` or `duration` to let Spotlight detect distribution shifts, not just categorical skews.
## List of related functions [#list-of-related-functions]
* [where](/apl/tabular-operators/where-operator): Filters events before Spotlight runs. Use it to scope the time window or dataset; use `spotlight` to compare selected vs baseline inside that scope.
* [summarize](/apl/tabular-operators/summarize-operator): Runs aggregations over events. `spotlight` is an aggregation you call within `summarize`.
* [top](/apl/tabular-operators/top-operator): Returns the most frequent values. Use `top` for simple frequency counts; use `spotlight` to contrast a cohort against its baseline with lift and significance.
* [lookup](/apl/tabular-operators/lookup-operator): Enriches events with reference attributes. Use `lookup` to add context before running `spotlight` across enriched fields.
## Other query languages [#other-query-languages]
In Splunk, there is no one operator that compares a selected cohort to the baseline across many fields at once. You often create a flag with `eval`, run separate `stats`/`eventstats` for each field, and then `appendpipe` or `join` to compare rates. In APL, `spotlight` is an aggregation you call once inside `summarize`. You pass a Boolean predicate to define the cohort and a list of fields to inspect, and APL returns a scored table of differences.
```sql Splunk example
index=web earliest=-15m
| eval is_error = if(status IN ("500","502","503"), 1, 0)
| stats count by method uri status geo_country geo_city
| eventstats sum(eval(is_error)) AS sel, sum(eval(1-is_error)) AS base
| ... (manual rate/lift calculations and sorting) ...
```
```kusto APL equivalent
['sample-http-logs']
| where _time >= now(-15m)
| summarize spotlight(status in ('500','502','503'),
['geo.country'], ['geo.city'], method, uri, status)
```
Standard SQL does not include a built-in cohort-vs-baseline comparator. You typically `CASE` a selection flag, aggregate twice (selected vs baseline), compute proportions, deltas, and significance, then union and sort. In APL, you express the selection as a predicate and let `spotlight` compute proportions, lift, and scores for each field/value.
```sql SQL example
WITH scoped AS (
SELECT *,
CASE WHEN status IN ('500','502','503') THEN 1 ELSE 0 END AS is_sel
FROM sample_http_logs
WHERE _time >= NOW() - INTERVAL '15' MINUTE
),
per_field AS (
SELECT 'status' AS field, status AS value,
AVG(is_sel) AS sel_rate,
AVG(1 - is_sel) AS base_rate
FROM scoped
GROUP BY status
)
SELECT field, value, sel_rate, base_rate,
sel_rate / NULLIF(base_rate,0) AS lift
FROM per_field
ORDER BY lift DESC
```
```kusto APL equivalent
['sample-http-logs']
| where _time >= now(-15m)
| summarize spotlight(status in ('500','502','503'),
status, method, uri, ['geo.country'], ['geo.city'])
```
---
# Aggregation functions
Source: https://axiom.co/docs/apl/aggregation-function/statistical-functions
The table summarizes the aggregation functions available in APL. Use all these aggregation functions in the context of the [summarize operator](/apl/tabular-operators/summarize-operator).
| Function | Description |
| --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| [arg\_min](/apl/aggregation-function/arg-min) | Returns the row where an expression evaluates to the minimum value. |
| [arg\_max](/apl/aggregation-function/arg-max) | Returns the row where an expression evaluates to the maximum value. |
| [avg](/apl/aggregation-function/avg) | Returns an average value across the group. |
| [avgif](/apl/aggregation-function/avgif) | Calculates the average value of an expression in records for which the predicate evaluates to true. |
| [count](/apl/aggregation-function/count) | Returns a count of the group without/with a predicate. |
| [countif](/apl/aggregation-function/countif) | Returns a count of rows for which the predicate evaluates to true. |
| [dcount](/apl/aggregation-function/dcount) | Returns an estimate for the number of distinct values that are taken by a scalar an expression in the summary group. |
| [dcountif](/apl/aggregation-function/dcountif) | Returns an estimate of the number of distinct values of an expression of rows for which the predicate evaluates to true. |
| [histogram](/apl/aggregation-function/histogram) | Returns a timeseries heatmap chart across the group. |
| [make\_list](/apl/aggregation-function/make-list) | Creates a dynamic JSON object (array) of all the values of an expression in the group. |
| [make\_list\_if](/apl/aggregation-function/make-list-if) | Creates a dynamic JSON object (array) of an expression values in the group for which the predicate evaluates to true. |
| [make\_set](/apl/aggregation-function/make-set) | Creates a dynamic JSON array of the set of distinct values that an expression takes in the group. |
| [make\_set\_if](/apl/aggregation-function/make-set-if) | Creates a dynamic JSON object (array) of the set of distinct values that an expression takes in records for which the predicate evaluates to true. |
| [max](/apl/aggregation-function/max) | Returns the maximum value across the group. |
| [maxif](/apl/aggregation-function/maxif) | Calculates the maximum value of an expression in records for which the predicate evaluates to true. |
| [min](/apl/aggregation-function/min) | Returns the minimum value across the group. |
| [minif](/apl/aggregation-function/minif) | Returns the minimum of an expression in records for which the predicate evaluates to true. |
| [percentile](/apl/aggregation-function/percentile) | Calculates the requested percentiles of the group and produces a timeseries chart. |
| [percentileif](/apl/aggregation-function/percentileif) | Calculates the requested percentiles of the field for the rows where the predicate evaluates to true. |
| [percentiles\_array](/apl/aggregation-function/percentiles-array) | Returns an array of numbers where each element is the value at the corresponding percentile. |
| [percentiles\_arrayif](/apl/aggregation-function/percentiles-arrayif) | Returns an array of percentile values for the records that satisfy the condition. |
| [phrases](/apl/aggregation-function/phrases) | Extracts and counts common phrases or word sequences from text fields. |
| [rate](/apl/aggregation-function/rate) | Calculates the rate of values in a group per second. |
| [spotlight](/apl/aggregation-function/spotlight) | Compares a selected set of events against a baseline and surface the most significant differences. |
| [stdev](/apl/aggregation-function/stdev) | Calculates the standard deviation of an expression across the group. |
| [stdevif](/apl/aggregation-function/stdevif) | Calculates the standard deviation of an expression in records for which the predicate evaluates to true. |
| [sum](/apl/aggregation-function/sum) | Calculates the sum of an expression across the group. |
| [sumif](/apl/aggregation-function/sumif) | Calculates the sum of an expression in records for which the predicate evaluates to true. |
| [topk](/apl/aggregation-function/topk) | Calculates the top values of an expression across the group in a dataset. |
| [topkif](/apl/aggregation-function/topkif) | Calculates the top values of an expression in records for which the predicate evaluates to true. |
| [variance](/apl/aggregation-function/variance) | Calculates the variance of an expression across the group. |
| [varianceif](/apl/aggregation-function/varianceif) | Calculates the variance of an expression in records for which the predicate evaluates to true. |
---
# stdev
Source: https://axiom.co/docs/apl/aggregation-function/stdev
The `stdev` aggregation in APL computes the standard deviation of a numeric field within a dataset. This is useful for understanding the variability or dispersion of data points around the mean. You can apply this aggregation to various use cases, such as performance monitoring, anomaly detection, and statistical analysis of logs and traces.
Use the `stdev` function to determine how spread out values like request duration, span duration, or response times are. This is particularly helpful when analyzing data trends and identifying inconsistencies, outliers, or abnormal behavior.
## Usage [#usage]
### Syntax [#syntax]
```kusto
stdev(numeric_field)
```
### Parameters [#parameters]
* **`numeric_field`**: The field containing numeric values for which the standard deviation is calculated.
### Returns [#returns]
The `stdev` aggregation returns a single numeric value representing the standard deviation of the specified numeric field in the dataset.
## Use case examples [#use-case-examples]
You can use the `stdev` aggregation to analyze HTTP request durations and identify performance variations across different requests. For instance, you can calculate the standard deviation of request durations to identify potential anomalies.
**Query**
```kusto
['sample-http-logs']
| summarize req_duration_std = stdev(req_duration_ms)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20req_duration_std%20%3D%20stdev\(req_duration_ms\)%22%7D)
**Output**
| req\_duration\_std |
| ------------------ |
| 345.67 |
This query calculates the standard deviation of the `req_duration_ms` field in the `sample-http-logs` dataset, helping to understand how much variability there is in request durations.
In distributed tracing, calculating the standard deviation of span durations can help identify inconsistent spans that might indicate performance issues or bottlenecks.
**Query**
```kusto
['otel-demo-traces']
| summarize span_duration_std = stdev(duration)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20span_duration_std%20%3D%20stdev\(duration\)%22%7D)
**Output**
| span\_duration\_std |
| ------------------- |
| 0:00:02.456 |
This query computes the standard deviation of span durations in the `otel-demo-traces` dataset, providing insight into how much variation exists between trace spans.
In security logs, the `stdev` function can help analyze the response times of various HTTP requests, potentially identifying patterns that might be related to security incidents or abnormal behavior.
**Query**
```kusto
['sample-http-logs']
| summarize resp_time_std = stdev(req_duration_ms) by status
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20resp_time_std%20%3D%20stdev\(req_duration_ms\)%20by%20status%22%7D)
**Output**
| status | resp\_time\_std |
| ------ | --------------- |
| 200 | 123.45 |
| 500 | 567.89 |
This query calculates the standard deviation of request durations grouped by the HTTP status code, providing insight into the performance of different status codes.
## List of related aggregations [#list-of-related-aggregations]
* [**avg**](/apl/aggregation-function/avg): Calculates the average value of a numeric field. Use `avg` to understand the central tendency of the data.
* [**min**](/apl/aggregation-function/min): Returns the smallest value in a numeric field. Use `min` when you need to find the minimum value.
* [**max**](/apl/aggregation-function/max): Returns the largest value in a numeric field. Use `max` to identify the peak value in a dataset.
* [**sum**](/apl/aggregation-function/sum): Adds up all the values in a numeric field. Use `sum` to get a total across records.
* [**count**](/apl/aggregation-function/count): Returns the number of records in a dataset. Use `count` when you need the number of occurrences or entries.
## Other query languages [#other-query-languages]
In Splunk SPL, the `stdev` aggregation function works similarly but has a different syntax. While SPL uses the `stdev` command within the `stats` function, APL users find the aggregation works similarly in APL with just minor differences in syntax.
```sql Splunk example
| stats stdev(duration) as duration_std
```
```kusto APL equivalent
['dataset']
| summarize duration_std = stdev(duration)
```
In ANSI SQL, the standard deviation is computed using the `STDDEV` function. APL's `stdev` function is the direct equivalent of SQL’s `STDDEV`, although APL uses pipes (`|`) for chaining operations and different keyword formatting.
```sql SQL example
SELECT STDDEV(duration) AS duration_std FROM dataset;
```
```kusto APL equivalent
['dataset']
| summarize duration_std = stdev(duration)
```
---
# stdevif
Source: https://axiom.co/docs/apl/aggregation-function/stdevif
The `stdevif` aggregation function in APL computes the standard deviation of values in a group based on a specified condition. This is useful when you want to calculate variability in data, but only for rows that meet a particular condition. For example, you can use `stdevif` to find the standard deviation of response times in an HTTP log, but only for requests that resulted in a 200 status code.
The `stdevif` function is useful when you want to analyze the spread of data values filtered by specific criteria, such as analyzing request durations in successful transactions or monitoring trace durations of specific services in OpenTelemetry data.
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize stdevif(column, condition)
```
### Parameters [#parameters]
* **column**: The column that contains the numeric values for which you want to calculate the standard deviation.
* **condition**: The condition that must be true for the values to be included in the standard deviation calculation.
### Returns [#returns]
The `stdevif` function returns a floating-point number representing the standard deviation of the specified column for the rows that satisfy the condition.
## Use case examples [#use-case-examples]
In this example, you calculate the standard deviation of request durations (`req_duration_ms`), but only for successful HTTP requests (status code 200).
**Query**
```kusto
['sample-http-logs']
| summarize stdevif(req_duration_ms, status == '200') by ['geo.country']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20summarize%20stdevif%28req_duration_ms%2C%20status%20%3D%3D%20%27200%27%29%20by%20%5B%27geo.country%27%5D%22%7D)
**Output**
| geo.country | stdev\_req\_duration\_ms |
| ----------- | ------------------------ |
| US | 120.45 |
| Canada | 98.77 |
| Germany | 134.92 |
This query calculates the standard deviation of request durations for HTTP 200 responses, grouped by country.
In this example, you calculate the standard deviation of span durations, but only for traces from the `frontend` service.
**Query**
```kusto
['otel-demo-traces']
| summarize stdevif(duration, ['service.name'] == "frontend") by kind
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27otel-demo-traces%27%5D%20%7C%20summarize%20stdevif%28duration%2C%20%5B%27service.name%27%5D%20%3D%3D%20%27frontend%27%29%20by%20kind%22%7D)
**Output**
| kind | stdev\_duration |
| ------ | --------------- |
| server | 45.78 |
| client | 23.54 |
This query computes the standard deviation of span durations for the `frontend` service, grouped by span type (`kind`).
In this example, you calculate the standard deviation of request durations for security events from specific HTTP methods, filtered by `POST` requests.
**Query**
```kusto
['sample-http-logs']
| summarize stdevif(req_duration_ms, method == "POST") by ['geo.city']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20summarize%20stdevif%28req_duration_ms%2C%20method%20%3D%3D%20%27POST%27%29%20by%20%5B%27geo.city%27%5D%22%7D)
**Output**
| geo.city | stdev\_req\_duration\_ms |
| -------- | ------------------------ |
| New York | 150.12 |
| Berlin | 130.33 |
This query calculates the standard deviation of request durations for `POST` HTTP requests, grouped by the originating city.
## List of related aggregations [#list-of-related-aggregations]
* [**avgif**](/apl/aggregation-function/avgif): Similar to `stdevif`, but instead of calculating the standard deviation, `avgif` computes the average of values that meet the condition.
* [**sumif**](/apl/aggregation-function/sumif): Computes the sum of values that meet the condition. Use `sumif` when you want to aggregate total values instead of analyzing data spread.
* [**varianceif**](/apl/aggregation-function/varianceif): Returns the variance of values that meet the condition, which is a measure of how spread out the data points are.
* [**countif**](/apl/aggregation-function/countif): Counts the number of rows that satisfy the specified condition.
* [**minif**](/apl/aggregation-function/minif): Retrieves the minimum value that satisfies the given condition, useful when finding the smallest value in filtered data.
## Other query languages [#other-query-languages]
In Splunk SPL, the `stdev` function is used to calculate the standard deviation, but you need to use an `if` function or a `where` clause to filter data. APL simplifies this by combining both operations in `stdevif`.
```sql Splunk example
| stats stdev(req_duration_ms) as stdev_req where status="200"
```
```kusto APL equivalent
['sample-http-logs']
| summarize stdevif(req_duration_ms, status == "200") by geo.country
```
In ANSI SQL, the `STDDEV` function is used to compute the standard deviation, but it requires the use of a `CASE WHEN` expression to apply a conditional filter. APL integrates the condition directly into the `stdevif` function.
```sql SQL example
SELECT STDDEV(CASE WHEN status = '200' THEN req_duration_ms END)
FROM sample_http_logs
GROUP BY geo.country;
```
```kusto APL equivalent
['sample-http-logs']
| summarize stdevif(req_duration_ms, status == "200") by geo.country
```
---
# sum
Source: https://axiom.co/docs/apl/aggregation-function/sum
The `sum` aggregation in APL is used to compute the total sum of a specific numeric field in a dataset. This aggregation is useful when you want to find the cumulative value for a certain metric, such as the total duration of requests, total sales revenue, or any other numeric field that can be summed.
You can use the `sum` aggregation in a wide range of scenarios, such as analyzing log data, monitoring traces, or examining security logs. It’s particularly helpful when you want to get a quick overview of your data in terms of totals or cumulative statistics.
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize [ =] sum()
```
### Parameters [#parameters]
* ``: (Optional) The name you want to assign to the resulting column that contains the sum.
* ``: The field in your dataset that contains the numeric values you want to sum.
### Returns [#returns]
The `sum` aggregation returns a single row with the sum of the specified numeric field. If used with a `by` clause, it returns multiple rows with the sum per group.
## Use case examples [#use-case-examples]
The `sum` aggregation can be used to calculate the total request duration in an HTTP log dataset.
**Query**
```kusto
['sample-http-logs']
| summarize total_duration = sum(req_duration_ms)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20total_duration%20%3D%20sum\(req_duration_ms\)%22%7D)
**Output**
| total\_duration |
| --------------- |
| 123456 |
This query calculates the total request duration across all HTTP requests in the dataset.
The `sum` aggregation can be applied to OpenTelemetry traces to calculate the total span duration.
**Query**
```kusto
['otel-demo-traces']
| summarize total_duration = sum(duration)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20total_duration%20%3D%20sum\(duration\)%22%7D)
**Output**
| total\_duration |
| --------------- |
| 7890 |
This query calculates the total duration of all spans in the dataset.
You can use the `sum` aggregation to calculate the total number of requests based on a specific HTTP status in security logs.
**Query**
```kusto
['sample-http-logs']
| where status == '200'
| summarize request_count = sum(1)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20where%20status%20%3D%3D%20'200'%20%7C%20summarize%20request_count%20%3D%20sum\(1\)%22%7D)
**Output**
| request\_count |
| -------------- |
| 500 |
This query counts the total number of successful requests (status 200) in the dataset.
## List of related aggregations [#list-of-related-aggregations]
* [**count**](/apl/aggregation-function/count): Counts the number of records in a dataset. Use `count` when you want to count the number of rows, not aggregate numeric values.
* [**avg**](/apl/aggregation-function/avg): Computes the average value of a numeric field. Use `avg` when you need to find the mean instead of the total sum.
* [**min**](/apl/aggregation-function/min): Returns the minimum value of a numeric field. Use `min` when you’re interested in the lowest value.
* [**max**](/apl/aggregation-function/max): Returns the maximum value of a numeric field. Use `max` when you’re interested in the highest value.
* [**sumif**](/apl/aggregation-function/sumif): Sums a numeric field conditionally. Use `sumif` when you only want to sum values that meet a specific condition.
## Other query languages [#other-query-languages]
In Splunk, you use the `sum` function in combination with the `stats` command to aggregate data. In APL, the `sum` aggregation works similarly but is structured differently in terms of syntax.
```splunk Splunk example
| stats sum(req_duration_ms) as total_duration
```
```kusto APL equivalent
['sample-http-logs']
| summarize total_duration = sum(req_duration_ms)
```
In ANSI SQL, the `SUM` function is commonly used with the `GROUP BY` clause to aggregate data by a specific field. In APL, the `sum` function works similarly but can be used without requiring a `GROUP BY` clause for simple summations.
```sql SQL example
SELECT SUM(req_duration_ms) AS total_duration
FROM sample_http_logs
```
```kusto APL equivalent
['sample-http-logs']
| summarize total_duration = sum(req_duration_ms)
```
---
# sumif
Source: https://axiom.co/docs/apl/aggregation-function/sumif
The `sumif` aggregation function in Axiom Processing Language (APL) computes the sum of a numeric expression for records that meet a specified condition. This function is useful when you want to filter data based on specific criteria and aggregate the numeric values that match the condition. Use `sumif` when you need to apply conditional logic to sums, such as calculating the total request duration for successful HTTP requests or summing the span durations in OpenTelemetry traces for a specific service.
## Usage [#usage]
### Syntax [#syntax]
```kusto
sumif(numeric_expression, condition)
```
### Parameters [#parameters]
* `numeric_expression`: The numeric field or expression you want to sum.
* `condition`: A boolean expression that determines which records contribute to the sum. Only the records that satisfy the condition are considered.
### Returns [#returns]
`sumif` returns the sum of the values in `numeric_expression` for records where the `condition` is true. If no records meet the condition, the result is 0.
## Use case examples [#use-case-examples]
In this use case, we calculate the total request duration for HTTP requests that returned a `200` status code.
**Query**
```kusto
['sample-http-logs']
| summarize total_req_duration = sumif(req_duration_ms, status == '200')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20summarize%20total_req_duration%20%3D%20sumif%28req_duration_ms%2C%20status%20%3D%3D%20%27200%27%29%22%7D)
**Output**
| total\_req\_duration |
| -------------------- |
| 145000 |
This query computes the total request duration (in milliseconds) for all successful HTTP requests (those with a status code of `200`).
In this example, we sum the span durations for the `frontend` service in OpenTelemetry traces.
**Query**
```kusto
['otel-demo-traces']
| summarize total_duration = sumif(duration, ['service.name'] == 'frontend')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27otel-demo-traces%27%5D%20%7C%20summarize%20total_duration%20%3D%20sumif%28duration%2C%20%5B%27service.name%27%5D%20%3D%3D%20%27frontend%27%29%22%7D)
**Output**
| total\_duration |
| --------------- |
| 32000 |
This query sums the span durations for traces related to the `frontend` service, providing insight into how long this service has been running over time.
Here, we calculate the total request duration for failed HTTP requests (those with status codes other than `200`).
**Query**
```kusto
['sample-http-logs']
| summarize total_req_duration_failed = sumif(req_duration_ms, status != '200')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20summarize%20total_req_duration_failed%20%3D%20sumif%28req_duration_ms%2C%20status%20%21%3D%20%27200%27%29%22%7D)
**Output**
| total\_req\_duration\_failed |
| ---------------------------- |
| 64000 |
This query computes the total request duration for all failed HTTP requests (where the status code isn’t `200`), which can be useful for security log analysis.
## List of related aggregations [#list-of-related-aggregations]
* [**avgif**](/apl/aggregation-function/avgif): Computes the average of a numeric expression for records that meet a specified condition. Use `avgif` when you’re interested in the average value, not the total sum.
* [**countif**](/apl/aggregation-function/countif): Counts the number of records that satisfy a condition. Use `countif` when you need to know how many records match a specific criterion.
* [**minif**](/apl/aggregation-function/minif): Returns the minimum value of a numeric expression for records that meet a condition. Useful when you need the smallest value under certain criteria.
* [**maxif**](/apl/aggregation-function/maxif): Returns the maximum value of a numeric expression for records that meet a condition. Use `maxif` to identify the highest values under certain conditions.
## Other query languages [#other-query-languages]
In Splunk SPL, the `sumif` equivalent functionality requires using a `stats` command with a `where` clause to filter the data. In APL, you can use `sumif` to simplify this operation by combining both the condition and the summing logic into one function.
```sql Splunk example
| stats sum(duration) as total_duration where status="200"
```
```kusto APL equivalent
summarize total_duration = sumif(duration, status == '200')
```
In ANSI SQL, achieving a similar result typically involves using a `CASE` statement inside the `SUM` function to conditionally sum values based on a specified condition. In APL, `sumif` provides a more concise approach by allowing you to filter and sum in a single function.
```sql SQL example
SELECT SUM(CASE WHEN status = '200' THEN duration ELSE 0 END) AS total_duration
FROM http_logs
```
```kusto APL equivalent
summarize total_duration = sumif(duration, status == '200')
```
---
# topk
Source: https://axiom.co/docs/apl/aggregation-function/topk
The `topk` aggregation in Axiom Processing Language (APL) allows you to identify the top `k` results based on a specified field. This is especially useful when you want to quickly analyze large datasets and extract the most significant values, such as the top-performing queries, most frequent errors, or highest latency requests.
Use `topk` to find the most common or relevant entries in datasets, especially in log analysis, telemetry data, and monitoring systems. This aggregation helps you focus on the most important data points, filtering out the noise.
The `topk` aggregation in APL is a statistical aggregation that returns estimated results. The estimation comes with the benefit of speed at the expense of accuracy. This means that `topk` is fast and light on resources even on a large or high-cardinality dataset, but it doesn’t provide precise results.
For completely accurate results, use the [`top` operator](/apl/tabular-operators/top-operator).
## Usage [#usage]
### Syntax [#syntax]
```kusto
topk(Field, k)
```
### Parameters [#parameters]
* `Field`: The field or expression to rank the results by.
* `k`: The number of top results to return.
### Returns [#returns]
A subset of the original dataset with the top `k` values based on the specified field.
## Use case examples [#use-case-examples]
When analyzing HTTP logs, you can use the `topk` function to find the top 5 most frequent HTTP status codes.
**Query**
```kusto
['sample-http-logs']
| summarize topk(status, 5)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%20%7C%20summarize%20topk\(status%2C%205\)%22%7D)
**Output**
| status | count\_ |
| ------ | ------- |
| 200 | 1500 |
| 404 | 400 |
| 500 | 200 |
| 301 | 150 |
| 302 | 100 |
This query groups the logs by HTTP status and returns the 5 most frequent statuses.
In OpenTelemetry traces, you can use `topk` to find the top five status codes by service.
**Query**
```kusto
['otel-demo-traces']
| summarize topk(['attributes.http.status_code'], 5) by ['service.name']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20topk\(%5B'attributes.http.status_code'%5D%2C%205\)%20by%20%5B'service.name'%5D%22%7D)
**Output**
| service.name | attributes.http.status\_code | \_count |
| ------------- | ---------------------------- | ---------- |
| frontendproxy | 200 | 34,862,088 |
| | 203 | 3,095,223 |
| | 404 | 154,417 |
| | 500 | 153,823 |
| | 504 | 3,497 |
This query shows the top five status codes by service.
You can use `topk` in security log analysis to find the top 5 cities generating the most HTTP requests.
**Query**
```kusto
['sample-http-logs']
| summarize topk(['geo.city'], 5)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%20%7C%20summarize%20topk\(%5B'geo.city'%5D%2C%205\)%22%7D)
**Output**
| geo.city | count\_ |
| -------- | ------- |
| New York | 500 |
| London | 400 |
| Paris | 350 |
| Tokyo | 300 |
| Berlin | 250 |
This query returns the top 5 cities based on the number of HTTP requests.
## List of related aggregations [#list-of-related-aggregations]
* [top](/apl/tabular-operators/top-operator): Returns the top values based on a field without requiring a specific number of results (`k`), making it useful when you’re unsure how many top values to retrieve.
* [topkif](/apl/aggregation-function/topkif): Returns the top `k` results without filtering. Use topk when you don’t need to restrict your analysis to a subset.
* [sort](/apl/tabular-operators/sort-operator): Orders the dataset based on one or more fields, which is useful if you need a complete ordered list rather than the top `k` values.
* [extend](/apl/tabular-operators/extend-operator): Adds calculated fields to your dataset, which can be useful in combination with `topk` to create custom rankings.
* [count](/apl/aggregation-function/count): Aggregates the dataset by counting occurrences, often used in conjunction with `topk` to find the most common values.
## Other query languages [#other-query-languages]
Splunk SPL doesn’t have the equivalent of the `topk` function. You can achieve similar results with SPL’s `top` command which is equivalent to APL’s `top` operator. The `topk` function in APL behaves similarly by returning the top `k` values of a specified field, but its syntax is unique to APL.
The main difference between `top` (supported by both SPL and APL) and `topk` (supported only by APL) is that `topk` is estimated. This means that APL’s `topk` is faster, less resource intenstive, but less accurate than SPL’s `top`.
```sql Splunk example
| top limit=5 status by method
```
```kusto APL equivalent
['sample-http-logs']
| summarize topk(status, 5) by method
```
In ANSI SQL, identifying the top `k` rows often involves using the `ORDER BY` and `LIMIT` clauses. While the logic remains similar, APL’s `topk` simplifies this process by directly returning the top `k` values of a field in an aggregation.
The main difference between SQL’s solution and APL’s `topk` is that `topk` is estimated. This means that APL’s `topk` is faster, less resource intenstive, but less accurate than SQL’s combination of `ORDER BY` and `LIMIT` clauses.
```sql SQL example
SELECT status, COUNT(*)
FROM sample_http_logs
GROUP BY status
ORDER BY COUNT(*) DESC
LIMIT 5;
```
```kusto APL equivalent
['sample-http-logs']
| summarize topk(status, 5)
```
---
# topkif
Source: https://axiom.co/docs/apl/aggregation-function/topkif
The `topkif` aggregation in Axiom Processing Language (APL) allows you to identify the top `k` values based on a specified field, while also applying a filter on another field. Use `topkif` when you want to find the most significant entries that meet specific criteria, such as the top-performing queries from a particular service, the most frequent errors for a specific HTTP method, or the highest latency requests from a specific country.
Use `topkif` when you need to focus on the most important filtered subsets of data, especially in log analysis, telemetry data, and monitoring systems. This aggregation helps you quickly zoom in on significant values without scanning the entire dataset.
The `topkif` aggregation in APL is a statistical aggregation that returns estimated results. The estimation provides the benefit of speed at the expense of precision. This means that `topkif` is fast and light on resources even on large or high-cardinality datasets but doesn’t provide completely accurate results.
For completely accurate results, use the [top operator](/apl/tabular-operators/top-operator) together with a filter.
## Syntax [#syntax]
```kusto
topkif(Field, k, Condition)
```
## Parameters [#parameters]
* `Field`: The field or expression to rank the results by.
* `k`: The number of top results to return.
* `Condition`: A logical expression that specifies the filtering condition.
## Returns [#returns]
A subset of the original dataset containing the top `k` values based on the specified field, after applying the filter condition.
# Use case examples [#use-case-examples]
Use `topkif` when analyzing HTTP logs to find the top 5 most frequent HTTP status codes for GET requests.
**Query**
```kusto
['sample-http-logs']
| summarize topkif(status, 5, method == 'GET')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20topkif\(status%2C%205%2C%20method%20%3D%3D%20'GET'\)%22%7D)
**Output**
| status | count\_ |
| ------ | ------- |
| 200 | 900 |
| 404 | 250 |
| 500 | 100 |
| 301 | 90 |
| 302 | 60 |
This query groups GET requests by HTTP status and returns the 5 most frequent statuses.
Use `topkif` in OpenTelemetry traces to find the top five services for server.
**Query**
```kusto
['otel-demo-traces']
| summarize topkif(['service.name'], 5, kind == 'server')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20topkif\(%5B'service.name'%5D%2C%205%2C%20kind%20%3D%3D%20'server'\)%22%7D)
**Output**
| service.name | count\_ |
| --------------- | ------- |
| frontend-proxy | 99,573 |
| frontend | 91,800 |
| product-catalog | 29,696 |
| image-provider | 25,223 |
| flagd | 10,336 |
This query shows the top five services filtered to server.
Use `topkif` in security log analysis to find the top 5 cities generating GET HTTP requests.
**Query**
```kusto
['sample-http-logs']
| summarize topkif(['geo.city'], 5, method == 'GET')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20topkif\(%5B'geo.city'%5D%2C%205%2C%20method%20%3D%3D%20'GET'\)%22%7D)
**Output**
| geo.city | count\_ |
| -------- | ------- |
| New York | 300 |
| London | 250 |
| Paris | 200 |
| Tokyo | 180 |
| Berlin | 160 |
This query returns the top 5 cities generating the most GET HTTP requests.
# List of related aggregations [#list-of-related-aggregations]
* [topk](/apl/aggregation-function/topk): Returns the top `k` results without filtering. Use topk when you don’t need to restrict your analysis to a subset.
* [top](/apl/tabular-operators/top-operator): Returns the top results based on a field with accurate results. Use top when precision is important.
* [sort](/apl/tabular-operators/sort-operator): Sorts the dataset based on one or more fields. Use sort if you need full ordered results.
* [extend](/apl/tabular-operators/extend-operator): Adds calculated fields to your dataset, useful before applying topkif to create new fields to rank.
* [count](/apl/aggregation-function/count): Counts occurrences in the dataset. Use count when you only need counts without focusing on the top entries.\`
## Other query languages [#other-query-languages]
Splunk SPL doesn’t have a direct equivalent to the `topkif` function. You can achieve similar results by using the top command combined with a where clause, which is closer to using APL’s top operator with a filter. However, APL’s `topkif` provides a more optimized, estimated solution when you want speed and efficiency.
```sql Splunk example
| where method="GET" | top limit=5 status
```
```kusto APL equivalent
['sample-http-logs']
| summarize topkif(status, 5, method == 'GET')
```
In ANSI SQL, identifying the top `k` rows filtered by a condition often involves a WHERE clause followed by ORDER BY and LIMIT. APL’s `topkif` simplifies this by combining the filtering and top-k selection in one function.
```sql SQL example
SELECT status, COUNT(*)
FROM sample_http_logs
WHERE method = 'GET'
GROUP BY status
ORDER BY COUNT(*) DESC
LIMIT 5;
```
```kusto APL equivalent
['sample-http-logs']
| summarize topkif(status, 5, method == 'GET')
```
# Usage [#usage]
---
# variance
Source: https://axiom.co/docs/apl/aggregation-function/variance
The `variance` aggregation function in APL calculates the variance of a numeric expression across a set of records. Variance is a statistical measurement that represents the spread of data points in a dataset. It’s useful for understanding how much variation exists in your data. In scenarios such as performance analysis, network traffic monitoring, or anomaly detection, `variance` helps identify outliers and patterns by showing how data points deviate from the mean.
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize variance(Expression)
```
### Parameters [#parameters]
* `Expression`: A numeric expression or field for which you want to compute the variance. The expression should evaluate to a numeric data type.
### Returns [#returns]
The function returns the variance (a numeric value) of the specified expression across the records.
## Use case examples [#use-case-examples]
You can use the `variance` function to measure the variability of request durations, which helps in identifying performance bottlenecks or anomalies in web services.
**Query**
```kusto
['sample-http-logs']
| summarize variance(req_duration_ms)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20variance\(req_duration_ms\)%22%7D)
**Output**
| variance\_req\_duration\_ms |
| --------------------------- |
| 1024.5 |
This query calculates the variance of request durations from a dataset of HTTP logs. A high variance indicates greater variability in request durations, potentially signaling performance issues.
For OpenTelemetry traces, `variance` can be used to measure how much span durations differ across service invocations, helping in performance optimization and anomaly detection.
**Query**
```kusto
['otel-demo-traces']
| summarize variance(duration)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20variance\(duration\)%22%7D)
**Output**
| variance\_duration |
| ------------------ |
| 1287.3 |
This query computes the variance of span durations across traces, which helps in understanding how consistent the service performance is. A higher variance might indicate unstable or inconsistent performance.
You can use the `variance` function on security logs to detect abnormal patterns in request behavior, such as unusual fluctuations in response times, which may point to potential security threats.
**Query**
```kusto
['sample-http-logs']
| summarize variance(req_duration_ms) by status
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20variance\(req_duration_ms\)%20by%20status%22%7D)
**Output**
| status | variance\_req\_duration\_ms |
| ------ | --------------------------- |
| 200 | 1534.8 |
| 404 | 2103.4 |
This query calculates the variance of request durations grouped by HTTP status codes. High variance in certain status codes (e.g., 404 errors) can indicate network or application issues.
## List of related aggregations [#list-of-related-aggregations]
* [**stdev**](/apl/aggregation-function/stdev): Computes the standard deviation, which is the square root of the variance. Use `stdev` when you need the spread of data in the same units as the original dataset.
* [**avg**](/apl/aggregation-function/avg): Computes the average of a numeric field. Combine `avg` with `variance` to analyze both the central tendency and the spread of data.
* [**count**](/apl/aggregation-function/count): Counts the number of records. Use `count` alongside `variance` to get a sense of data size relative to variance.
* [**percentile**](/apl/aggregation-function/percentile): Returns a value below which a given percentage of observations fall. Use `percentile` for a more detailed distribution analysis.
* [**max**](/apl/aggregation-function/max): Returns the maximum value. Use `max` when you are looking for extreme values in addition to variance to detect anomalies.
## Other query languages [#other-query-languages]
In SPL, variance is computed using the `stats` command with the `var` function, whereas in APL, you can use `variance` for the same functionality.
```sql Splunk example
| stats var(req_duration_ms) as variance
```
```kusto APL equivalent
['sample-http-logs']
| summarize variance(req_duration_ms)
```
In ANSI SQL, variance is typically calculated using `VAR_POP` or `VAR_SAMP`. APL provides a simpler approach using the `variance` function without needing to specify population or sample.
```sql SQL example
SELECT VAR_POP(req_duration_ms) FROM sample_http_logs;
```
```kusto APL equivalent
['sample-http-logs']
| summarize variance(req_duration_ms)
```
---
# varianceif
Source: https://axiom.co/docs/apl/aggregation-function/varianceif
The `varianceif` aggregation in APL calculates the variance of values that meet a specified condition. This is useful when you want to understand the variability of a subset of data without considering all data points. For example, you can use `varianceif` to compute the variance of request durations for HTTP requests that resulted in a specific status code or to track anomalies in trace durations for a particular service.
You can use the `varianceif` aggregation when analyzing logs, telemetry data, or security events where conditions on subsets of the data are critical to your analysis.
## Usage [#usage]
### Syntax [#syntax]
```kusto
summarize varianceif(Expr, Predicate)
```
### Parameters [#parameters]
* `Expr`: The expression (numeric) for which you want to calculate the variance.
* `Predicate`: A boolean condition that determines which records to include in the calculation.
### Returns [#returns]
Returns the variance of `Expr` for the records where the `Predicate` is true. If no records match the condition, it returns `null`.
## Use case examples [#use-case-examples]
You can use the `varianceif` function to calculate the variance of HTTP request durations for requests that succeeded (`status == '200'`).
**Query**
```kusto
['sample-http-logs']
| summarize varianceif(req_duration_ms, status == '200')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20varianceif%28req_duration_ms%2C%20status%20%3D%3D%20'200'%29%22%7D)
**Output**
| varianceif\_req\_duration\_ms |
| ----------------------------- |
| 15.6 |
This query calculates the variance of request durations for all HTTP requests that returned a status code of 200 (successful requests).
You can use the `varianceif` function to monitor the variance in span durations for a specific service, such as the `frontend` service.
**Query**
```kusto
['otel-demo-traces']
| summarize varianceif(duration, ['service.name'] == 'frontend')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'otel-demo-traces'%5D%20%7C%20summarize%20varianceif%28duration%2C%20%5B'service.name'%5D%20%3D%3D%20'frontend'%29%22%7D)
**Output**
| varianceif\_duration |
| -------------------- |
| 32.7 |
This query calculates the variance in the duration of spans generated by the `frontend` service.
The `varianceif` function can also be used to track the variance in request durations for requests from a specific geographic region, such as requests from `geo.country == 'United States'`.
**Query**
```kusto
['sample-http-logs']
| summarize varianceif(req_duration_ms, ['geo.country'] == 'United States')
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%20%7C%20summarize%20varianceif%28req_duration_ms%2C%20%5B'geo.country'%5D%20%3D%3D%20'United%20States'%29%22%7D)
**Output**
| varianceif\_req\_duration\_ms |
| ----------------------------- |
| 22.9 |
This query calculates the variance in request durations for requests originating from the United States.
## List of related aggregations [#list-of-related-aggregations]
* [**avgif**](/apl/aggregation-function/avgif): Computes the average value of an expression for records that match a given condition. Use `avgif` when you want the average instead of variance.
* [**sumif**](/apl/aggregation-function/sumif): Returns the sum of values that meet a specified condition. Use `sumif` when you’re interested in totals, not variance.
* [**stdevif**](/apl/aggregation-function/stdevif): Returns the standard deviation of values based on a condition. Use `stdevif` when you want to measure dispersion using standard deviation instead of variance.
## Other query languages [#other-query-languages]
In Splunk, you would use the `eval` function to filter data and calculate variance for specific conditions. In APL, `varianceif` combines the filtering and aggregation into a single function, making your queries more concise.
```sql Splunk example
| eval filtered_var=if(status=="200",req_duration_ms,null())
| stats var(filtered_var)
```
```kusto APL equivalent
['sample-http-logs']
| summarize varianceif(req_duration_ms, status == '200')
```
In ANSI SQL, you typically use a `CASE` statement to apply conditional logic and then compute the variance. In APL, `varianceif` simplifies this by combining both the condition and the aggregation.
```sql SQL example
SELECT VARIANCE(CASE WHEN status = '200' THEN req_duration_ms END)
FROM sample_http_logs;
```
```kusto APL equivalent
['sample-http-logs']
| summarize varianceif(req_duration_ms, status == '200')
```
---
# Map fields
Source: https://axiom.co/docs/apl/data-types/map-fields
Map fields are a special type of field that can hold a collection of nested key-value pairs within a single field. You can think of the content of a map field as a JSON object.
Axiom automatically creates map fields in datasets that use [OpenTelemetry](/send-data/opentelemetry) and you can create map fields yourself in any dataset.
## Benefits and drawbacks of map fields [#benefits-and-drawbacks-of-map-fields]
Map fields help you manage high-dimensionality data by storing multiple key-value pairs within a single field. One of the benefits of map fields is that you can store additional attributes without adding more fields. This is particularly useful when the shape of your data is unpredictable (for example, additional attributes added by OpenTelemetry instrumentation). Using map fields means that you can avoid reaching the field limit of a dataset.
Use map fields in the following cases:
* You approach the dataset field limit.
* The shape of your data is unpredictable. For example, an OpenTelemetry instrumentation or another SDK creates objects with many keys.
* You work with feature flags or custom attributes that generate many fields.
Map fields reduce impact on field limits, but involve trade-offs in query efficiency and compression. The drawbacks of map fields are the following:
* Querying map fields uses more query-hours than querying conventional fields.
* In some cases, map fields don’t compress as well as conventional fields. For example, if there is little shared structure between map values. This means datasets with map fields can use more storage.
* You don’t have visibility into map fields from the schema. For example, autocomplete doesn’t know the properties inside the map field.
## Custom attributes in tracing datasets [#custom-attributes-in-tracing-datasets]
If you use [OpenTelemetry](/send-data/opentelemetry) to send data to Axiom, you find some attributes in the `attributes.custom` map field. The reason is that instrumentation libraries can add hundreds or even thousands of arbitrary attributes to spans. Storing each custom attribute in a separate field would significantly increase the number of fields in your dataset. To keep the number of fields in your dataset under control, Axiom places all custom attributes in the single `attributes.custom` map field.
## Use map fields in queries [#use-map-fields-in-queries]
Map fields are particularly useful for handling nested data structures, such as data from `logfmt` format or other key-value formats with unpredictable structure.
The example query below uses the `http.protocol` property inside the `attributes.custom` map field to filter results:
```kusto
['otel-demo-traces']
| where ['attributes.custom']['http.protocol'] == 'HTTP/1.1'
```
[Run in playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7b%22apl%22%3a%22%5b%27otel-demo-traces%27%5d%5cn%7c%20where%20%5b%27attributes.custom%27%5d%5b%27http.protocol%27%5d%20%3d%3d%20%27HTTP%2f1.1%27%22%2c%22queryOptions%22%3a%7b%22quickRange%22%3a%2230d%22%7d%7d)
## Create map fields using UI [#create-map-fields-using-ui]
To create a map field using the UI:
1. Go to the Datasets tab.
2. Select the dataset where you want to create the map field.
3. In the top right of the fields list, click **More > Create map field**.
4. In **Field name**, enter the full name of the field, including parent fields, if any. For example, `map_field_name`. For more information on syntax, see [Access properties of nested maps](#access-properties-of-nested-maps)
5. Click **Create map field**.
## Create map fields using API [#create-map-fields-using-api]
To create a map field using the Axiom API, send a request to the [Create map field](/restapi/endpoints/createMapField) endpoint. For example:
```bash
curl --request POST \
--url https://api.axiom.co/v2/datasets/DATASET_NAME/mapfields \
--header 'Authorization: Bearer API_TOKEN' \
--header 'Content-Type: application/json' \
--data '{
"name": "MAP_FIELD"
}'
```
Replace `MAP_FIELD` with the name of the field that you want to change to a map field.
Creating a map field affects the schema of the dataset. If the dataset’s schema is locked, Axiom automatically regenerates the locked schema when you create a map field so that the locked schema reflects the change. For more information, see [Lock dataset schema](/reference/datasets#lock-dataset-schema).
## View map fields [#view-map-fields]
To view map fields:
1. Go to the Datasets tab.
2. Select a dataset where you want to view map fields.
3. Map fields are labelled in the following way:
* **MAPPED** means that the field was previously an ordinary field but at some point its parent was changed to a map field. Axiom adds new events to the field as an attribute of the parent map field. Events you ingested before the change retain the ordinary structure. To remove the ordinary field together with the values you ingested before the change, [delete the field](/reference/datasets#delete-fields). This doesn’t affect the values that Axiom stores in the parent map field.
* **UNUSED** means that the field is configured as a map field but you haven’t yet ingested data into it. Once ingested, data within this field won’t count toward your field limit.
* **REMOVED** means that the field was configured as a map field but at some point it was changed to an ordinary field. Axiom adds new events to the field as usual. Events you ingested before the change retain the map structure. To fully remove this field, [delete the field](/reference/datasets#delete-fields). Alternatively, [trim your dataset](/reference/datasets#trim-dataset) to remove the time period when map data was ingested, and then [vacuum the fields](/reference/datasets#vacuum-fields).
## Access properties of nested maps [#access-properties-of-nested-maps]
To access the properties of nested maps, use index notation, dot notation, or a mix of the two. If you use index notation for an entity, enclose the entity name in quotation marks (`'` or `"`) and square brackets (`[]`). For example:
* `where ['map_field']['property1']['property2'] == 14`
* `where map_field.property1.property2 == 14`
* `where ['map_field'].property1.property2 == 14`
If an entity name has spaces (` `), dots (`.`), or dashes (`-`), you can only use index notation for that entity. You can use dot notation for the other entities. For example:
* `where ['map.field']['property.name1']['property.name2'] == 14`
* `where ['map.field'].property1.property2 == 14`
In OTel traces, custom attributes are located in the `attributes.custom` map field. You can access them as `['attributes.custom']['header.Accept']`, for example. In this case, you don’t access the `Accept` field nested within the `header` field. What actually happens is that you access the field named `header.Accept` within the `attributes.custom` map field.
For more information on quoting field names, see [Entity names](/apl/entities/entity-names#quote-identifiers).
## Map fields and flattened fields [#map-fields-and-flattened-fields]
Within a dataset, the same fields can exist as flattened fields and as subfields of a map field.
For example, consider the following:
1. `geo` is initially not a map field.
2. You ingest the following:
```json
{
"geo": {
"city": "Paris",
"country": "France"
}
}
```
This adds two flattened fields to the dataset that you can access as `['geo.city']` or `['geo.country']`.
3. You change `geo` to a map field through the UI or the API.
4. You ingest the following:
```json
{
"geo": {
"city": "Paris",
"country": "France"
}
}
```
You use the same ingest JSON as before, but this adds the new subfields to the `geo` parent map field. You can access the subfields as `['geo']['city']` and `['geo']['country']`.
Axiom treats the flattened fields (`['geo.city']` and `['geo.country']`) and the subfields of the map field (`['geo']['city']` and `['geo']['country']`) as separate fields and doesn’t maintain a relationship between them.
Queries using `['geo.city']` access a field literally named `geo.city`, while `['geo']['city']` accesses the `city` key inside a `geo` map. These references aren’t equivalent.
To avoid confusion:
* Choose either a flattened or map-based structure when designing your schema.
* Be explicit in queries about which fields to include or exclude.
---
# Null values
Source: https://axiom.co/docs/apl/data-types/null-values
All scalar data types in APL have a special value that represents a missing value. This value is called the null value, or null.
## Null literals [#null-literals]
The null value of a scalar type D is represented in the query language by the null literal D(null). The following query returns a single row full of null values:
```kusto
print bool(null), datetime(null), dynamic(null), int(null), long(null), real(null), double(null), time(null)
```
## Predicates on null values [#predicates-on-null-values]
The scalar function [isnull()](/apl/scalar-functions/string-functions#isnull\(\)) can be used to determine if a scalar value is the null value. The corresponding function [isnotnull()](/apl/scalar-functions/string-functions#isnotnull\(\)) can be used to determine if a scalar value isn’t the null value.
## Equality and inequality of null values [#equality-and-inequality-of-null-values]
* Equality (`==`): Applying the equality operator to two null values yields `bool(null)`. Applying the equality operator to a null value and a non-null value yields `bool(false)`.
* inequality(`!=`): Applying the inequality operator to two null values yields `bool(null)`. Applying the inequality operator to a null value and a non-null value yields `bool(true)`.
---
# Scalar data types
Source: https://axiom.co/docs/apl/data-types/scalar-data-types
Axiom Processing Language supplies a set of system data types that define all the types of data that can be used with APL.
The following table lists the data types supported by APL, alongside additional aliases you can use to refer to them.
| **Type** | **Additional names** | **gettype()** |
| ------------------------------------- | ----------------------------- | ------------------------------------------------------------ |
| [bool()](#the-bool-data-type) | **boolean** | **int8** |
| [datetime()](#the-datetime-data-type) | **date** | **datetime** |
| [dynamic()](#the-dynamic-data-type) | | **array** or **dictionary** or any other of the other values |
| [int()](#the-int-data-type) | **int** has an alias **long** | **int** |
| [long()](#the-long-data-type) | | **long** |
| [real()](#the-real-data-type) | **double** | **real** |
| [string()](#the-string-data-type) | | **string** |
| [timespan()](#the-timespan-data-type) | **time** | **timespan** |
## The bool data type [#the-bool-data-type]
The bool (boolean) data type can have one of two states: `true` or `false` (internally encoded as 1 and 0, respectively), as well as the null value.
### bool literals [#bool-literals]
The bool data type has the following literals:
* true and bool(true): Representing trueness
* false and bool(false): Representing falsehood
* null and bool(null): Representing the null value
### bool operators [#bool-operators]
The `bool` data type supports the following operators: equality (`==`), inequality (`!=`), logical-and (`and`), and logical-or (`or`).
## The datetime data type [#the-datetime-data-type]
The datetime (date) data type represents an instant in time, typically expressed as a date and time of day. Values range from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 PM, December 31, 9999 AD (CE) in the Gregorian calendar.
### datetime literals [#datetime-literals]
Literals of type **datetime** have the syntax **datetime** (`value`), where a number of formats are supported for value, as indicated by the following table:
| **Example** | **Value** |
| ----------------------------------------------------------------- | -------------------------------------------------------------- |
| **datetime(2019-11-30 23:59:59.9)** **datetime(2015-12-31)** | Times are always in UTC. Omitting the date gives a time today. |
| **datetime(null)** | Check out [null values](/apl/data-types/null-values) |
| **now()** | The current time. |
| **now(-timespan)** | now()-timespan |
| **ago(timespan)** | now()-timespan |
**now()** and **ago()** indicate a `datetime` value compared with the moment in time when APL started to execute the query.
### Supported formats [#supported-formats]
Axiom supports the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format which is the standard format for representing dates and times in the Gregorian calendar.
| **Format** | **Example** |
| ------------------- | --------------------------- |
| %Y-%m-%dT%H:%M:%s%z | 2016-06-26T08:20:03.123456Z |
| %Y-%m-%dT%H:%M:%s | 2016-06-26T08:20:03.123456 |
| %Y-%m-%dT%H:%M | 2016-06-26T08:20 |
| %Y-%m-%d %H:%M:%s%z | 2016-10-06 15:55:55.123456Z |
| %Y-%m-%d %H:%M:%s | 2016-10-06 15:55:55 |
| %Y-%m-%d %H:%M | 2016-10-06 15:55 |
| %Y-%m-%d | 2014-11-08 |
## The dynamic data type [#the-dynamic-data-type]
The **dynamic** scalar data type is special in that it can take on any value of other scalar data types from the list below, as well as arrays and property bags. Specifically, a **dynamic** value can be:
* null
* A value of any of the primitive scalar data types: **bool**, **datetime**, **int**, **long**, **real**, **string**, and **timespan**.
* An array of **dynamic** values, holding zero or more values with zero-based indexing.
* A property bag, holding zero or more key-value pairs.
### Dynamic literals [#dynamic-literals]
A literal of type dynamic looks like this:
dynamic (`Value`)
Value can be:
* null, in which case the literal represents the null dynamic value: **dynamic(null)**.
* Another scalar data type literal, in which case the literal represents the **dynamic** literal of the "inner" type. For example, **dynamic(6)** is a dynamic value holding the value 6 of the long scalar data type.
* An array of dynamic or other literals: \[`ListOfValues`]. For example, dynamic(\[3, 4, "bye"]) is a dynamic array of three elements, two **long** values and one **string** value.
* A property bag: \{`Name`=`Value ...`}. For example, `dynamic(\{"a":1, "b":\{"a":2\}\})` is a property bag with two slots, a, and b, with the second slot being another property bag.
## The int data type [#the-int-data-type]
The **int** data type represents a signed, 64-bit wide, integer.
The special form **int(null)** represents the [null value.](/apl/data-types/null-values)
**int** has an alias **[long](/apl/data-types/scalar-data-types#the-long-data-type)**
## The long data type [#the-long-data-type]
The **long** data type represents a signed, 64-bit wide, integer.
### long literals [#long-literals]
Literals of the long data type can be specified in the following syntax:
long(`Value`)
Where Value can take the following forms:
* One more or digits, in which case the literal value is the decimal representation of these digits. For example, **long(11)** is the number eleven of type long.
* A minus (`-`) sign followed by one or more digits. For example, **long(-3)** is the number minus three of type **long**.
* null, in which case this is the [null value](/apl/data-types/null-values) of the **long** data type. Thus, the null value of type **long** is **long(null)**.
## The real data type [#the-real-data-type]
The **real** data type represents a 64-bit wide, double-precision, floating-point number.
## The string data type [#the-string-data-type]
The **string** data type represents a sequence of zero or more [Unicode](https://home.unicode.org/) characters.
### String literals [#string-literals]
There are several ways to encode literals of the **string** data type in a query text:
* Enclose the string in double-quotes(`"`): "This is a string literal. Single quote characters (') don’t require escaping. Double quote characters (") are escaped by a backslash (\\)"
* Enclose the string in single-quotes (`'`): Another string literal. Single quote characters (') require escaping by a backslash (\\). Double quote characters (") don’t require escaping.
In the two representations above, the backslash (`\`) character indicates escaping. The backslash is used to escape the enclosing quote characters, tab characters (`\t`), newline characters (`\n`), and itself (`\\`).
### Raw string literals [#raw-string-literals]
Raw string literals are also supported. In this form, the backslash character (`\`) stands for itself, and doesn’t denote an escape sequence.
* Enclosed in double-quotes (`""`): `@"This is a raw string literal"`
* Enclose in single-quotes (`'`): `@'This is a raw string literal'`
Raw strings are particularly useful for regexes where you can use `@"^[\d]+$"` instead of `"^[\\d]+$"`.
## The timespan data type [#the-timespan-data-type]
The **timespan** `(time)` data type represents a time interval.
## timespan literals [#timespan-literals]
Literals of type **timespan** have the syntax **timespan(value)**, where a number of formats are supported for value, as indicated by the following table:
| **Value** | **length of time** |
| --------------- | ------------------ |
| '`2d` | 2 days |
| `1.5h` | 1.5 hour |
| `30m` | 30 minutes |
| `10s` | 10 seconds |
| `timespan(15s)` | 15 seconds |
| `0.1s` | 0.1 second |
| `timespan(2d)` | 2 days |
## Type conversions [#type-conversions]
APL provides a set of functions to convert values between different scalar data types. These conversion functions allow you to convert a value from one type to another.
Some of the commonly used conversion functions include:
* `tobool()`: Converts input to boolean representation.
* `todatetime()`: Converts input to datetime scalar.
* `todouble()` or `toreal()`: Converts input to a value of type real.
* `tostring()`: Converts input to a string representation.
* `totimespan()`: Converts input to timespan scalar.
* `tolong()`: Converts input to long (signed 64-bit) number representation.
* `toint()`: Converts input to an integer value (signed 64-bit) number representation.
For a complete list of conversion functions and their detailed descriptions and examples, refer to the [Conversion functions](/apl/scalar-functions/conversion-functions) documentation.
---
# Entity names
Source: https://axiom.co/docs/apl/entities/entity-names
APL entities (datasets, tables, columns, and operators) are named. For example, two fields or columns in the same dataset can have the same name if the casing is different, and a table and a dataset may have the same name because they aren’t in the same scope.
## Columns [#columns]
* Column names are case-sensitive for resolving purposes and they have a specific position in the dataset’s collection of columns.
* Column names are unique within a dataset and table.
* In queries, columns are generally referenced by name only. They can only appear in expressions, and the query operator under which the expression appears determines the table or tabular data stream.
## Identifier naming rules [#identifier-naming-rules]
Axiom uses identifiers to name various entities. Valid identifier names follow these rules:
* Between 1 and 1024 characters long.
* Allowed characters:
* Alphanumeric characters (letters and digits)
* Underscore (`_`)
* Space (` `)
* Dot (`.`)
* Dash (`-`)
Identifier names are case-sensitive.
## Quote identifiers [#quote-identifiers]
Quote an identifier in your APL query if any of the following is true:
* The identifier name contains at least one of the following special characters:
* Space (` `)
* Dot (`.`)
* Dash (`-`)
* The identifier name is identical to one of the reserved keywords of the APL query language. For example, `project` or `where`.
If any of the above is true, you must quote the identifier by enclosing it in quotation marks (`'` or `"`) and square brackets (`[]`). For example, `['my-field']`.
If none of the above is true, you don’t need to quote the identifier in your APL query. For example, `myfield`. In this case, quoting the identifier name is optional.
---
# Migrate from SQL to APL
Source: https://axiom.co/docs/apl/guides/migrating-from-sql-to-apl
## Introduction [#introduction]
As data grows exponentially, organizations are continuously seeking more efficient and powerful tools to manage and analyze their data. The Query tab, which utilizes the Axiom Processing Language (APL), is one such service that offers fast, scalable, and interactive data exploration capabilities.
This tutorial helps you migrate SQL to APL, helping you understand key differences and providing you with query examples.
## Introduction to Axiom Processing Language (APL) [#introduction-to-axiom-processing-language-apl]
Axiom Processing Language (APL) is the language used by the Query tab, a fast and highly scalable data exploration service. APL is optimized for real-time and historical data analytics, making it a suitable choice for various data analysis tasks.
**Tabular operators**: In APL, there are several tabular operators that help you manipulate and filter data, similar to SQL’s SELECT, FROM, WHERE, GROUP BY, and ORDER BY clauses. Some of the commonly used tabular operators are:
* `extend`: Adds new columns to the result set.
* `project`: Selects specific columns from the result set.
* `where`: Filters rows based on a condition.
* `summarize`: Groups and aggregates data similar to the GROUP BY clause in SQL.
* `sort`: Sorts the result set based on one or more columns, similar to ORDER BY in SQL.
## Key differences between SQL and APL [#key-differences-between-sql-and-apl]
While SQL and APL are query languages, there are some key differences to consider:
* APL is designed for querying large volumes of structured, semi-structured, and unstructured data.
* APL is a pipe-based language, meaning you can chain multiple operations using the pipe operator (`|`) to create a data transformation flow.
* APL doesn’t use SELECT, and FROM clauses like SQL. Instead, it uses keywords such as summarize, extend, where, and project.
* APL is case-sensitive, whereas SQL isn’t.
## Benefits of migrating from SQL to APL: [#benefits-of-migrating-from-sql-to-apl]
* **Time Series Analysis:** APL is particularly strong when it comes to analyzing time-series data (logs, telemetry data, etc.). It has a rich set of operators designed specifically for such scenarios, making it much easier to handle time-based analysis.
* **Pipelining:** APL uses a pipelining model, much like the UNIX command line. You can chain commands together using the pipe (`|`) symbol, with each command operating on the results of the previous command. This makes it very easy to write complex queries.
* **Easy to Learn:** APL is designed to be simple and easy to learn, especially for those already familiar with SQL. It doesn’t require any knowledge of database schemas or the need to specify joins.
* **Scalability:** APL is a more scalable platform than SQL. This means that it can handle larger amounts of data.
* **Flexibility:** APL is a more flexible platform than SQL. This means that it can be used to analyze different types of data.
* **Features:** APL offers more features and capabilities than SQL. This includes features such as real-time analytics, and time-based analysis.
## Basic APL Syntax [#basic-apl-syntax]
A basic APL query follows this structure:
```kusto
|
|
|
|
```
## Query Examples [#query-examples]
Let’s see some examples of how to convert SQL queries to APL.
## SELECT with a simple filter [#select-with-a-simple-filter]
**SQL:**
```sql
SELECT *
FROM [Sample-http-logs]
WHERE method = 'GET';
```
**APL:**
```kusto
['sample-http-logs']
| where method == 'GET'
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20where%20method%20==%20%27GET%27%22,%22queryOptions%22:\{%22quickRange%22:%2230d%22}})
## COUNT with GROUP BY [#count-with-group-by]
**SQL:**
```sql
SELECT Country, COUNT(*)
FROM [Sample-http-logs]
GROUP BY method;
```
**APL:**
```kusto
['sample-http-logs']
| summarize count() by method
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20summarize%20count\(\)%20by%20method%22,%22queryOptions%22:\{%22quickRange%22:%2230d%22}})
## Top N results [#top-n-results]
**SQL:**
```sql
SELECT TOP 10 Status, Method
FROM [Sample-http-logs]
ORDER BY Method DESC;
```
**APL:**
```kusto
['sample-http-logs']
| top 10 by method desc
| project status, method
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|top%2010%20by%20method%20desc%20\n|%20project%20status,%20method%22,%22queryOptions%22:\{%22quickRange%22:%2215d%22}})
## Simple filtering and projection [#simple-filtering-and-projection]
**SQL:**
```sql
SELECT method, status, geo.country
FROM [Sample-http-logs]
WHERE resp_header_size_bytes >= 18;
```
**APL:**
```kusto
['sample-http-logs']
| where resp_header_size_bytes >= 18
| project method, status, ['geo.country']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|where%20resp_header_size_bytes%20%3E=18%20\n|%20project%20method,%20status,%20\[%27geo.country%27]%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## COUNT with a HAVING clause [#count-with-a-having-clause]
**SQL:**
```sql
SELECT geo.country
FROM [Sample-http-logs]
GROUP BY geo.country
HAVING COUNT(*) > 100;
```
**APL:**
```kusto
['sample-http-logs']
| summarize count() by ['geo.country']
| where count_ > 100
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20summarize%20count\(\)%20by%20\[%27geo.country%27]\n|%20where%20count_%20%3E%20100%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Multiple Aggregations [#multiple-aggregations]
**SQL:**
```sql
SELECT geo.country,
COUNT(*) AS TotalRequests,
AVG(req_duration_ms) AS AverageRequest,
MIN(req_duration_ms) AS MinRequest,
MAX(req_duration_ms) AS MaxRequest
FROM [Sample-http-logs]
GROUP BY geo.country;
```
**APL:**
```kusto
Users
| summarize TotalRequests = count(),
AverageRequest = avg(req_duration_ms),
MinRequest = min(req_duration_ms),
MaxRequest = max(req_duration_ms) by ['geo.country']
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20summarize%20totalRequests%20=%20count\(\),%20Averagerequest%20=%20avg\(req_duration_ms\),%20MinRequest%20=%20min\(req_duration_ms\),%20MaxRequest%20=%20max\(req_duration_ms\)%20by%20\[%27geo.country%27]%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
### Sum of a column [#sum-of-a-column]
**SQL:**
```sql
SELECT SUM(resp_body_size_bytes) AS TotalBytes
FROM [Sample-http-logs];
```
**APL:**
```kusto
[‘sample-http-logs’]
| summarize TotalBytes = sum(resp_body_size_bytes)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20summarize%20TotalBytes%20=%20sum\(resp_body_size_bytes\)%22,%22queryOptions%22:\{%22quickRange%22:%2230d%22}})
### Average of a column [#average-of-a-column]
**SQL:**
```sql
SELECT AVG(req_duration_ms) AS AverageRequest
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| summarize AverageRequest = avg(req_duration_ms)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20summarize%20AverageRequest%20=%20avg\(req_duration_ms\)%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Minimum and Maximum Values of a column [#minimum-and-maximum-values-of-a-column]
**SQL:**
```sql
SELECT MIN(req_duration_ms) AS MinRequest, MAX(req_duration_ms) AS MaxRequest
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| summarize MinRequest = min(req_duration_ms), MaxRequest = max(req_duration_ms)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20summarize%20MinRequest%20=%20min\(req_duration_ms\),%20MaxRequest%20=%20max\(req_duration_ms\)%22,%22queryOptions%22:\{%22quickRange%22:%2230d%22}})
## Count distinct values [#count-distinct-values]
**SQL:**
```sql
SELECT COUNT(DISTINCT method) AS UniqueMethods
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| summarize UniqueMethods = dcount(method)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|summarize%20UniqueMethods%20=%20dcount\(method\)%22,%22queryOptions%22:\{%22quickRange%22:%2230d%22}})
## Standard deviation of a data [#standard-deviation-of-a-data]
**SQL:**
```sql
SELECT STDDEV(req_duration_ms) AS StdDevRequest
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| summarize StdDevRequest = stdev(req_duration_ms)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20summarize%20stdDEVRequest%20=%20stdev\(req_duration_ms\)%22,%22queryOptions%22:\{%22quickRange%22:%2230d%22}})
## Variance of a data [#variance-of-a-data]
**SQL:**
```sql
SELECT VAR(req_duration_ms) AS VarRequest
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| summarize VarRequest = variance(req_duration_ms)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20summarize%20VarRequest%20=%20variance\(req_duration_ms\)%22,%22queryOptions%22:\{%22quickRange%22:%2215d%22}})
## Multiple aggregation functions [#multiple-aggregation-functions]
**SQL:**
```sql
SELECT COUNT(*) AS TotalDuration, SUM(req_duration_ms) AS TotalDuration, AVG(Price) AS AverageDuration
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| summarize TotalOrders = count(), TotalDuration = sum( req_duration_ms), AverageDuration = avg(req_duration_ms)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20summarize%20TotalOrders%20=%20count\(\),%20TotalDuration%20=%20sum\(req_duration_ms\),%20AverageDuration%20=%20avg\(req_duration_ms\)%20%22,%22queryOptions%22:\{%22quickRange%22:%2215d%22}})
## Aggregation with GROUP BY and ORDER BY [#aggregation-with-group-by-and-order-by]
**SQL:**
```sql
SELECT status, COUNT(*) AS TotalStatus, SUM(resp_header_size_bytes) AS TotalRequest
FROM [Sample-http-logs];
GROUP BY status
ORDER BY TotalSpent DESC;
```
**APL:**
```kusto
['sample-http-logs']
| summarize TotalStatus = count(), TotalRequest = sum(resp_header_size_bytes) by status
| order by TotalRequest desc
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20summarize%20TotalStatus%20=%20count\(\),%20TotalRequest%20=%20sum\(resp_header_size_bytes\)%20by%20status\n|%20order%20by%20TotalRequest%20desc%20%22,%22queryOptions%22:\{%22quickRange%22:%2215d%22}})
## Count with a condition [#count-with-a-condition]
**SQL:**
```sql
SELECT COUNT(*) AS HighContentStatus
FROM [Sample-http-logs];
WHERE resp_header_size_bytes > 1;
```
**APL:**
```kusto
['sample-http-logs']
| where resp_header_size_bytes > 1
| summarize HighContentStatus = count()
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20where%20resp_header_size_bytes%20%3E%201\n|%20summarize%20HighContentStatus%20=%20count\(\)%20%20%20%22,%22queryOptions%22:\{%22quickRange%22:%2215d%22}})
## Aggregation with HAVING [#aggregation-with-having]
**SQL:**
```sql
SELECT Status
FROM [Sample-http-logs];
GROUP BY Status
HAVING COUNT(*) > 10;
```
**APL:**
```kusto
['sample-http-logs']
| summarize OrderCount = count() by status
| where OrderCount > 10
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20summarize%20OrderCount%20=%20count\(\)%20by%20status\n|%20where%20OrderCount%20%3E%2010%20%20%20%22,%22queryOptions%22:\{%22quickRange%22:%2215d%22}})
## Count occurrences of a value in a field [#count-occurrences-of-a-value-in-a-field]
**SQL:**
```sql
SELECT content_type, COUNT(*) AS RequestCount
FROM [Sample-http-logs];
WHERE content_type = ‘text/csv’;
```
**APL:**
```kusto
['sample-http-logs'];
| where content_type == 'text/csv'
| summarize RequestCount = count()
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20where%20content_type%20==%20%27text/csv%27%20\n|%20summarize%20RequestCount%20=%20count\(\)%20%20%20%22,%22queryOptions%22:\{%22quickRange%22:%2215d%22}})
## String Functions: [#string-functions]
## Length of a string [#length-of-a-string]
**SQL:**
```sql
SELECT LEN(Status) AS NameLength
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| extend NameLength = strlen(status)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20extend%20NameLength%20=%20strlen\(status\)%20%22,%22queryOptions%22:\{%22quickRange%22:%2215d%22}})
## Concatentation [#concatentation]
**SQL:**
```sql
SELECT CONCAT(content_type, ' ', method) AS FullLength
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| extend FullLength = strcat(content_type, ' ', method)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20extend%20FullLength%20=%20strcat\(content_type,%20%27%20%27,%20method\)%20%20%22,%22queryOptions%22:\{%22quickRange%22:%2215d%22}})
## Substring [#substring]
**SQL:**
```sql
SELECT SUBSTRING(content_type, 1, 10) AS ShortDescription
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| extend ShortDescription = substring(content_type, 0, 10)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20extend%20ShortDescription%20=%20substring\(content_type,%200,%2010\)%20%22,%22queryOptions%22:\{%22quickRange%22:%2215d%22}})
## Left and Right [#left-and-right]
**SQL:**
```sql
SELECT LEFT(content_type, 3) AS LeftTitle, RIGHT(content_type, 3) AS RightTitle
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| extend LeftTitle = substring(content_type, 0, 3), RightTitle = substring(content_type, strlen(content_type) - 3, 3)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20extend%20LeftTitle%20=%20substring\(content_type,%200,%203\),%20RightTitle%20=%20substring\(content_type,%20strlen\(content_type\)%20-%203,%203\)%20%20%22,%22queryOptions%22:\{%22quickRange%22:%2215d%22}})
## Replace [#replace]
**SQL:**
```sql
SELECT REPLACE(StaTUS, 'old', 'new') AS UpdatedStatus
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| extend UpdatedStatus = replace('old', 'new', status)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20extend%20UpdatedStatus%20=%20replace\(%27old%27,%20%27new%27,%20status\)%20%20%22,%22queryOptions%22:\{%22quickRange%22:%2215d%22}})
## Upper and Lower [#upper-and-lower]
**SQL:**
```sql
SELECT UPPER(FirstName) AS UpperFirstName, LOWER(LastName) AS LowerLastName
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| project upperFirstName = toupper(content_type), LowerLastNmae = tolower(status)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20project%20upperFirstName%20=%20toupper\(content_type\),%20LowerLastNmae%20=%20tolower\(status\)%20%22,%22queryOptions%22:\{%22quickRange%22:%2230d%22}})
## LTrim and RTrim [#ltrim-and-rtrim]
**SQL:**
```sql
SELECT LTRIM(content_type) AS LeftTrimmedFirstName, RTRIM(content_type) AS RightTrimmedLastName
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| extend LeftTrimmedFirstName = trim_start(' ', content_type), RightTrimmedLastName = trim_end(' ', content_type)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20project%20LeftTrimmedFirstName%20=%20trim_start\(%27%27,%20content_type\),%20RightTrimmedLastName%20=%20trim_end\(%27%27,%20content_type\)%20%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Trim [#trim]
**SQL:**
```sql
SELECT TRIM(content_type) AS TrimmedFirstName
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| extend TrimmedFirstName = trim(' ', content_type)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20extend%20TrimmedFirstName%20=%20trim\(%27%20%27,%20content_type\)%20%22,%22queryOptions%22:\{%22quickRange%22:%2230d%22}})
## Reverse [#reverse]
**SQL:**
```sql
SELECT REVERSE(Method) AS ReversedFirstName
FROM [Sample-http-logs];
```
**APL:**
```kusto
['sample-http-logs']
| extend ReversedFirstName = reverse(method)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20project%20ReservedFirstnName%20=%20reverse\(method\)%20%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Case-insensitive search [#case-insensitive-search]
**SQL:**
```sql
SELECT Status, Method
FROM “Sample-http-logs”
WHERE LOWER(Method) LIKE 'get’';
```
**APL:**
```kusto
['sample-http-logs']
| where tolower(method) contains 'GET'
| project status, method
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20where%20tolower\(method\)%20contains%20%27GET%27\n|%20project%20status,%20method%22,%22queryOptions%22:\{%22quickRange%22:%2230d%22}})
## Take the First Step Today: Dive into APL [#take-the-first-step-today-dive-into-apl]
The journey from SQL to APL might seem daunting at first, but with the right approach, it can become an empowering transition. It’s about expanding your data query capabilities to leverage the advanced, versatile, and fast querying infrastructure that APL provides. In the end, the goal is to enable you to draw more value from your data, make faster decisions, and ultimately propel your business forward.
Try converting some of your existing SQL queries to APL and observe the performance difference. Explore the Axiom Processing Language and start experimenting with its unique features.
**Happy querying.**
---
# Migrate from Sumo Logic Query Language to APL
Source: https://axiom.co/docs/apl/guides/migrating-from-sumologic-to-apl
## Introduction [#introduction]
In the sphere of data analytics and log management, being able to query data efficiently and effectively is of paramount importance.
This guide dives into why APL could be a superior choice for your data needs, the differences between Sumo Logic and APL, and the potential benefits you could reap from migrating from Sumo Logic to APL. Let’s explore the compelling case for APL as a robust, powerful tool for handling your complex data querying requirements.
APL is powerful and flexible and uses a pipe (`|`) operator for chaining commands, and it provides a richer set of functions and operators for more complex queries.
## Benefits of Migrating from SumoLogic to APL [#benefits-of-migrating-from-sumologic-to-apl]
* **Scalability and Performance:** APL was built with scalability in mind. It handles very large volumes of data more efficiently and provides quicker query execution compared to Sumo Logic, making it a suitable choice for organizations with extensive data requirements. APL is designed for high-speed data ingestion, real-time analytics, and providing insights across structured, semi-structured data. It’s also optimized for time-series data analysis, making it highly efficient for log and telemetry data.
* **Advanced Analytics Capabilities:** With APL’s support for aggregation and conversion functions and more advanced statistical visualization, organizations can derive more sophisticated insights from their data.
## Query Examples [#query-examples]
Let’s see some examples of how to convert SumoLogic queries to APL.
## Parse, and Extract Operators [#parse-and-extract-operators]
Extract `from` and `to` fields. For example, if a raw event contains `From: Jane To: John,` then `from=Jane and to=John.`
**Sumo Logic:**
```bash
* | parse "From: * To: *" as (from, to)
```
**APL:**
```kusto
['sample-http-logs']
| extend (method) == extract("From: (.*?) To: (.*)", 1, method)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20extend%20\(method\)%20==%20extract\(%22From:%20\(.*?\)%20To:%20\(.*\)%22,%201,%20method\)%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Extract Source IP with Regex [#extract-source-ip-with-regex]
In this section, a regular expression identifies the four octets of an IP address. This helps you efficiently extract the source IP addresses from the data.
**Sumo Logic:**
```bash
*| parse regex "(\\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"
```
**APL:**
```kusto
['sample-http-logs']
| extend ip = extract("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})", 1, "23.45.67.90")
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20extend%20ip%20=%20extract\(%22\(\\\d\{1,3}\\\\.\\\d\{1,3}\\\\.\\\d\{1,3}\\\\.\\\d\{1,3}\)%22,%201,%20%2223.45.67.90%22\)%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Extract Visited URLs [#extract-visited-urls]
This section focuses on identifying all URL addresses visited and extracting them to populate the "url" field. This method provides an organized way to track user activity using APL.
**Sumo Logic:**
```bash
_sourceCategory=apache
| parse "GET * " as url
```
**APL:**
```kusto
['sample-http-logs']
| where method == "GET"
| project url = extract(@"(\w+)", 1, method)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B'sample-http-logs'%5D%5Cn%7C%20where%20method%20%3D%3D%20%5C%22GET%5C%22%5Cn%7C%20project%20url%20%3D%20extract\(%40%5C%22\(%5C%5Cw%2B\)%5C%22%2C%201%2C%20method\)%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
## Extract Data from Source Category Traffic [#extract-data-from-source-category-traffic]
This section aims to identify and analyze traffic originating from the Source Category. It extracts critical information including the source addresses, the sizes of messages transmitted, and the URLs visited, providing valuable insights into the nature of the traffic using APL.
**Sumo Logic:**
```bash
_sourceCategory=apache
| parse "* " as src_IP
| parse " 200 * " as size
| parse "GET * " as url
```
**APL:**
```kusto
['sample-http-logs']
| extend src_IP = extract("^(\\S+)", 0, uri)
| extend size = extract("^(\\S+)", 1, status)
| extend url = extract("^(\\S+)", 1, method)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%5Cn%7C%20extend%20src_IP%20%3D%20extract\(%5C%22%5E\(%40S%2B\)%5C%22%2C%200%2C%20uri\)%5Cn%7C%20extend%20size%20%3D%20extract\(%5C%22%5E\(%40S%2B\)%5C%22%2C%201%2C%20status\)%5Cn%7C%20extend%20url%20%3D%20extract\(%5C%22%5E\(%40S%2B\)%5C%22%2C%201%2C%20method\)%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
## Calculate Bytes Transferred per Source IP [#calculate-bytes-transferred-per-source-ip]
In this part, compute the total number of bytes transferred to each source IP address. This allows you to gauge the data volume associated with each source using APL.
**Sumo Logic:**
```bash
_sourceCategory=apache
| parse "* " as src_IP
| parse " 200 * " as size
| count, sum(size) by src_IP
```
**APL:**
```kusto
['sample-http-logs']
| extend src_IP = extract("^(\\S+)", 1, uri)
| extend size = toint(extract("200", 0, status))
| summarize count(), sum(size) by src_IP
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20extend%20size%20=%20toint\(extract\(%22200%22,%200,%20status\)\)\n|%20summarize%20count\(\),%20sum\(size\)%20by%20status%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Compute Average HTTP Response Size [#compute-average-http-response-size]
In this section, calculate the average size of all successful HTTP responses. This metric helps you understand the typical data load associated with successful server responses.
**Sumo Logic:**
```bash
_sourceCategory=apache
| parse " 200 * " as size
| avg(size)
```
**APL:**
Get the average value from a string:
```kusto
['sample-http-logs']
| extend number = todouble(extract("\\d+(\\.\\d+)?", 0, status))
| summarize Average = avg(number)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20extend%20number%20=%20todouble\(status\)\n|%20summarize%20Average%20=%20avg\(number\)%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Extract Data with Missing Size Field (NoDrop) [#extract-data-with-missing-size-field-nodrop]
This section focuses on extracting key parameters like `src`, `size`, and `URL`, even when the `size` field may be absent from the log message.
**Sumo Logic:**
```bash
_sourceCategory=apache
| parse "* " as src_IP
| parse " 200 * " as size nodrop
| parse "GET * " as url
```
**APL:**
```kusto
['sample-http-logs']
| where content_type == "text/css"
| extend src_IP = extract("^(\\S+)", 1, ['id'])
| extend size = toint(extract("(\\w+)", 1, status))
| extend url = extract("GET", 0, method)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=%7B%22apl%22%3A%22%5B%27sample-http-logs%27%5D%20%7C%20where%20content_type%20%3D%3D%20%5C%22text%2Fcss%5C%22%20%7C%20extend%20src_IP%20%3D%20extract\(%5C%22%5E\(%5C%5CS%2B\)%5C%22%2C%201%2C%20%5B%27id%27%5D\)%20%7C%20extend%20size%20%3D%20toint\(extract\(%5C%22\(%5C%5Cw%2B\)%5C%22%2C%201%2C%20status\)\)%20%7C%20extend%20url%20%3D%20extract\(%5C%22GET%5C%22%2C%200%2C%20method\)%22%2C%22queryOptions%22%3A%7B%22quickRange%22%3A%2230d%22%7D%7D)
## Count URL Visits [#count-url-visits]
This section is dedicated to identifying the frequency of visits to a specific URL. By counting these occurrences, you can gain insights into website popularity and user behavior.
**Sumo Logic:**
```bash
_sourceCategory=apache
| parse "GET * " as url
| count by url
```
**APL:**
```kusto
['sample-http-logs']
| extend url = extract("^(\\S+)", 1, method)
| summarize Count = count() by url
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?qid=RsnK4jahgNC-rviz3s)
## Page Count by Source IP [#page-count-by-source-ip]
In this section, identify the total number of pages associated with each source IP address. This analysis allows you to understand the volume of content generated or hosted by each source.
**Sumo Logic:**
```bash
_sourceCategory=apache
| parse "* -" as src_ip
| count by src_ip
```
**APL:**
```kusto
['sample-http-logs']
| extend src_ip = extract(".*", 0, ['id'])
| summarize Count = count() by src_ip
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20extend%20src_ip%20=%20extract\(%22.*%22,%200,%20%20\[%27id%27]\)\n|%20summarize%20Count%20=%20count\(\)%20by%20src_ip%22,%22queryOptions%22:\{%22quickRange%22:%2230d%22}})
## Reorder Pages by Load Frequency [#reorder-pages-by-load-frequency]
This section aims to identify the total number of pages per source IP address. Following this, the pages will be reordered based on the frequency of loads, which will provide insights into the most accessed content.
**Sumo Logic:**
```bash
_sourceCategory=apache
| parse "* " as src_ip
| parse "GET * " as url
| count by url
| sort by _count
```
**APL:**
```kusto
['sample-http-logs']
| extend src_ip = extract(".*", 0, ['id'])
| extend url = extract("(GET)", 1, method)
| where isnotnull(url)
| summarize _count = count() by url, src_ip
| order by _count desc
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20extend%20src_ip%20=%20extract\(%22.*%22,%200,%20\[%27id%27]\)\n|%20extend%20url%20=%20extract\(%22\(GET\)%22,%201,%20method\)\n|%20where%20isnotnull\(url\)\n|%20summarize%20_count%20=%20count\(\)%20by%20url,%20src_ip\n|%20order%20by%20_count%20desc%22,%22queryOptions%22:\{%22quickRange%22:%2230d%22}})
## Identify the top 10 requested pages [#identify-the-top-10-requested-pages]
**Sumo Logic:**
```bash
* | parse "GET * " as url
| count by url
| top 10 url by _count
```
**APL:**
```kusto
['sample-http-logs']
| where method == "GET"
| top 10 by method desc
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20where%20method%20==%20%22GET%22\n|%20top%2010%20by%20method%20desc%22,%22queryOptions%22:\{%22quickRange%22:%2230d%22}})
## Top 10 IPs by Bandwidth Usage [#top-10-ips-by-bandwidth-usage]
This section aims to identify the top 10 source IP addresses based on their bandwidth consumption.
**Sumo Logic:**
```bash
_sourceCategory=apache
| parse " 200 * " as size
| parse "* -" as src_ip
| sum(size) as total_bytes by src_ip
| top 10 src_ip by total_bytes
```
**APL:**
```kusto
['sample-http-logs']
| extend size = req_duration_ms
| summarize total_bytes = sum(size) by ['id']
| top 10 by total_bytes desc
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20extend%20size%20=%20req_duration_ms\n|%20summarize%20total_bytes%20=%20sum\(size\)%20by%20\[%27id%27]\n|%20top%2010%20by%20total_bytes%20desc%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Top 6 IPs by Number of Hits [#top-6-ips-by-number-of-hits]
This section focuses on identifying the top six source IP addresses according to the number of hits they generate. This will provide insight into the most frequently accessed or active sources in the network.
**Sumo Logic**
```bash
_sourceCategory=apache
| parse "* -" as src_ip
| count by src_ip
| top 100 src_ip by _count
```
**APL:**
```kusto
['sample-http-logs']
| extend src_ip = extract("^(\\S+)", 1, user_agent)
| summarize _count = count() by src_ip
| top 6 by _count desc
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20summarize%20_count%20=%20count\(\)%20by%20user_agent\n|%20order%20by%20_count%20desc\n|%20limit%206%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Timeslice and Transpose [#timeslice-and-transpose]
For the Source Category `"apache"`, count by status\_code and timeslice of 1 hour.
**Sumo Logic:**
```bash
_sourceCategory=apache*
| parse "HTTP/1.1\" * * \"" as (status_code, size)
| timeslice 1h
| count by _timeslice, status_code
```
**APL:**
```kusto
['sample-http-logs']
| extend status_code = extract("^(\\S+)", 1, method)
| where status_code == "POST"
| summarize count() by status_code, bin(_time, 1h)
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20where%20method%20==%20%22POST%22\n|%20summarize%20count\(\)%20by%20method,%20bin\(_time,%201h\)%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Hourly Status Code Count for "Text" Source [#hourly-status-code-count-for-text-source]
This section aims to count instances by `status_code`, grouped into one-hour timeslices, and then transpose `status_code` to column format. This helps you understand the frequency and timing of different status codes.
**Sumo Logic:**
```bash
_sourceCategory=text*
| parse "HTTP/1.1\" * * \"" as (status_code, size)
| timeslice 1h
| count by _timeslice, status_code
| transpose row _timeslice column status_code
```
**APL:**
```
['sample-http-logs']
| where content_type startswith 'text/css'
| extend status_code= status
| summarize count() by bin(_time, 1h), content_type, status_code
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20where%20content_type%20startswith%20%27text/css%27\n|%20extend%20status_code%20=%20status\n|%20summarize%20count\(\)%20by%20bin\(_time,%201h\),%20content_type,%20status_code%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Status Code Count in 5 Time Buckets [#status-code-count-in-5-time-buckets]
This example performs a count by 'status\_code', sliced into five time buckets across the search results. This will help analyze the distribution and frequency of status codes over specific time intervals.
**Sumo Logic:**
```bash
_sourceCategory=apache*
| parse "HTTP/1.1\" * * \"" as (status_code, size)
| timeslice 5 buckets
| count by _timeslice, status_code
```
**APL:**
```kusto
['sample-http-logs']
| where content_type startswith 'text/css'
| extend p=("HTTP/1.1\" * * \""), tostring( is_tls)
| extend status_code= status
| summarize count() by bin(_time, 12m), status_code
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20where%20content_type%20startswith%20%27text/css%27\n|%20extend%20p=\(%22HTTP/1.1\\%22%20*%20*%20\\%22%22\),%20tostring\(is_tls\)\n|%20extend%20status_code%20=%20status\n|%20summarize%20count\(\)%20by%20bin\(_time,%2012m\),%20status_code%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Grouped Status Code Count [#grouped-status-code-count]
This example counts messages by status code categories. It groups all messages with status codes in the `200s`, `300s`, `400s`, and `500s` together, and also groups the method requests with the `GET`, `POST`, `PUT`, `DELETE` attributes. This provides an overview of the response status distribution.
**Sumo Logic:**
```bash
_sourceCategory=Apache/Access
| timeslice 15m
| if (status_code matches "20*",1,0) as resp_200
| if (status_code matches "30*",1,0) as resp_300
| if (status_code matches "40*",1,0) as resp_400
| if (status_code matches "50*",1,0) as resp_500
| if (!(status_code matches "20*" or status_code matches "30*" or status_code matches "40*" or status_code matches "50*"),1,0) as resp_others
| count(*), sum(resp_200) as tot_200, sum(resp_300) as tot_300, sum(resp_400) as tot_400, sum(resp_500) as tot_500, sum(resp_others) as tot_others by _timeslice
```
**APL:**
```kusto
['sample-http-logs']
| extend MethodCategory = case(
method == "GET", "GET Requests",
method == "POST", "POST Requests",
method == "PUT", "PUT Requests",
method == "DELETE", "DELETE Requests",
"Other Methods")
| extend StatusCodeCategory = case(
status startswith "2", "Success",
status startswith "3", "Redirection",
status startswith "4", "Client Error",
status startswith "5", "Server Error",
"Unknown Status")
| extend ContentTypeCategory = case(
content_type == "text/csv", "CSV",
content_type == "application/json", "JSON",
content_type == "text/html", "HTML",
"Other Types")
| summarize Count=count() by bin_auto(_time), StatusCodeCategory, MethodCategory, ContentTypeCategory
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20extend%20MethodCategory%20=%20case\(\n%20%20%20method%20==%20%22GET%22,%20%22GET%20Requests%22,\n%20%20%20method%20==%20%22POST%22,%20%22POST%20Requests%22,\n%20%20%20method%20==%20%22PUT%22,%20%22PUT%20Requests%22,\n%20%20%20method%20==%20%22DELETE%22,%20%22DELETE%20Requests%22,\n%20%20%20%22Other%20Methods%22\)\n|%20extend%20StatusCodeCategory%20=%20case\(\n%20%20%20status%20startswith%20%222%22,%20%22Success%22,\n%20%20%20status%20startswith%20%223%22,%20%22Redirection%22,\n%20%20%20status%20startswith%20%224%22,%20%22Client%20Error%22,\n%20%20%20status%20startswith%20%225%22,%20%22Server%20Error%22,\n%20%20%20%22Unknown%20Status%22\)\n|%20extend%20ContentTypeCategory%20=%20case\(\n%20%20%20content_type%20==%20%22text/csv%22,%20%22CSV%22,\n%20%20%20content_type%20==%20%22application/json%22,%20%22JSON%22,\n%20%20%20content_type%20==%20%22text/html%22,%20%22HTML%22,\n%20%20%20%22Other%20Types%22\)\n|%20summarize%20Count=count\(\)%20by%20bin_auto\(_time\),%20StatusCodeCategory,%20MethodCategory,%20ContentTypeCategory%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Conditional Operators [#conditional-operators]
For the Source Category `"apache"`, find all messages with a client error status code (40\*):
**Sumo Logic:**
```bash
_sourceCategory=apache*
| parse "HTTP/1.1\" * * \"" as (status_code, size)
| where status_code matches "40*"
```
**APL:**
```kusto
['sample-http-logs']
| where content_type startswith 'text/css'
| extend p = ("HTTP/1.1\" * * \"")
| where status == "200"
```
[Run in Playground](https://play.axiom.co/axiom-play-qf1k/query?initForm=\{%22apl%22:%22\[%27sample-http-logs%27]\n|%20where%20content_type%20startswith%20%27text/css%27\n|%20extend%20p%20=%20\(%22HTTP/1.1\\%22%20*%20*%20\\%22%22\)\n|%20where%20status%20==%20%22200%22%22,%22queryOptions%22:\{%22quickRange%22:%2290d%22}})
## Browser-based Hit Count [#browser-based-hit-count]
This query example counts the number of hits by browser. This analysis provides insights into the different browsers used to access the source and their respective frequencies.
**Sumo Logic:**
```bash
_sourceCategory=Apache/Access
| extract "\"[A-Z]+ \S+ HTTP/[\d\.]+\" \S+ \S+ \S+ \"(?