Use the SLS Skill to quickly integrate SDKs

Updated at:

alibabacloud-sls is an Agent Skill provided by Simple Log Service (SLS) for SDK usage scenarios. It helps the Agent deliver better results when selecting SDKs, installing and configuring them, and writing code.

The skill provides the following capabilities:

  • Multi-language support: covers more than 10 SDK languages, including Java, Go, Python, and Node.js.

  • Full-pipeline coverage: supports ingestion, consumption, querying, and resource management.

  • Intelligent SDK selection: automatically recommends the most suitable SDK and integration method based on the programming language and business scenario.

  • Instant code generation: generates SDK installation commands, initialization code, and complete examples from natural language prompts.

Scenarios

Scenario

Description

Sample prompt

SDK selection

Recommend the most suitable SDK based on the programming language and business scenario (ingestion, consumption, querying, or resource management), and explain the selection rationale.

My Java project needs high-throughput log ingestion to SLS and Consumer Group-based log consumption. Which SDKs should I use?

Installation and configuration

Provide dependency configurations and installation commands for Maven, pip, go get, npm, NuGet, Composer, Cargo, and other package managers.

How do I install the SLS SDK in a Go project? Provide the go get command.

Log ingestion

Guide the use of the Producer SDK, language SDKs, or logging framework Appenders to write logs to SLS, with complete code examples.

Use the Java Producer SDK to asynchronously write logs to SLS in batches. Provide the Maven dependency and code example.

Log consumption

Guide the use of a Consumer Group to consume logs from an SLS Logstore, including Processor implementation and checkpoint management.

My Java project needs Consumer Group-based log consumption from SLS with automatic checkpointing and multi-instance load balancing. Provide the code.

Appender integration

Guide zero-code integration of Log4j, Log4j2, or Logback applications with SLS through configuration files.

My project uses Log4j2. How do I send logs directly to SLS through an Appender? Provide the Maven dependency and log4j2.xml configuration.

SDK comparison

Explain the differences between the alibabacloud (OpenAPI) and aliyun (traditional) SDK families and their use cases.

What is the difference between alibabacloud_sls20201230 and aliyun-log-python-sdk? I need to write logs and manage resources. Which one should I install for each task?

Prerequisites

  • Alibaba Cloud account credentials (AccessKey ID and AccessKey Secret) are required only when your SDK code actually accesses SLS resources.

  • At least one Agent that supports skill installation is available, such as Qoder, Claude Code, Codex, or OpenClaw.

Warning

To prevent credential leaks, do not paste an AccessKey ID or AccessKey Secret into an Agent conversation. Code examples generated by the skill read credentials from environment variables.

Install the skill

To install the skill, follow the instructions in Install SLS Skill.

Usage guide

After installation, describe your SDK requirements in the Agent to trigger the skill. Based on its built-in SDK routing table and selection rules, the Agent recommends the most suitable SDK and provides installation commands and code examples.

Prompt writing tips

To help the Agent recommend SDKs and generate code more accurately, include the following information in your prompts:

  • Programming language and version. For example, "Java 17" or "Go 1.21".

  • Business scenario. For example, "high-throughput log ingestion", "Consumer Group-based log consumption", "query logs", or "create an index configuration".

  • Existing technology stack. For example, "Spring Boot project" or "the project already uses Log4j2".

The Project names, Logstore names, and code in the following scenarios are examples. Replace the resource names with your actual names.

Scenario 1: Select the right SDK for your business scenario

Prompt

My Java project needs high-throughput log ingestion to Alibaba Cloud SLS and Consumer Group-based log consumption for real-time processing. Which SDKs should I use? Provide the Maven dependencies for each.

Sample Agent output

Based on your requirements, use the following two SDKs for ingestion and consumption:

### Ingestion: aliyun-log-java-producer

For high-throughput log ingestion in Java, use the Producer SDK instead of the basic Java SDK's PutLogs API.
The Producer provides asynchronous non-blocking sending, automatic batching, automatic retries, and memory throttling.
It is suitable for big data scenarios such as Flink and Spark.

Maven dependency:
<dependency>
  <groupId>com.aliyun.openservices</groupId>
  <artifactId>aliyun-log-producer</artifactId>
  <version>0.3.25</version>
</dependency>

### Consumption: loghub-client-lib (aliyun-log-consumer-java)

