Write logs with Rust Producer
Simple Log Service (SLS) Rust Producer sends logs in batches in the background, and automatically compresses logs and retries failed requests. This topic describes how to write logs with Rust Producer and explains the commonly used configuration options.
Prerequisites
A Project and a LogStore are created.
You have obtained the AccessKey of a RAM user and granted the RAM user write permissions on the destination LogStore (
log:PostLogStoreLogs).The Rust toolchain is installed, the
cargocommand is available, and a Rust project is created.The environment where the program runs can access the service endpoint of the region where the Project resides.
Delivery semantics and reliability limits
Producer sends logs asynchronously in batches, and the delivery semantics have the following limits. Confirm each one before you deploy to production:
sendreturning success only means that the log was accepted locally, not that it was written to the LogStore. To confirm the final write result, use a callback.Logs pending delivery are stored only in memory and may be lost if the process exits unexpectedly. Before a normal exit, wait for
close_blocking()to complete. This method does not aggregate the failures to send individual logs.Producer does not guarantee the order in which logs are written, and retries may cause duplicate logs.
Producer should not be the only reliable storage for business data.
QuickStart
1. Install dependencies
In the Rust project directory, run the following commands:
cargo add aliyun-log-producer
cargo add aliyun-log-rust-sdkaliyun-log-producer provides the Producer, ProducerConfig, and log! macros, and aliyun-log-rust-sdk provides the environment_credentials_provider() function that reads credentials from environment variables. The sample code depends on both crates, and neither can be omitted. This example is a synchronous program, so you do not need to add Tokio directly.
2. Configure access credentials
The example uses environment_credentials_provider() to read the following environment variables. Set these variables in the terminal where the program runs (Linux/macOS):
export ALIBABA_CLOUD_ACCESS_KEY_ID="<your-access-key-id>"
export ALIBABA_CLOUD_ACCESS_KEY_SECRET="<your-access-key-secret>"Replace the placeholders with an actual AccessKey. export takes effect only in the current terminal session, and you must set the variables again if you switch to another terminal. Windows users can set system environment variables with the same names and then reopen the terminal. Do not commit actual credentials to a code repository.
3. Write logs
Save the following code as src/main.rs, and replace three items in it: the service endpoint in with_endpoint, and the Project name and LogStore name in producer.writer.
use aliyun_log_producer::{log, Producer, ProducerConfig};
use aliyun_log_rust_sdk::environment_credentials_provider;
use std::time::SystemTime;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ProducerConfig::default()
// Replace with the Endpoint for the region where the Project resides.
.with_endpoint("https://cn-hangzhou.log.aliyuncs.com")
.with_credentials_provider(environment_credentials_provider()?);
let producer = Producer::create(config)?;
let writer = producer.writer("my-project", "my-logstore")?; // Replace with existing Project and LogStore names.
// Write logs
let _ = writer.send(log!("level": "INFO", "message": "Hello from Rust Producer"));
let _ = writer.send(log!(time = SystemTime::now(); "level": "INFO", "message": "Log with timestamp"));
// When the program exits, call close
producer.close_blocking()?;
Ok(())
}Run cargo run to start the sample program. The example ends after close_blocking() returns. The terminal does not print the write result, so query the two logs in the destination LogStore to confirm that the values of message are Hello from Rust Producer and Log with timestamp respectively.
Configuration description
ProducerConfig::default().with_*() configures options through chained calls. Options that you do not configure use their default values. For example, .with_linger(std::time::Duration::from_millis(500)) changes the batch wait time from the default 2 seconds to 500 milliseconds.
Credentials have two mutually exclusive paths: with_credentials_provider configures the credential source, and with_access_key directly sets the AccessKey ID and Secret. The option that you configure later overrides the earlier one. (Recommended) Use with_credentials_provider. The example calls environment_credentials_provider() to read the AccessKey from environment variables, so no credentials appear in the code. with_access_key requires plaintext credentials in the code, so use it only when you cannot configure a credential source. Do not commit actual credentials to a code repository.
When you call send multiple times, the logs are first buffered in memory. A batch enters the sending process when it reaches the size, count, or wait-time condition, whichever comes first, and is sent after being compressed in the manner specified by with_compression. If sending fails, the batch is retried according to with_max_attempts, with_base_backoff, and with_max_backoff. The sending result is returned through a callback, and the number of logs whose callbacks have not completed is limited by with_callback_capacity.
| Configuration method | Required | Default value | Description |
with_endpoint | Yes | None | The service endpoint of the region where the Project resides. It must match the region of the Project. Example value: https://cn-hangzhou.log.aliyuncs.com. |
with_credentials_provider | Either this option or with_access_key must be configured. | None | Configures the credential source. The example reads the AccessKey from environment variables. |
with_access_key | Either this option or with_credentials_provider must be configured. | None | Directly sets the AccessKey ID and Secret. |
with_compression | No | Compression::Zstd | The compression method. You can also select Compression::Lz4. |
with_batch_size_threshold | No | 1 MiB | A batch is sent when its estimated size reaches this value. Valid values: 1 to 8388608 bytes (8 MiB). This value is not the maximum size of a single log. |
with_batch_count_threshold | No | 4096 logs | A batch is sent when the number of logs in it reaches this value. Valid values: 1 to 40960. |
with_linger | No | 2 seconds | The maximum time that logs are buffered in memory. When this time elapses, the batching condition is met and the logs are sent immediately. |
with_buffer_bytes | No | 128 MiB | The estimated raw data volume budget for logs pending delivery. New logs are rejected when this budget is exceeded. |
with_processing_workers | No | 2 | The number of log processing threads. |
with_max_attempts | No | 10 | The maximum number of times that each batch is sent, including the first attempt. A value of 1 disables retries. |
with_base_backoff | No | 200 milliseconds | The initial upper limit of the retry wait time. This value does not exceed max_backoff. |
with_max_backoff | No | 10 seconds | The maximum upper limit of the retry wait time. |
with_delivery_timeout | No | 600 seconds | The sending time budget, measured from when a batch stops accumulating logs. This period includes queuing, processing, and retries, but excludes the accumulation wait time and callbacks. |
with_callback_capacity | No | 65536 | The maximum number of logs whose callbacks have not completed. Sends without callbacks do not consume this capacity. |
with_generate_pack_id | No | true | Automatically adds a PackId, which can be used to perform a contextual query after the logs are written to the LogStore. |
with_user_agent | No | aliyun-log-rust-producer/<version> | The custom User-Agent of the request, which identifies the client. |
FAQ
The program runs without errors, but no logs can be queried in the LogStore. How do I troubleshoot this? Check the following items in order: whether the AccessKey environment variables take effect in the current terminal session; whether the service endpoint in
with_endpointmatches the region where the Project resides; whether the Project and LogStore names passed toproducer.writerrefer to existing resources; and whether the volume of data pending delivery exceeds thewith_buffer_bytesbudget and is therefore rejected.Why does the example use
let _ =to discard the return value ofsend? The example omits the handling of the return value. The return value indicates whether the log was accepted locally. In production code, check the return value and use a callback to confirm the final write result on the server.