### Install Axiom Go SDK Source: https://axiom.co/docs/guides/go Install the Axiom Go SDK using the go get command. ```shell go get github.com/axiomhq/axiom-go/axiom ``` -------------------------------- ### Install axiom-hostmetrics with Homebrew Source: https://axiom.co/docs/query-data/metrics Install the axiom-hostmetrics CLI tool using Homebrew for quick setup of OTel metrics streaming to Axiom. ```sh brew install axiomhq/tap/axiom-hostmetrics ``` -------------------------------- ### Install Axiom Loki Proxy using go get Source: https://axiom.co/docs/send-data/loki-multiplexer Install or update the axiom-loki-proxy using the go get command. This method requires Go to be installed on your system. ```bash go get -u github.com/axiomhq/axiom-loki-proxy/cmd/axiom-loki-proxy ``` -------------------------------- ### Run Axiom Loki Proxy Locally Source: https://axiom.co/docs/send-data/loki-multiplexer Execute the axiom-loki-proxy binary after installation. This command starts the proxy service, ready to receive logs. ```bash ./axiom-loki-proxy ``` -------------------------------- ### Source Script and Start Claude Code Source: https://axiom.co/docs/guides/opentelemetry-claude-code This command sources the setup script to export necessary environment variables and then starts the Claude Code application. Ensure the setup script is in your current directory. ```bash source ./setup-otel.sh && claude ``` -------------------------------- ### Install axiom-hostmetrics with Go Source: https://axiom.co/docs/llms-full.txt Install the axiom-hostmetrics CLI using Go if Homebrew is not available. ```sh go install github.com/axiom/axiom-hostmetrics/cmd/axiom-hostmetrics@latest ``` -------------------------------- ### Install Axiom Syslog Proxy using Go command Source: https://axiom.co/docs/send-data/syslog-proxy Install the Axiom Syslog Proxy directly using the 'go install' command. ```shell go install github.com/axiomhq/axiom-syslog-proxy/cmd/axiom-syslog-proxy@latest ``` -------------------------------- ### Install axiom-hostmetrics with Go Source: https://axiom.co/docs/query-data/metrics Install the axiom-hostmetrics CLI tool using Go for streaming OTel metrics to Axiom. ```sh go install github.com/axiomhq/axiom-hostmetrics/cmd/axiom-hostmetrics@latest ``` -------------------------------- ### Install Axiom CLI using Go Source: https://axiom.co/docs/reference/cli Install the Axiom CLI using the Go programming language. Ensure you have Go installed before running this command. ```bash go install github.com/axiomhq/cli/cmd/axiom@latest ``` -------------------------------- ### Install Axiom MCP Server Binary Source: https://axiom.co/docs/console/intelligence/mcp-server Installs the latest Axiom MCP Server binary from GitHub releases using go install. ```bash go install github.com/axiomhq/axiom-mcp@latest ``` -------------------------------- ### Install Axiom Python SDK on Windows Source: https://axiom.co/docs/guides/python Install the axiom-py package using pip on Windows. ```shell py -m pip install axiom-py ``` -------------------------------- ### Start Node.js Application in Production Source: https://axiom.co/docs/guides/opentelemetry-nodejs Start your built Node.js application in production mode. ```bash npm start ``` -------------------------------- ### Install Project Dependencies Source: https://axiom.co/docs/llms-full.txt Run this command in the root of your project to install all necessary packages listed in package.json. ```bash npm install ``` -------------------------------- ### Install Axiom CLI using Homebrew Source: https://axiom.co/docs/reference/cli Install the Axiom CLI using Homebrew. This command installs Axiom command globally. ```bash brew install --cask axiomhq/tap/axiom ``` -------------------------------- ### Install dependencies from requirements.txt Source: https://axiom.co/docs/guides/opentelemetry-python Install all Python dependencies listed in the requirements.txt file using pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install @axiomhq/logging Source: https://axiom.co/docs/guides/javascript Install the @axiomhq/logging library using npm. This library provides structured logging capabilities. ```bash npm install @axiomhq/logging ``` -------------------------------- ### Install Axiom Python SDK using pip3 Source: https://axiom.co/docs/guides/python Install the axiom-py package using pip3. ```shell pip3 install axiom-py ``` -------------------------------- ### Install Autoevals Source: https://axiom.co/docs/ai-engineering/evaluate/scorers Install the autoevals library using npm. This is a prerequisite for using the prebuilt scorers. ```bash npm install autoevals ``` -------------------------------- ### Install @axiomhq/js Source: https://axiom.co/docs/guides/javascript Install the @axiomhq/js library using npm. This is the first step to integrate Axiom into your JavaScript application. ```shell npm install @axiomhq/js ``` -------------------------------- ### Get the role of the first message in a GenAI conversation Source: https://axiom.co/docs/apl/scalar-functions/genai-functions/genai-get-role Retrieves the role of the very first message (index 0) in a GenAI conversation. This example counts conversations starting with a 'system' role. ```kusto ['otel-demo-genai'] | extend first_role = genai_get_role(['attributes.gen_ai.input.messages'], 0) | summarize conversations_with_system = countif(first_role == 'system'), total_conversations = count() ``` -------------------------------- ### Main HTTP Server Setup and Signal Handling Source: https://axiom.co/docs/llms-full.txt This Go code sets up a basic HTTP server with OpenTelemetry instrumentation. It includes signal handling for graceful shutdown and demonstrates server configuration like timeouts and context. ```go // main.go package main import ( "context" "fmt" "log" "math/rand" "net" "net/http" "os" "os/signal" time "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 } ``` -------------------------------- ### Install Axiom CLI from Source Source: https://axiom.co/docs/reference/cli Build and install the Axiom CLI binary from its source code. This requires cloning the repository and using the make command. ```bash git clone https://github.com/axiomhq/cli.git cd cli make install ``` -------------------------------- ### Get Schema Use Case Example Source: https://axiom.co/docs/llms-full.txt Example of querying the schema for 'sample-http-logs' dataset using the getschema operator in APL. ```kusto ['sample-http-logs'] | getschema ``` -------------------------------- ### Basic MPL Query Example Source: https://axiom.co/docs/llms-full.txt This example queries the otel-demo-metrics dataset's go.memory.used metric. It filters results to the 'checkout' deployment and aggregates values over 5-minute time windows into their average. ```kusto `otel-demo-metrics`:`go.memory.used` | where `k8s.deployment.name` == "checkout" | align to 5m using avg ``` -------------------------------- ### Get current time in APL (equivalent to SQL) Source: https://axiom.co/docs/apl/scalar-functions/datetime-functions/now This APL example demonstrates getting the current time, equivalent to SQL's CURRENT_TIMESTAMP. ```kusto ['dataset'] | extend current_time = now() ``` -------------------------------- ### Create Project Directory Source: https://axiom.co/docs/guides/opentelemetry-cloudflare-workers Create a new directory for your project and navigate into it. ```bash mkdir my-axiom-worker && cd my-axiom-worker ``` -------------------------------- ### Get current time in APL (equivalent to Splunk) Source: https://axiom.co/docs/apl/scalar-functions/datetime-functions/now This APL example demonstrates getting the current time, equivalent to the Splunk SPL now() function. ```kusto | extend current_time = now() ``` -------------------------------- ### Top 5 Cities Generating GET HTTP Requests Source: https://axiom.co/docs/apl/aggregation-function/topkif Find the top 5 cities that are generating the most GET HTTP requests. This example uses topkif on the 'geo.city' field, filtered by requests where the method is 'GET'. ```kusto ['sample-http-logs'] | summarize topkif(['geo.city'], 5, method == 'GET') ``` -------------------------------- ### Complete Example: Instrumenting AI SDK with Axiom Source: https://axiom.co/docs/llms-full.txt This example demonstrates how `wrapAISDKModel`, `wrapTool`, and `withSpan` work together. It shows wrapping the AI model client, defining and wrapping tools, and using `withSpan` to tie everything together. ```typescript 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_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}
; } ``` -------------------------------- ### Splunk SPL now() example Source: https://axiom.co/docs/llms-full.txt This snippet shows how to get the current time in Splunk SPL using the `now()` function. ```sql ... | eval current_time=now() ``` -------------------------------- ### Splunk SPL len Function Example Source: https://axiom.co/docs/apl/scalar-functions/array-functions/len In Splunk SPL, the len function is used within eval or where expressions to get string length or array size. This example shows how to evaluate the length of a 'uri' field. ```sql ... | eval uri_length=len(uri) ``` -------------------------------- ### Get current timestamp in SQL Source: https://axiom.co/docs/apl/scalar-functions/datetime-functions/now This SQL example shows how to retrieve the current date and time using CURRENT_TIMESTAMP. ```sql SELECT CURRENT_TIMESTAMP AS current_time; ``` -------------------------------- ### OpenAPI Specification for Get Annotations Source: https://axiom.co/docs/restapi/endpoints/getAnnotations This OpenAPI 3.0.0 specification defines the GET /annotations endpoint. It details the request parameters, including filtering by datasets, start time, and end time, as well as the structure of the Annotation response object. ```yaml openapi: 3.0.0 info: description: A public and stable API for interacting with axiom services title: Axiom termsOfService: http://axiom.co/terms contact: name: Axiom support team url: https://axiom.co email: hello@axiom.co license: name: Apache 2.0 url: https://www.apache.org/licenses/LICENSE-2.0.html version: 2.0.0 servers: - url: https://api.axiom.co/v2/ security: - bearerAuth: [] paths: /annotations: get: tags: - annotations description: Get annotations operationId: getAnnotations parameters: - description: 'Optional: Filter for dataset names.' name: datasets in: query style: form explode: false schema: type: array items: type: string - description: >- Optional: Filter for events after this date. Use RFC3339 time format. name: start in: query schema: type: string - description: >- Optional: Filter for events before this date. Use RFC3339 time format. name: end in: query schema: type: string responses: '200': description: Annotation content: application/json: schema: type: array items: $ref: '#/components/schemas/Annotation' security: - Auth: - annotations|read components: schemas: Annotation: type: object required: - id - time - datasets - type properties: datasets: description: >- array{text}
; } ``` -------------------------------- ### Install next-axiom Package Source: https://axiom.co/docs/send-data/nextjs Install the next-axiom package using npm. Ensure you have the necessary environment variables configured for your Axiom dataset and token. ```sh npm install --save next-axiom ``` -------------------------------- ### APL not Example: Identify Non-Standard HTTP Methods Source: https://axiom.co/docs/apl/scalar-functions/mathematical-functions/not Use the 'not' function to filter for HTTP requests that do not use standard GET or HEAD methods. This helps identify potentially suspicious activity. ```kusto ['sample-http-logs'] | extend is_safe_method = (method == 'GET' or method == 'HEAD') | where not(is_safe_method) | project _time, id, status, method, uri ``` -------------------------------- ### Complete Support Ticket Classification Evaluation Source: https://axiom.co/docs/ai-engineering/evaluate/write-evaluations A full evaluation setup including capability definition, custom scorers for category and confidence, and test data. This example demonstrates classifying tickets into predefined categories. ```typescript import { Eval } from 'axiom/ai/evals'; import { Scorer } from 'axiom/ai/scorers'; import { generateObject } from 'ai'; import { openai } from '@ai-sdk/openai'; import { wrapAISDKModel } from 'axiom/ai'; import { z } from 'zod'; // The capability function async function classifyTicket({ subject, content }: { subject?: string; content: string }) { const result = await generateObject({ model: wrapAISDKModel(openai('gpt-4o-mini')), messages: [ { role: 'system', content: `You are a customer support engineer. Classify tickets as: spam, question, feature_request, or bug_report.`, }, { role: 'user', content: subject ? `Subject: ${subject}\n\n${content}` : content, }, ], schema: z.object({ category: z.enum(['spam', 'question', 'feature_request', 'bug_report']), confidence: z.number().min(0).max(1), }), }); return result.object; } ``` ```typescript // Custom scorer for category matching const CategoryScorer = Scorer( 'category-match', ({ output, expected }) => { return output.category === expected.category ? true : false; } ); // Custom scorer for high-confidence predictions const ConfidenceScorer = Scorer( 'high-confidence', ({ output }) => { return output.confidence >= 0.8 ? true : false; } ); // Define the evaluation Eval('spam-classification', { data: [ { input: { subject: "Congratulations! You've Won!", content: 'Claim your $500 gift card now!', }, expected: { category: 'spam', }, }, { input: { subject: 'How do I reset my password?', content: 'I forgot my password and need help resetting it.', }, expected: { category: 'question', }, }, { input: { subject: 'Feature request: Dark mode', content: 'Would love to see a dark mode option in the app.', }, expected: { category: 'feature_request', }, }, { input: { subject: 'App crashes on startup', content: 'The app crashes immediately when I try to open it.', }, expected: { category: 'bug_report', }, }, ], task: async ({ input }) => { return await classifyTicket(input); }, scorers: [CategoryScorer, ConfidenceScorer], metadata: { description: 'Classify support tickets into categories', }, }); ``` -------------------------------- ### Build and Run .NET App Source: https://axiom.co/docs/guides/send-logs-from-dotnet Builds and runs the .NET project. Ensure you are in the project directory. ```bash dotnet build dotnet run ``` -------------------------------- ### Initialize a Go Module Source: https://axiom.co/docs/guides/opentelemetry-go Creates a go.mod file to track your project's dependencies. Replace