Prerequisites
- Create an Axiom account.
- Create a dataset in Axiom where you send your data.
- Create an API token in Axiom with permissions to ingest data to the dataset you have created.
- Install Flutter SDK version 3.0.0 or higher.
Install required dependencies
To install the required Flutter dependencies, add these lines to yourpubspec.yaml file:
- 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 alib/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.
lib/axiom_logger.dart
Create main.dart file
Create anexample/main.dart file with the following content. This file demonstrates how to use the Axiom Logger with different log levels and metadata.
example/main.dart
Replace
API_TOKEN with the Axiom API token you have generated. For added security, store the API token in an environment variable.Replace DATASET_NAME with the name of the Axiom dataset where you send your data.Replace AXIOM_DOMAIN with the base domain of your edge deployment. For more information, see Edge deployments.Run the app and observe logs in Axiom
-
Run the following code in your terminal to run the Flutter example:
The app sends logs with different severity levels to Axiom, demonstrating batching, immediate sending for critical logs, and the use of custom metadata.
- 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
Basic integration
To add Axiom logging to your existing Flutter app, follow these steps:-
Add the Axiom Logger to your project by copying the
axiom_logger.dartfile to yourlibdirectory. -
Initialize the logger early in your app’s lifecycle, typically in your
main()function. -
Use the logger throughout your app to capture important events, errors, and debug information. For example:
Integration with Flutter error handling
Capture Flutter framework errors and send them to Axiom:Logging user interactions
Track user behavior and navigation patterns:Performance monitoring
Log performance metrics to identify bottlenecks:Best practices
- Use appropriate log levels: Reserve
criticalfor system failures,errorfor recoverable errors,warningfor potential issues,infofor important events, anddebugfor 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
batchSizeandflushIntervalbased on your app’s logging volume and network conditions.
Reference
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 application 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
AxiomLoggerConfig
TheAxiomLoggerConfig 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
TheAxiomLogger 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 is not yet implemented but can be added.
Log levels
The logger supports five log levels in increasing order of severity:- DEBUG: Detailed information for diagnosing problems, typically used during development.
- INFO: Confirmation that things are working as expected, such as successful operations.
- WARNING: Indication that something unexpected happened, but the app continues to work normally.
- ERROR: A more serious problem that prevented a specific operation from completing.
- 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
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
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
dio
The Dio package 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.
intl
The intl package provides internationalization and localization support, including:- Date and time formatting using standard patterns.
- Number formatting for different locales.
- Message translation support.
yyyy-MM-dd'T'HH:mm:ss.SSS'Z'), ensuring consistent and parseable timestamp strings across all log entries.
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
falsefrom theflush()method, allowing you to implement retry logic. - Uninitialized logger calls are safely ignored with console warnings.
Thread safety
The logger is designed for use in Flutter’s single-threaded Dart environment. All async operations use Dart’sFuture API, ensuring proper sequencing of log operations without race conditions.