Rust SDK Getting Started
This topic provides two complete examples that show how to use a Client of the Simple Log Service (SLS) Rust SDK to write logs to an existing LogStore and query logs from the last 15 minutes. The direct write method is the default path for this quickstart; when you need to scale up write capability, use Rust Producer instead, and see What to do next for the complete criteria. The examples use existing resources and do not create or modify Project, LogStore, or index configurations.
Before you begin
Prerequisites
You have added the SDK dependency as described in Install the Rust SDK, and run
cargo add aliyun-log-sdk-protobufto add theLogandLogGroupdata type dependencies required by the write example.You have configured access credentials as described in Initialize the Rust SDK.
The destination Project and LogStore exist, and the credentials have write and query permissions.
Configure the runtime environment
Both the write and query examples use environment_credentials_provider() to read access credentials. Before you run the examples, set the following environment variables in the same terminal (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 the AccessKey of a RAM user that has access to the destination LogStore. Do not commit actual credentials to a code repository. Windows users can set system environment variables with the same names and then reopen the terminal.
The write and query examples in this topic use #[tokio::main] to run asynchronous code. Before you run the examples, add the Tokio dependency in the project directory:
cargo add tokio --features macros,rt-multi-threadYou must enable a full-text index for the destination LogStore before you write logs. Writing logs does not require an index, but the query example in this topic does. Index configurations typically take effect only for data written afterward, so enable the index before you run the write example.
Step 1: Write logs
Before you run the write example, make sure that a full-text index is enabled for the destination LogStore (index configurations typically take effect only for data written afterward). Save the following code as src/main.rs:
use aliyun_log_rust_sdk::{environment_credentials_provider, Client, Config, FromConfig};
use aliyun_log_sdk_protobuf::{Log, LogGroup};
use std::time::{SystemTime, UNIX_EPOCH};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::builder()
// Replace with the Endpoint for the region where the Project resides.
.endpoint("https://cn-hangzhou.log.aliyuncs.com")
.credentials_provider(environment_credentials_provider()?)
.build()?;
let client = Client::from_config(config)?;
// Replace with existing Project and Logstore names.
let project = "my-project";
let logstore = "my-logstore";
let seconds = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
let mut log = Log::from_unixtime(u32::try_from(seconds)?);
log.add_content_kv("level", "INFO")
.add_content_kv("message", "Hello from Rust SDK");
let mut group = LogGroup::new();
group.set_topic("rust-demo")
.set_source("rust-app")
.add_log(log);
let response = client.put_logs(project, logstore)
.log_group(group)
.send()
.await?;
println!("Logs written successfully, request_id={:?}", response.get_request_id());
Ok(())
}Run the following command in the project directory:
cargo runWhen the program outputs "Logs written successfully", the server has confirmed that the request is successful. request_id is the request identifier and can be used for troubleshooting.
About the write code
Logrepresents a log. Both field names and field values are strings. For a numeric field, you can first call.to_string().Log::from_unixtimeaccepts a Unix timestamp in seconds. Do not pass a timestamp in milliseconds.LogGrouprepresents a group of logs. You can call.add_log()multiple times to write multiple logs in one request.topicandsourceare optional. They are used to distinguish business operations and identify the log source, respectively.Client automatically compresses and sends the log group, but does not automatically combine separate
put_logscalls into a batch.
Step 2: Query logs
After you write logs, wait until the logs become available for query. Replace src/main.rs with the following code, and then run cargo run. You do not need to run the write example again. The write code from Step 1 remains in this topic. Copy it again when you need to write logs.
use aliyun_log_rust_sdk::{environment_credentials_provider, Client, Config, FromConfig};
use std::time::{SystemTime, UNIX_EPOCH};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::builder()
// Replace with the Endpoint for the region where the Project resides.
.endpoint("https://cn-hangzhou.log.aliyuncs.com")
.credentials_provider(environment_credentials_provider()?)
.build()?;
let client = Client::from_config(config)?;
// Replace with existing Project and Logstore names.
let project = "my-project";
let logstore = "my-logstore";
let now = i64::try_from(SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs())?;
let response = client.get_logs(project, logstore)
.from(now - 15 * 60)
.to(now + 1)
.topic("rust-demo")
.query("*")
.offset(0)
.line(100)
.send()
.await?;
let body = response.get_body();
if !body.is_complete() {
return Err(std::io::Error::other("The query is not complete. Retry later with the same conditions.").into());
}
println!("This query returned {} logs", body.logs_count());
for log in body.logs() {
println!("{log:?}");
}
Ok(())
}The example queries logs whose topic is rust-demo and returns up to 100 logs. When the program outputs "This query returned {} logs" and prints the details of each log, the query has returned successfully. The query results should contain a record whose message is Hello from Rust SDK. If 0 logs are returned, see the is_complete() description below and the FAQ section for troubleshooting.
Query parameters
Parameter | Description |
| The start and end times of the query, in Unix seconds. The time range is left-closed and right-open: |
| Limits the query to a log topic. To query all topics, remove this parameter. |
| The query statement. |
| The position from which a non-SQL query starts returning results. A value of 0 specifies the first result. |
| The maximum number of logs that a non-SQL query returns in this request. This value does not represent the total number of matching logs. |
To use a field condition such as level:INFO, configure an index for the field in advance. For SQL analysis, use the SQL LIMIT clause to control the number of returned rows. Do not use line and offset for pagination.
is_complete() returning true indicates that the current query is complete. It does not mean that all pages of data have been retrieved, and it does not mean that newly written logs are necessarily available for query. If 0 logs are returned, first check the Project, LogStore, topic, time range, and index configurations, and then query again later.
FAQ
Symptom | Suggestion |
An environment variable does not exist | Make sure that the variable is set in the terminal or deployment environment where the program runs. The SDK does not automatically read the |
Authentication fails or access is denied | Check whether the AccessKey is valid, whether the Security Token Service token matches and has not expired, and whether the RAM permissions on the destination resource are sufficient. |
The Project or LogStore does not exist | Check the names and the region of the Endpoint. |
The connection fails or times out | Check the network, DNS, and Endpoint, and make sure that the internal endpoint is applicable to the current environment. |
Logs are written but cannot be queried | Make sure that the index was enabled before the logs were written, that the query time range includes the log time, and that the logs are available for query. Do not write the logs again solely because they are temporarily unavailable for query. |
Error handling and retry considerations
If a Client request returns an error, the example exits and prints an error message. A server-side error typically contains an error code, a description, and request_id. Retain this information for troubleshooting, but do not log the AccessKey pair.
A network timeout does not necessarily mean that the server failed to write the logs. Automatic retries or resubmission by the application may result in duplicate logs. For businesses that are sensitive to duplicates, include a unique business identifier in each log.
What to do next
If you need automatic batch sending, background retries, and callbacks for sending results, or if you write logs continuously and in large volumes, see Use Rust Producer to Write Logs.