For Consumer Group scenarios, use the Consumer Library. It automatically handles shard assignment,
heartbeats, checkpoint persistence, and multi-instance load balancing.
You only need to implement the processing logic for a single shard.

Maven dependencies:
<dependency>
  <groupId>com.aliyun.openservices</groupId>
  <artifactId>loghub-client-lib</artifactId>
  <version>0.6.50</version>
</dependency>
<dependency>
  <groupId>com.google.protobuf</groupId>
  <artifactId>protobuf-java</artifactId>
  <version>2.5.0</version>
</dependency>

### Why not use the basic Java SDK?

aliyun-log-java-sdk supports ingestion and querying, but ingestion uses the synchronous PutLogs API
without batching or retries, which is insufficient for high-throughput scenarios.
Consumption requires a separate Consumer Library.

If you also need to query logs or manage SLS resources (create Projects, Logstores, indexes, and so on),
you can additionally use alibabacloud-sls-java-sdk (OpenAPI SDK).

Scenario 2: Write logs with the Java Producer SDK

Prompt

My Java Spring Boot project needs to use the Producer SDK to asynchronously write business logs to SLS. The Project is prod-web, the Logstore is app-logs, and the region is China (Hangzhou). Provide a complete code example.

Sample Agent output

Use aliyun-log-java-producer, which provides asynchronous sending, automatic batching, and automatic retries.
It is suitable for high-throughput server-side log ingestion.

### Maven dependency

<dependency>
  <groupId>com.aliyun.openservices</groupId>
  <artifactId>aliyun-log-producer</artifactId>
  <version>0.3.25</version>
</dependency>

### Code example

import com.aliyun.openservices.aliyun.log.producer.LogProducer;
import com.aliyun.openservices.aliyun.log.producer.ProducerConfig;
import com.aliyun.openservices.aliyun.log.producer.ProjectConfig;
import com.aliyun.openservices.log.common.LogItem;

// 1. Create a Producer (global singleton, thread-safe)
ProducerConfig producerConfig = new ProducerConfig();
LogProducer producer = new LogProducer(producerConfig);

producer.putProjectConfig(new ProjectConfig(
    "prod-web", "cn-hangzhou.log.aliyuncs.com",
    System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
    System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")));

// 2. Build a log entry and send (asynchronous, returns immediately)
LogItem item = new LogItem();
item.PushBack("level", "INFO");
item.PushBack("service", "order-service");
item.PushBack("message", "Order created successfully");
item.PushBack("orderId", "202604240001");

producer.send("prod-web", "app-logs", "", "", item);

// 3. Call close() before the process exits, or buffered logs will be lost
producer.close();

### Notes

- send() is asynchronous and returns immediately. Logs are batched and sent by background threads.
- Call producer.close() before the process exits. It blocks until all buffered logs are sent.
- topic and source are batching dimensions. Avoid high-cardinality values such as request IDs, which reduce batching effectiveness.
- If you encounter protobuf version conflicts, use the jar-with-dependencies classifier.

Scenario 3: Consume logs with a Java Consumer Group

Prompt

My Java project needs to consume logs from an SLS Logstore in real time, with automatic checkpointing and multi-instance load balancing. The Project is prod-web, and the Logstore is app-logs. Provide the complete Consumer Group code.

Sample Agent output

Use aliyun-log-consumer-java (loghub-client-lib). It automatically handles shard assignment,
heartbeats, checkpoint persistence, and multi-instance load balancing.
You only need to implement the ILogHubProcessor interface.

### Maven dependencies

<dependency>
  <groupId>com.aliyun.openservices</groupId>
  <artifactId>loghub-client-lib</artifactId>
  <version>0.6.50</version>
</dependency>
<dependency>
  <groupId>com.google.protobuf</groupId>
  <artifactId>protobuf-java</artifactId>
  <version>2.5.0</version>
</dependency>

### Start the Consumer Worker

LogHubConfig config = new LogHubConfig(
    "my-consumer-group",
    "consumer-1",          // Must be unique within the same consumer group
    "cn-hangzhou.log.aliyuncs.com",
    "prod-web", "app-logs",
    System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
    System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
    LogHubConfig.ConsumePosition.BEGIN_CURSOR);

ClientWorker worker = new ClientWorker(new SampleProcessorFactory(), config);
Thread thread = new Thread(worker);
thread.start();

// Shut down gracefully when the process exits
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    worker.shutdown();
    try { Thread.sleep(30_000); } catch (InterruptedException ignored) {}
}));

