### Create Monitor Example Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/users-tokens-monitors.md Example of creating a new monitor with specific configurations for name, description, query, operator, threshold, interval, range, and notifier IDs. ```go monitor, err := client.Monitors.Create(ctx, axiom.MonitorCreateRequest{ Monitor: axiom.Monitor{ Name: "High Error Rate", Description: "Alert on error rate > 5%", Type: axiom.MonitorTypeThreshold, APLQuery: "['events'] | where level == 'error' | stats count()", Operator: axiom.Above, Threshold: 100, Interval: 5 * time.Minute, Range: 10 * time.Minute, NotifierIDs: []string{"notifier-123"}, }, }) ``` -------------------------------- ### Install Axiom Go Client Source: https://github.com/axiomhq/axiom-go/blob/main/README.md Command to install the axiom-go library using the Go build tools. ```shell go get github.com/axiomhq/axiom-go ``` -------------------------------- ### Execute Query with Start Time Option Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/query.md Example of executing a query and setting the start time to 24 hours ago. ```go result, err := client.Query( ctx, "['dataset'] | limit 100", query.SetStartTime(time.Now().Add(-24*time.Hour)), ) ``` -------------------------------- ### Create API Token Example Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/users-tokens-monitors.md An example demonstrating how to create a new API token with a name, description, expiration, and specific dataset ingest capabilities. ```go token, err := client.Tokens.Create(ctx, axiom.APITokenCreateRequest{ Name: "Production Ingester", Description: "Token for production data ingestion", ExpiresAt: time.Now().AddDate(1, 0, 0), // 1 year DatasetCapabilities: map[string]axiom.DatasetCapabilities{ "events": { CanIngest: true, CanQuery: false, }, }, }) ``` -------------------------------- ### Example: List Annotations Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/notifiers-annotations-virtualfields.md Demonstrates how to list annotations within a specified time range using the AnnotationsService. Requires setting start and end times. ```go annotations, err := client.Annotations.List( ctx, "events", query.SetStartTime(time.Now().Add(-7*24*time.Hour)), query.SetEndTime(time.Now()), ) if err != nil { log.Fatal(err) } for _, annotation := range annotations { log.Printf("Annotation: %s at %v\n", annotation.Name, annotation.Created) } ``` -------------------------------- ### Install axiom-go Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/getting-started.md Add the axiom-go library to your Go project. Requires Go 1.21 or later. ```bash go get github.com/axiomhq/axiom-go ``` -------------------------------- ### Example: Create Annotation Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/notifiers-annotations-virtualfields.md Shows how to create a new annotation with a name, description, timestamp, and an optional URL. Ensure required fields are provided. ```go annotation, err := client.Annotations.Create(ctx, "events", axiom.AnnotationCreateRequest{ Name: "Deployment", Description: "Deployed v1.2.3 to production", Time: time.Now(), URL: "https://github.com/example/releases/tag/v1.2.3", }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Process Ingestion Failures Example Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/ingest.md Shows how to check for ingestion failures and iterate through the details of each failure. ```go status, err := client.Datasets.IngestEvents(ctx, "dataset", events) if err != nil { log.Fatal(err) } if status.Failed > 0 { for _, failure := range status.Failures { log.Printf("[%v] %s\n", failure.Timestamp, failure.Error) } } ``` -------------------------------- ### Create Annotation and Monitor Example Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/notifiers-annotations-virtualfields.md Demonstrates how to mark a deployment with an annotation and subsequently create a monitor to track the error rate after the deployment using the Axiom Go client. ```go // Mark a deployment in annotations annotation, err := client.Annotations.Create(ctx, "app-logs", axiom.AnnotationCreateRequest{ Name: "Release v2.0.0", Description: "Deployed new release with performance improvements", Time: time.Now(), URL: "https://github.com/myapp/releases/tag/v2.0.0", }) if err != nil { log.Fatal(err) } // Create a monitor to track error rate after deployment monitor, err := client.Monitors.Create(ctx, axiom.MonitorCreateRequest{ Monitor: axiom.Monitor{ Name: "Post-Deployment Errors", Description: "Check for errors after release", Type: axiom.MonitorTypeThreshold, APLQuery: "['app-logs'] | where level == 'error' | stats count()", Operator: axiom.Above, Threshold: 10, Interval: 1 * time.Minute, Range: 5 * time.Minute, }, }) ``` -------------------------------- ### Complete Monitor Setup and Test Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/users-tokens-monitors.md Demonstrates the full process of creating a notifier, setting up a threshold monitor, and testing its configuration. Ensure the notifier is created before the monitor, and handle potential errors at each step. ```go // Create notifier first notifier, err := client.Notifiers.Create(ctx, axiom.NotifierCreateRequest{ Name: "Slack", Type: axiom.NotifierTypeSlack, // ... notifier-specific config }) if err != nil { log.Fatal(err) } // Create monitor monitor, err := client.Monitors.Create(ctx, axiom.MonitorCreateRequest{ Monitor: axiom.Monitor{ Name: "High Latency Alert", Description: "Alert when p99 latency > 1s", Type: axiom.MonitorTypeThreshold, APLQuery: "['http-logs'] | stats pct(duration_ms, 99)", Operator: axiom.Above, Threshold: 1000, Interval: 5 * time.Minute, Range: 10 * time.Minute, AlertOnNoData: false, NotifierIDs: []string{notifier.ID}, }, }) if err != nil { log.Fatal(err) } // Test the monitor result, err := client.Monitors.Test(ctx, monitor.ID) if err != nil { log.Fatal(err) } log.Printf("Monitor test result: %d rows matched\n", result.Status.RowsMatched) ``` -------------------------------- ### Go Query Execution and Result Processing Example Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/query.md Demonstrates how to execute a query and process its results, including accessing status information and iterating over tables and rows. ```go result, err := client.Query(ctx, "['events'] | stats count() by level") if err != nil { log.Fatal(err) } log.Printf("Matched %d rows\n", result.Status.RowsMatched) log.Printf("Duration: %v\n", result.Status.Duration) for _, table := range result.Tables { log.Printf("Table: %s (%d rows)\n", table.Name, len(table.Columns[0])) for row := range table.Rows() { log.Printf("Row: %v\n", row) } } ``` -------------------------------- ### Ship Logs to Axiom with Zerolog Source: https://github.com/axiomhq/axiom-go/blob/main/examples/README.md Example of how to ship logs to Axiom using the popular Zerolog logging package. This demonstrates integration with a third-party logging library. ```go package main import ( "os" "github.com/axiomhq/axiom-go/zerolog" "github.com/rs/zerolog" ) func main() { logger := zerolog.New(axiom.NewAdapter(nil)).With().Timestamp().Logger() logger.Info("Hello Axiom!") logger.Warn().Int("value", 123).Msg("This is a warning") } ``` -------------------------------- ### Paginate Query Results Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/query.md Example demonstrating how to perform an initial query and then a follow-up query using cursor pagination to retrieve subsequent results. ```go // First query result, err := client.Query(ctx, "['dataset'] | limit 100") if err != nil { log.Fatal(err) } // Follow-up query with cursor pagination if result.Status.RowsMatched > 100 { nextResult, err := client.Query( ctx, "['dataset'] | limit 100", query.SetStartTime(result.Tables[0].Range.Start), query.SetEndTime(result.Tables[0].Range.End), query.SetCursor(result.Status.Cursor, false), ) } ``` -------------------------------- ### Complete Dashboard Management Example Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/organizations-dashboards.md Demonstrates the full lifecycle of dashboard management: creation with multiple charts, updating an existing dashboard by modifying charts and name, listing all dashboards, and finally deleting a dashboard. ```go // Create a dashboard with multiple charts dashboard, err := client.Dashboards.Create(ctx, axiom.DashboardCreateRequest{ Name: "System Performance", Description: "Real-time system metrics", Charts: []axiom.DashboardChart{ { Name: "CPU Usage", Query: "['metrics'] | stats avg(cpu) by host | timechart", Type: "timeseries", }, { Name: "Memory Usage", Query: "['metrics'] | stats avg(memory) by host | timechart", Type: "timeseries", }, { Name: "Error Count", Query: "['events'] | where level == 'error' | stats count()", Type: "number", }, }, }) if err != nil { log.Fatal(err) } log.Printf("Created dashboard: %s\n", dashboard.ID) // Later, update the dashboard updatedDashboard, err := client.Dashboards.Update(ctx, dashboard.ID, axiom.DashboardUpdateRequest{ Name: "System Performance v2", Charts: []axiom.DashboardChart{ { Name: "CPU Usage", Query: "['metrics'] | stats avg(cpu) by host, region | timechart", Type: "timeseries", }, { Name: "Memory Usage", Query: "['metrics'] | stats avg(memory) by host, region | timechart", Type: "timeseries", }, { Name: "Error Count", Query: "['events'] | where level == 'error' | stats count()", Type: "number", }, { Name: "Disk Usage", Query: "['metrics'] | stats avg(disk_usage) by host | timechart", Type: "timeseries", }, }, }) if err != nil { log.Fatal(err) } // Fetch and display all dashboards dashboards, err := client.Dashboards.List(ctx) if err != nil { log.Fatal(err) } for _, dash := range dashboards { log.Printf("Dashboard: %s (%d charts)\n", dash.Name, len(dash.Charts)) } // Delete dashboard err = client.Dashboards.Delete(ctx, dashboard.ID) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Ship Logs to Axiom with Apex Source: https://github.com/axiomhq/axiom-go/blob/main/examples/README.md Example of how to ship logs to Axiom using the popular Apex logging package. This demonstrates integration with a third-party logging library. ```go package main import ( "log" "github.com/axiomhq/axiom-go/apex" "github.com/apex/log" ) func main() { log.SetHandler(apex.NewHandler(nil)) log.Info("Hello Axiom!") log.Warnf("This is a warning with %d fields", 123) } ``` -------------------------------- ### SetStartTime Option Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/query.md Specifies the start of the query time window. ```APIDOC ## SetStartTime Specifies the start of the query time window. ```go func SetStartTime(startTime time.Time) Option ``` **Example:** ```go result, err := client.Query( ctx, "['dataset'] | limit 100", query.SetStartTime(time.Now().Add(-24*time.Hour)), ) ``` ``` -------------------------------- ### Ingest Events with Axiom Go Source: https://github.com/axiomhq/axiom-go/blob/main/examples/README.md Example of how to ingest events into Axiom using the axiom-go library. Ensure required environment variables are set. ```go package main import ( "context" "log" "github.com/axiomhq/axiom-go" ) func main() { client, err := axiom.NewClient() if err != nil { log.Fatalf("axiom.NewClient: %v", err) } ctx := context.Background() _, err = client.Ingest(ctx, "my-dataset", []axiom.Event{ { "message": "Hello Axiom!", }, { "message": "Another event", "extra_field": 123, }, }) if err != nil { log.Fatalf("client.Ingest: %v", err) } } ``` -------------------------------- ### Query Dataset with Axiom Go (Legacy) Source: https://github.com/axiomhq/axiom-go/blob/main/examples/README.md Example of how to query a dataset using the legacy query datatypes. This demonstrates retrieving data from Axiom using an older query method. ```go package main import ( "context" "log" "github.com/axiomhq/axiom-go" ) func main() { client, err := axiom.NewClient() if err != nil { log.Fatalf("axiom.NewClient: %v", err) } ctx := context.Background() // Query for the last 10 events in the "my-dataset" dataset using legacy query. resp, err := client.QueryLegacy(ctx, "my-dataset", "order by timestamp desc | limit 10") if err != nil { log.Fatalf("client.QueryLegacy: %v", err) } // Process the query results. for _, row := range resp.Results { log.Printf("%v\n", row) } } ``` -------------------------------- ### Ship Logs to Axiom with Zap Source: https://github.com/axiomhq/axiom-go/blob/main/examples/README.md Example of how to ship logs to Axiom using the popular Zap logging package. This demonstrates integration with a third-party logging library. ```go package main import ( "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/axiomhq/axiom-go/zap" ) func main() { core, err := zap.NewDevelopmentCore() if err != nil { panic(err) } adapter := axiom.NewZapCore(nil, zapcore.InfoLevel) logger := zap.New(zapcore.NewTee(core, adapter)) defer logger.Sync() logger.Info("Hello Axiom!") logger.Warn("This is a warning", zap.Int("value", 123)) } ``` -------------------------------- ### Aggregate Ingestion Status Example Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/ingest.md Demonstrates how to aggregate the status from multiple ingestion operations into a total status summary. ```go var totalStatus ingest.Status for _, batch := range batches { status, err := client.Datasets.IngestEvents(ctx, "dataset", batch) if err != nil { log.Fatal(err) } totalStatus.Add(status) } log.Printf("Total ingested: %d\n", totalStatus.Ingested) log.Printf("Total failed: %d\n", totalStatus.Failed) ``` -------------------------------- ### Ship Traces to Axiom with OpenTelemetry Source: https://github.com/axiomhq/axiom-go/blob/main/examples/README.md Example of how to ship traces to Axiom using the OpenTelemetry Go SDK and the Axiom SDKs `otel` helper package. This demonstrates sending trace data to Axiom. ```go package main import ( "context" "log" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.17.0" "github.com/axiomhq/axiom-go/otel/traces" ) func main() { ctx := context.Background() // Initialize the Axiom OpenTelemetry exporter. exporter, err := traces.NewExporter(nil) if err != nil { log.Fatalf("traces.NewExporter: %v", err) } // Configure the tracer provider. tracerProvider := trace.NewTracerProvider( trace.WithBatcher(exporter), trace.WithResource(resource.NewWithAttributes( semconv.SchemaURL, semconv.ServiceNameKey.String("my-service"), attribute.String("environment", "production"), )), ) defer func() { if err := tracerProvider.Shutdown(ctx); err != nil { log.Fatalf("tracerProvider.Shutdown: %v", err) } }() // Set the global tracer provider. otel.SetTracerProvider(tracerProvider) // Get a tracer instance. tracer := otel.Tracer("my-tracer") // Start a new span. _, span := tracer.Start(ctx, "my-operation") defer span.End() span.AddEvent("event-happened") } ``` -------------------------------- ### Go Table Row and Column Processing Example Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/query.md Demonstrates iterating over rows using the Rows() method and accessing individual column values by index. ```go table := result.Tables[0] log.Printf("Fields: %v\n", table.Fields) // Iterate over rows for row := range table.Rows() { log.Printf("Row values: %v\n", row) } // Or work with specific columns col0 := table.Columns[0] for i, value := range col0 { log.Printf("Column 0, row %d: %v\n", i, value) } ``` -------------------------------- ### Instrument Axiom Go Client with OpenTelemetry Source: https://github.com/axiomhq/axiom-go/blob/main/examples/README.md Example of how to instrument the Axiom Go client using OpenTelemetry. This allows for distributed tracing and metrics collection. ```go package main import ( "context" "log" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.17.0" "github.com/axiomhq/axiom-go/otelinstrument" ) func main() { ctx := context.Background() // Initialize the Axiom OpenTelemetry exporter. exporter, err := otelinstrument.NewExporter(nil) if err != nil { log.Fatalf("otelinstrument.NewExporter: %v", err) } // Configure the tracer provider. tracerProvider := trace.NewTracerProvider( trace.WithBatcher(exporter), trace.WithResource(resource.NewWithAttributes( semconv.SchemaURL, semconv.ServiceNameKey.String("my-service"), attribute.String("environment", "production"), )), ) defer func() { if err := tracerProvider.Shutdown(ctx); err != nil { log.Fatalf("tracerProvider.Shutdown: %v", err) } }() // Set the global tracer provider. otel.SetTracerProvider(tracerProvider) // Get a tracer instance. tracer := otel.Tracer("my-tracer") // Start a new span. _, span := tracer.Start(ctx, "my-operation") defer span.End() span.AddEvent("event-happened") } ``` -------------------------------- ### Set Query Start Time Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/query.md Use SetStartTime to specify the beginning of the time range for your query. This helps narrow down the search to a specific period. ```go func SetStartTime(startTime time.Time) Option ``` -------------------------------- ### List All Dashboards Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/organizations-dashboards.md Lists all available dashboards within the organization. This is useful for getting an overview of existing visualizations. ```go dashboards, err := client.Dashboards.List(context.Background()) if err != nil { log.Fatal(err) } for _, dashboard := range dashboards { log.Printf("Dashboard: %s\n", dashboard.Name) } ``` -------------------------------- ### Query Dataset with Axiom Go (APL) Source: https://github.com/axiomhq/axiom-go/blob/main/examples/README.md Example of how to query a dataset using the Kusto-like Axiom Processing Language (APL). This demonstrates retrieving data from Axiom. ```go package main import ( "context" "log" "github.com/axiomhq/axiom-go" ) func main() { client, err := axiom.NewClient() if err != nil { log.Fatalf("axiom.NewClient: %v", err) } ctx := context.Background() // Query for the last 10 events in the "my-dataset" dataset. resp, err := client.Query(ctx, "my-dataset", "order by timestamp desc | limit 10") if err != nil { log.Fatalf("client.Query: %v", err) } // Process the query results. for _, row := range resp.Results { log.Printf("%v\n", row) } } ``` -------------------------------- ### Ship Logs to Axiom with Logrus Source: https://github.com/axiomhq/axiom-go/blob/main/examples/README.md Example of how to ship logs to Axiom using the popular Logrus logging package. This demonstrates integration with a third-party logging library. ```go package main import ( "github.com/axiomhq/axiom-go/logrus" "github.com/sirupsen/logrus" ) func main() { logrus.SetOutput(axiom.NewAdapter(nil)) logrus.SetFormatter(&logrus.JSONFormatter{}) logrus.Info("Hello Axiom!") logrus.Warnf("This is a warning with %d fields", 123) } ``` -------------------------------- ### Configure Zerolog Adapter with Dataset Source: https://github.com/axiomhq/axiom-go/blob/main/adapters/zerolog/README.md Configure the zerolog adapter with a specific dataset using the SetDataset option. This example also shows how to set up the logger to write to both the adapter and standard error. ```go writer, err := adapter.New( adapter.SetDataset("logs"), ) l.Logger = zerolog.New(io.MultiWriter(writer, os.Stderr)).With().Timestamp().Logger() ``` -------------------------------- ### MonitorsService Get Method Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/users-tokens-monitors.md Retrieves a specific alert monitor by its unique ID. Requires a context and the monitor's ID. ```go func (s *MonitorsService) Get(ctx context.Context, id string) (*Monitor, error) ``` -------------------------------- ### Catching ErrExists Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/errors.md This example shows how to detect and handle errors when attempting to create a resource that already exists in Axiom. It checks for `axiom.ErrExists`, which is returned for duplicate datasets, users, tokens, or monitor configurations. ```go _, err := client.Datasets.Create(ctx, axiom.DatasetCreateRequest{ Name: "existing-dataset", }) if err != nil { if errors.Is(err, axiom.ErrExists) { log.Println("Dataset already exists") } } ``` -------------------------------- ### Access Axiom Client Services Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/client.md Demonstrates accessing various service APIs provided by the Axiom client, such as listing datasets, getting user information, and querying data. ```go // List all datasets datasets, err := client.Datasets.List(context.Background()) if err != nil { log.Fatal(err) } // Get current user user, err := client.Users.Current(context.Background()) if err != nil { log.Fatal(err) } // Query data result, err := client.Query(context.Background(), "['my-dataset'] | limit 100") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Ship Logs to Axiom with Slog Source: https://github.com/axiomhq/axiom-go/blob/main/examples/README.md Example of how to ship logs to Axiom using the standard libraries Slog structured logging package. This demonstrates integration with Go's built-in logging. ```go package main import ( "log/slog" "github.com/axiomhq/axiom-go/slog" ) func main() { client := axiom.NewAdapter(nil) logger := slog.New(slog.NewJSONHandler(client, nil)) logger.Info("Hello Axiom!") logger.Error("Something went wrong", "err", "division by zero") } ``` -------------------------------- ### Export Axiom Configuration Source: https://github.com/axiomhq/axiom-go/blob/main/examples/README.md Export Axiom configuration environment variables using the Axiom CLI. This is useful for quickstarting and setting up required variables. ```shell eval $(axiom config export -f) ``` -------------------------------- ### Ingest File Contents with Axiom Go Source: https://github.com/axiomhq/axiom-go/blob/main/examples/README.md Example of how to ingest the contents of a file into Axiom and compress them on the fly. This is useful for processing log files or other structured data. ```go package main import ( "context" "log" "github.com/axiomhq/axiom-go" ) func main() { client, err := axiom.NewClient() if err != nil { log.Fatalf("axiom.NewClient: %v", err) } ctx := context.Background() // This example assumes you have a file named "events.jsonl" in the same directory. // Each line in the file should be a valid JSON object. _, err = client.IngestFile(ctx, "my-dataset", "events.jsonl") if err != nil { log.Fatalf("client.IngestFile: %v", err) } } ``` -------------------------------- ### Ingest Hacker News Data with Axiom Go Source: https://github.com/axiomhq/axiom-go/blob/main/examples/README.md Example of how to ingest the contents of Hacker News into Axiom. This demonstrates fetching external data and sending it to Axiom. ```go package main import ( "context" "encoding/json" "log" "net/http" "github.com/axiomhq/axiom-go" ) func main() { client, err := axiom.NewClient() if err != nil { log.Fatalf("axiom.NewClient: %v", err) } ctx := context.Background() resp, err := http.Get("https://hn.algolia.com/api/v1/search_by_date?tags=story") if err != nil { log.Fatalf("http.Get: %v", err) } var result struct { Hits []json.RawMessage `json:"hits"` } if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { log.Fatalf("json.NewDecoder: %v", err) } _, err = client.IngestJSON(ctx, "hackernews", result.Hits) if err != nil { log.Fatalf("client.IngestJSON: %v", err) } } ``` -------------------------------- ### Get Organization Details Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/organizations-dashboards.md Retrieves the current organization's details. Use this to get information about the active organization. ```go org, err := client.Organizations.Get(context.Background()) if err != nil { log.Fatal(err) } log.Printf("Organization: %s\n", org.Name) log.Printf("Plan: %s\n", org.Plan) log.Printf("Quota: %d GB\n", org.Quota) ``` -------------------------------- ### Get Current Authenticated User Go Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/users-tokens-monitors.md Retrieves the details of the currently authenticated user. Use this to verify the active session or get user-specific information. ```go user, err := client.Users.Current(context.Background()) if err != nil { log.Fatal(err) } log.Printf("Authenticated as: %s (%s)\n", user.Name, user.Email) ``` -------------------------------- ### UsersService.Get Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/users-tokens-monitors.md Gets a user by ID. ```APIDOC ## UsersService.Get ### Description Gets a user by ID. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - User UUID ### Response #### Success Response (200) - **User** (*User) - The requested user object. ### Response Example ```json { "id": "user-123", "name": "Alice Smith", "email": "alice@example.com", "role": "user" } ``` ``` -------------------------------- ### Ingest Events and Query Data with Axiom Go Source: https://github.com/axiomhq/axiom-go/blob/main/README.md Demonstrates how to initialize the Axiom client, ingest events into a dataset, and query data. Ensure the client is configured via environment variables or explicit credentials. ```go package main import ( "context" "fmt" "log" "github.com/axiomhq/axiom-go/axiom" "github.com/axiomhq/axiom-go/axiom/ingest" ) func main() { ctx := context.Background() client, err := axiom.NewClient( // If you don't want to configure your client using the environment, // pass credentials explicitly: // axiom.SetToken("xaat-xyz"), ) 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) } } ``` -------------------------------- ### UsersService.Current Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/users-tokens-monitors.md Gets the currently authenticated user. ```APIDOC ## UsersService.Current ### Description Gets the currently authenticated user. ### Method GET ### Endpoint /users/current ### Response #### Success Response (200) - **User** (*User) - Current user object. ### Response Example ```json { "id": "user-123", "name": "Alice Smith", "email": "alice@example.com", "role": "user" } ``` ``` -------------------------------- ### Range Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/query.md Specifies the time window that a query was restricted to, including the start and end times. ```APIDOC ## Range ### Description The time window a query was restricted to. ### Type Definition ```go type Range struct { Field string // Field name (usually "_time") Start time.Time // Range start End time.Time // Range end (queries restrict to [start, end)) } ``` ``` -------------------------------- ### Initialize Axiom Client Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/README.md Creates a new Axiom client instance. Ensure the AXIOM_TOKEN environment variable is set or use SetToken() for authentication. ```go import "github.com/axiomhq/axiom-go/axiom" client, err := axiom.NewClient() if err != nil { log.Fatal(err) } // Access services datasets := client.Datasets users := client.Users monitors := client.Monitors ``` -------------------------------- ### Configure Client for CI/CD Environments Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/configuration.md Validate environment variables for Axiom configuration and initialize the client, failing fast if not configured. Verifies credentials. ```go // Fail fast if not configured if err := axiom.ValidateEnvironment(); err != nil { log.Fatal("Axiom not configured:", err) } client, err := axiom.NewClient(axiom.SetNoEnv()) if err != nil { log.Fatal(err) } // Verify connectivity if err := client.ValidateCredentials(ctx); err != nil { log.Fatal("Cannot connect to Axiom:", err) } ``` -------------------------------- ### Get Notifier Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/notifiers-annotations-virtualfields.md Retrieves a specific notifier by its unique identifier. It returns the Notifier object or an error. ```APIDOC ## Get Notifier ### Description Gets a specific notifier by ID. ### Method GET ### Endpoint /notifiers/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Notifier UUID - **ctx** (context.Context) - Required - The context for the request. ### Response #### Success Response (200) - **Notifier** - Notifier details. #### Response Example { "example": "{\"id\": \"uuid-1\", \"name\": \"Team Alerts\", \"type\": \"Slack\"}" } ``` -------------------------------- ### Get Notifier by ID Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/notifiers-annotations-virtualfields.md Fetches details for a specific notifier using its unique identifier (UUID). ```go func (s *NotifiersService) Get(ctx context.Context, id string) (*Notifier, error) ``` -------------------------------- ### DashboardsService.List Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/organizations-dashboards.md Lists all dashboards available within the organization. This is useful for getting an overview of existing visualizations. ```APIDOC ## GET /dashboards ### Description Lists all dashboards in the organization. ### Method GET ### Endpoint /dashboards ### Parameters None ### Request Example ``` // No request body for GET ``` ### Response #### Success Response (200) - **[]*Dashboard** - Slice of dashboards or error. #### Response Example ```json [ { "ID": "dashboard-123", "Name": "Application Health", "Description": "Real-time application metrics", "CreatedAt": "2023-10-27T10:00:00Z", "UpdatedAt": "2023-10-27T10:00:00Z", "Charts": [ { "Name": "Error Rate", "Description": "Error rate by severity", "Query": "['events'] | where level == 'error' | stats count() by severity", "Type": "timeseries" } ] } ] ``` ``` -------------------------------- ### Initialize Axiom Client with Environment Variables Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/configuration.md Initialize the Axiom client, which will automatically read configuration from environment variables. Ensure environment variables are set prior to this call. ```go client, err := axiom.NewClient() if err != nil { log.Fatal(err) } ``` -------------------------------- ### Configure Axiom Client with Explicit Options Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/README.md Initialize the Axiom client by explicitly providing configuration options such as token, organization ID, and URL. ```go client, err := axiom.NewClient( axiom.SetToken("xaat-xyz"), axiom.SetOrganizationID("org-123"), axiom.SetURL("https://api.axiom.co"), ) ``` -------------------------------- ### Get Monitor Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/users-tokens-monitors.md Retrieves a specific monitor by its unique identifier. Use this to fetch details of an existing monitor. ```APIDOC ## Get Monitor ### Description Gets a monitor by ID. ### Method GET ### Endpoint /monitors/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the monitor to retrieve. - **ctx** (context.Context) - Required - The context for the request. ### Response #### Success Response (200) - **Monitor** (*Monitor) - The Monitor object if found. - **error** - An error if the monitor was not found or the request failed. ``` -------------------------------- ### Configure Adapter with Client Options Source: https://github.com/axiomhq/axiom-go/blob/main/adapters/apex/README.md Configure the adapter by passing client options to set the Axiom personal token and organization ID. ```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"), ), ) ``` -------------------------------- ### Execute Query with a Variable Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/query.md Example of executing a query that uses a variable named 'severity' to filter events. ```go result, err := client.Query( ctx, "['dataset'] | where level == $severity | limit 100", query.SetVariable("severity", "error"), ) ``` -------------------------------- ### List Datasets Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/datasets.md Retrieves a list of all available datasets in your Axiom organization. This is useful for getting an overview of your data storage. ```go datasets, err := client.Datasets.List(context.Background()) if err != nil { log.Fatal(err) } for _, ds := range datasets { log.Printf("Dataset: %s (%s)\n", ds.Name, ds.ID) } ``` -------------------------------- ### List Notifiers Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/notifiers-annotations-virtualfields.md Retrieves a list of all notifiers configured in the organization. Use this to get an overview of existing notification channels. ```go func (s *NotifiersService) List(ctx context.Context) ([]*Notifier, error) ``` ```go notifiers, err := client.Notifiers.List(context.Background()) if err != nil { log.Fatal(err) } for _, notifier := range notifiers { log.Printf("Notifier: %s (%s)\n", notifier.Name, notifier.Type) } ``` -------------------------------- ### Create a Monitor in Axiom Go Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/README.md This snippet demonstrates how to create a monitor in Axiom, which can alert based on query results. Configure the monitor's name, query, operator, and threshold. ```go monitor, err := client.Monitors.Create(ctx, axiom.MonitorCreateRequest{ Monitor: axiom.Monitor{ Name: "High Error Rate", APLQuery: "['logs'] | stats count() where level == 'error'", Operator: axiom.Above, Threshold: 100, }, }) ``` -------------------------------- ### Get Current Authenticated User Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/getting-started.md Retrieve information about the currently authenticated user, including their name, email, and role. ```go user, err := client.Users.Current(ctx) if err != nil { log.Fatal(err) } log.Printf("Authenticated as: %s (%s)\n", user.Name, user.Email) log.Printf("Role: %s\n", user.Role.Name) ``` -------------------------------- ### Import Zerolog Adapter Source: https://github.com/axiomhq/axiom-go/blob/main/adapters/zerolog/README.md Import the zerolog adapter package, aliasing it to 'adapter' to avoid naming conflicts. ```go // Imported as "adapter" to not conflict with the "rs/zerolog" package. import adapter "github.com/axiomhq/axiom-go/adapters/zerolog" ``` -------------------------------- ### Get API Token Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/users-tokens-monitors.md Retrieves a specific API token by its unique identifier. This is useful for inspecting the details of an existing token. ```APIDOC ## Get API Token ### Description Gets an API token by ID. ### Method GET ### Endpoint /api/v1/tokens/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Token UUID ### Response #### Success Response (200) - `*APIToken` - The requested API token. ``` -------------------------------- ### Configure Adapter with Dataset Source: https://github.com/axiomhq/axiom-go/blob/main/adapters/apex/README.md Configure the adapter by setting the Axiom dataset using adapter options. ```go handler, err := adapter.New( adapter.SetDataset("AXIOM_DATASET"), ) ``` -------------------------------- ### Initialize Axiom Client with Options Only Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/configuration.md Initialize the Axiom client using explicit options, disabling environment variable reading. This provides direct control over configuration. ```go client, err := axiom.NewClient( axiom.SetNoEnv(), axiom.SetToken("xaat-abc123xyz"), axiom.SetURL("https://api.axiom.co"), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Axiom Organization Details Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/getting-started.md Retrieve details about the current Axiom organization, including its name, plan, and storage quota. ```go org, err := client.Organizations.Get(ctx) if err != nil { log.Fatal(err) } log.Printf("Organization: %s\n", org.Name) log.Printf("Plan: %s\n", org.Plan) log.Printf("Storage quota: %.2f GB\n", float64(org.Quota)/(1024*1024*1024)) ``` -------------------------------- ### Local Development with Environment Overrides Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/configuration.md Load Axiom configuration from a .env file and override specific settings like URL for local testing with a mock server. ```bash # .env file AXIOM_TOKEN=xaat-dev-token AXIOM_ORG_ID=org-dev AXIOM_URL=https://api.dev.axiom.co ``` ```go // Load from .env, override for local testing client, err := axiom.NewClient( axiom.SetURL("http://localhost:8080"), // Local mock server ) ``` -------------------------------- ### Go Range Struct Definition Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/query.md Represents the time window a query was restricted to, including the field, start, and end times. ```go type Range struct { Field string // Field name (usually "_time") Start time.Time // Range start End time.Time // Range end (queries restrict to [start, end)) } ``` -------------------------------- ### Set Query Start and End Time Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/configuration.md Define the time range for query results. Uses `time.Now()` for current time. ```go now := time.Now() query.SetStartTime(now.Add(-24 * time.Hour)) query.SetEndTime(now) ``` -------------------------------- ### Get Virtual Field Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/notifiers-annotations-virtualfields.md Retrieves a specific virtual field by its unique identifier. Use this to inspect the details of a single virtual field. ```APIDOC ## Get Virtual Field ### Description Gets a specific virtual field by ID. ### Method GET ### Endpoint /api/v1/virtualfields/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Virtual field UUID - **ctx** (context.Context) - Required - Context for the request. ### Response #### Success Response (200) - **VirtualField** - The requested virtual field object. #### Response Example ```json { "ID": "vf-123", "Name": "environment", "Description": "Extract environment from hostname", "Expression": "split(hostname, '-') | [2]", "FieldType": "string", "Datasets": ["logs", "events"] } ``` ``` -------------------------------- ### List Virtual Fields Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/notifiers-annotations-virtualfields.md Lists all virtual fields configured for the organization. This is useful for getting an overview of existing virtual fields and their configurations. ```APIDOC ## List Virtual Fields ### Description Lists all virtual fields in the organization. ### Method GET ### Endpoint /api/v1/virtualfields ### Parameters #### Query Parameters - **ctx** (context.Context) - Required - Context for the request. ### Response #### Success Response (200) - **[]*VirtualField** - Slice of virtual fields. #### Response Example ```json [ { "ID": "vf-123", "Name": "environment", "Description": "Extract environment from hostname", "Expression": "split(hostname, '-') | [2]", "FieldType": "string", "Datasets": ["logs", "events"] } ] ``` ``` -------------------------------- ### Get Specific Dashboard by ID Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/organizations-dashboards.md Retrieves a single dashboard using its unique identifier. Requires the dashboard's ID as a parameter. ```go dashboard, err := client.Dashboards.Get(context.Background(), "dashboard-123") if err != nil { log.Fatal(err) } log.Printf("Dashboard: %s\n", dashboard.Name) log.Printf("Created: %v\n", dashboard.CreatedAt) log.Printf("Charts: %d\n", len(dashboard.Charts)) ``` -------------------------------- ### Import Axiom Apex Adapter Source: https://github.com/axiomhq/axiom-go/blob/main/adapters/apex/README.md Import the adapter package, aliasing it to 'adapter' to avoid conflicts with the 'apex/log' package. ```go // Imported as "adapter" to not conflict with the "apex/log" package. import adapter "github.com/axiomhq/axiom-go/adapters/apex" ``` -------------------------------- ### Configure Zerolog Adapter with Client Options Source: https://github.com/axiomhq/axiom-go/blob/main/adapters/zerolog/README.md Configure the zerolog adapter by passing client options to the New function. This allows for manual configuration of the underlying Axiom client. ```go import ( "github.com/axiomhq/axiom-go/axiom" adapter "github.com/axiomhq/axiom-go/adapters/zerolog" ) // ... writer, err := adapter.New() if err != nil { log.Fatal(err) } l.Logger = zerolog.New(io.MultiWriter(writer, os.Stderr)).With().Timestamp().Logger() ``` -------------------------------- ### Get API Token by ID Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/users-tokens-monitors.md Retrieves a specific API token using its unique identifier. Requires the token's ID as a parameter. ```go func (s *TokensService) Get(ctx context.Context, id string) (*APIToken, error) ``` -------------------------------- ### Get Specific Virtual Field Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/notifiers-annotations-virtualfields.md Retrieves a single virtual field by its unique identifier. Requires the virtual field's ID as a parameter. ```go func (s *VirtualFieldsService) Get(ctx context.Context, id string) (*VirtualField, error) ``` -------------------------------- ### Common Axiom Go Client Imports Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/getting-started.md Shows the essential packages to import for using the Axiom Go client, including the main client, ingestion options, and query options. ```go import ( "github.com/axiomhq/axiom-go/axiom" "github.com/axiomhq/axiom-go/axiom/ingest" "github.com/axiomhq/axiom-go/axiom/query" ) ``` -------------------------------- ### Define Range Struct Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/types.md Represents the time window for a query, specifying the field and the start and end times. Used for time-based filtering or bucketing. ```go type Range struct { Field string Start time.Time End time.Time } ``` -------------------------------- ### Create New User Go Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/users-tokens-monitors.md Creates a new user and sends an invitation. Requires the user's name, email, and role. ```go user, err := client.Users.Create(ctx, axiom.CreateUserRequest{ Name: "Alice Smith", Email: "alice@example.com", Role: "user", }) ``` -------------------------------- ### Configure Client for Multi-Organization Support Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/configuration.md Initialize the Axiom client with a personal access token and a default organization, then switch organizations later using client options. ```go client, err := axiom.NewClient( axiom.SetPersonalTokenConfig("token", "org-1"), ) // Later, switch to another org client.Options(axiom.SetOrganizationID("org-2")) ``` -------------------------------- ### Custom HTTP Client with Timeout and Transport Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/configuration.md Demonstrates how to create a custom HTTP client with a specific timeout and transport settings, overriding the defaults. Useful for fine-tuning request behavior. ```go client, err := axiom.NewClient( axiom.SetClient(&http.Client{ Timeout: 10 * time.Second, Transport: &http.Transport{ MaxIdleConns: 100, MaxIdleConnsPerHost: 10, }, }), ) ``` -------------------------------- ### Create New Dataset Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/datasets.md Creates a new dataset with specified configurations like name, description, and retention policy. Ensure the dataset name adheres to the defined naming conventions. ```go dataset, err := client.Datasets.Create(context.Background(), axiom.DatasetCreateRequest{ Name: "my-events", Description: "Application events", UseRetentionPeriod: true, RetentionDays: 30, }) if err != nil { log.Fatal(err) } log.Printf("Created dataset: %s\n", dataset.ID) ``` -------------------------------- ### Get Specific Dataset Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/api-reference/datasets.md Fetches details for a single dataset using its unique identifier (ID). Use this to inspect a dataset's configuration and metadata. ```go dataset, err := client.Datasets.Get(context.Background(), "dataset-123") if err != nil { log.Fatal(err) } log.Printf("Dataset: %s\n", dataset.Name) log.Printf("Created: %v\n", dataset.CreatedAt) log.Printf("Can Write: %v\n", dataset.CanWrite) log.Printf("Retention: %d days\n", dataset.RetentionDays) ``` -------------------------------- ### Create Axiom Alert Monitor Source: https://github.com/axiomhq/axiom-go/blob/main/_autodocs/getting-started.md Set up a threshold-based alert monitor that triggers when a specified condition is met within a given interval. Requires a configured notifier. ```go monitor, err := client.Monitors.Create(ctx, axiom.MonitorCreateRequest{ Monitor: axiom.Monitor{ Name: "High Error Rate", Description: "Alert when error count exceeds 100 in 5 minutes", Type: axiom.MonitorTypeThreshold, APLQuery: "['app-logs'] | where level == 'error' | stats count()", Operator: axiom.Above, Threshold: 100, Interval: 5 * time.Minute, Range: 10 * time.Minute, NotifierIDs: []string{"notifier-id"}, // Configure notifier first }, }) if err != nil { log.Fatal(err) } log.Printf("Created monitor: %s\n", monitor.ID) ```