### Processor implementation

class SampleProcessor implements ILogHubProcessor {
    private int shardId;

    @Override
    public void initialize(int shardId) {
        this.shardId = shardId;
    }

    @Override
    public String process(List<LogGroupData> logGroups,
                          ILogHubCheckPointTracker tracker) {
        for (LogGroupData data : logGroups) {
            // Process logs
            System.out.println("Shard " + shardId + ": "
                + data.GetAllLogs().size() + " logs");
        }
        tracker.saveCheckPoint(false); // Save locally; the framework persists to the server about every 60 seconds
        return null;
    }

    @Override
    public void shutdown(ILogHubCheckPointTracker tracker) {
        tracker.saveCheckPoint(true); // Persist to the server immediately on shutdown
    }
}

class SampleProcessorFactory implements ILogHubProcessorFactory {
    @Override
    public ILogHubProcessor generatorProcessor() {
        return new SampleProcessor();
    }
}

### Notes

- ConsumePosition.BEGIN_CURSOR takes effect only when the Consumer Group is first created.
  Subsequent restarts resume from the last saved checkpoint.
- Checkpoints are automatically submitted to the server about every 60 seconds by default.
  A crash may cause a small amount of duplicate consumption (at-least-once).
- Consumer names must be unique within the same Consumer Group. Use IP + PID as the name.
- A Logstore supports up to 30 Consumer Groups.

Scenario 4: Integrate SLS through a Log4j2 Appender with zero code changes

Prompt

My Java project already uses Log4j2 for logging. I want to send logs directly to Alibaba Cloud SLS without modifying any business code. How do I configure this?

Sample Agent output

Use aliyun-log-log4j2-appender. Add a Maven dependency and update log4j2.xml.
No changes to your business code are required. The Appender uses the Java Producer
under the hood to send logs asynchronously in batches.

### Maven dependencies

<dependency>
  <groupId>com.aliyun.openservices</groupId>
  <artifactId>aliyun-log-log4j2-appender</artifactId>
  <version>0.1.15</version>
</dependency>
<dependency>
  <groupId>com.google.protobuf</groupId>
  <artifactId>protobuf-java</artifactId>
  <version>2.5.0</version>
</dependency>

### log4j2.xml configuration

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
  <Appenders>
    <Loghub name="Loghub"
            project="your_project"
            logStore="your_logstore"
            endpoint="cn-hangzhou.log.aliyuncs.com"
            accessKeyId="${env:ALIBABA_CLOUD_ACCESS_KEY_ID}"
            accessKeySecret="${env:ALIBABA_CLOUD_ACCESS_KEY_SECRET}"
            totalSizeInBytes="104857600"
            maxBlockMs="0"
            ioThreadCount="8"
            batchSizeThresholdInBytes="524288"
            batchCountThreshold="4096"
            lingerMs="2000"
            retries="10"
            baseRetryBackoffMs="100"
            maxRetryBackoffMs="50000"
            topic=""
            source=""
            ignoreExceptions="true">
      <PatternLayout pattern="%d %-5level [%thread] %logger{0}: %msg"/>
    </Loghub>
  </Appenders>
  <Loggers>
    <Root level="WARN">
      <AppenderRef ref="Loghub"/>
    </Root>
  </Loggers>
</Configuration>

### Usage

After configuration, logs written with the standard Log4j2 API are automatically sent to SLS without additional code:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

Logger logger = LogManager.getLogger(MyClass.class);
logger.info("Application started");
logger.error("Order creation failed", exception);

Each log in SLS contains the following fields: level, location, message, throwable (if an exception exists),
thread, time, and log.

### Notes

- Set maxBlockMs="0" (recommended) to prevent blocking business threads when the buffer is full.
- Do not hard-code AccessKeys in configuration files. Use ${env:...} to read environment variables.
- If your project uses Log4j or Logback, SLS also provides corresponding Appenders:
  aliyun-log-log4j-appender and aliyun-log-logback-appender.

FAQ

What SDKs and programming languages are supported?

The skill covers 10 language platforms: Java, Go, Python, Node.js, PHP, .NET, Rust, C/C++, iOS, and Android. It supports more than 20 SDKs, including language SDKs, Producer SDKs, Consumer Libraries, Log4j / Log4j2 / Logback Appenders, and alibabacloud OpenAPI SDKs.

For other frequently asked questions, see SLS Skill FAQ.