tencent cloud

Android/iOS SDK Log Upload
Last updated:2026-02-05 15:59:09
Android/iOS SDK Log Upload
Last updated: 2026-02-05 15:59:09

SDK Overview

Tencent Cloud Log Service (CLS) mobile SDK supports both Android and iOS platforms. It provides core capabilities such as log collection, log upload, and network detection. With advantages like client-side optimization, high reliability, upload acceleration, and elastic configuration, it is designed to meet the log management needs of various mobile apps, ensuring secure and efficient transmission and storage of logs.

Core Features

Core Capabilities for Log Upload

Client-side optimization: Adapts to mobile scenarios while balancing performance and resource consumption.
Native deep adaptation: It ensures compatibility with native Android/iOS APIs, prevents conflicts through native thread synchronization, and leverages the Reachability library and ConnectivityManager for real-time network status detection, precisely matching the mobile runtime environment.
Intelligent resource management: This feature uses SQLite for local storage with maxDatabaseSize to limit database size. Core logic runs on a dedicated background thread to prevent UI blocking. It also supports batchSize and sendLogInterval configurations for batched log sending, significantly reducing network overhead and battery consumption.
Secure storage compliance: Database operations are confined exclusively to the app sandbox's Documents directory. This practice, which strictly adheres to mobile data storage standards, prevents data leakage and unauthorized access at the source.
Reliability assurance: Provides full-link protection to ensure zero log loss or duplication.
Local persistence: Logs are immediately serialized and stored in the local database upon generation. This ensures data integrity in the event of app crashes or network outages, with automatic upload resumption once the network is restored.
Multi-layer verification system: It validates data integrity (including logIds, topicId, and Protobuf serialization results) and request legitimacy (URL and body) prior to sending, preventing failures caused by parameter errors.
Intelligent retry mechanism: This mechanism processes error codes precisely. It aborts retries for 4xx errors while retaining logs and dynamically adjusting the retry policy for 5xx and specific 4xx errors. Local logs are only deleted after a 200 response is received from the server, ensuring eventual data consistency.
Upload acceleration policy: Employs two-stage compression to enhance transmission efficiency.
Efficient serialization: Google Protocol Buffers is adopted instead of JSON/XML, yielding a more compact data format and faster parsing speed. This significantly reduces both transmission volume and CPU consumption.
Ultra-fast compression: The LZ4 algorithm is applied for secondary compression on Protobuf-serialized data. This adds minimal CPU overhead while further shrinking the transmission payload to maximize upload speed.
Elastic configuration capability: Flexibly adapts to complex business scenarios.
Various configuration items: Core configurations (including endpoint, accessKeyId, and accessKey) and performance parameters (including sendLogInterval and maxMemorySize) are uniformly encapsulated for both Android and iOS.
Dynamic adjustment: Parameters like the log send interval and database capacity can be modified at runtime. Changes take effect without an app restart, enabling adaptation to scenarios such as weak networks or high real-time requirements.
Lifecycle management: An updateToken method is provided to enable dynamic updates of authentication tokens, meeting the need for temporary security credential rotation and enhancing environmental adaptability.
Engineering advantage: Features a stable architecture that is secure and scalable.
Architecture design: The singleton pattern guarantees a single global log manager, preventing resource contention. Its modular design clearly separates components like the core controller and data access layer, making the structure clear and easy to maintain and extend.
Security protection: It signs requests (method, path, parameters, headers) using the HMACSHA1 algorithm to defend against man-in-the-middle tampering and replay attacks. It never stores keys on disk and works with server-side signature verification to secure data transmission.
Thread safety: Multi-threaded calls to methods like updateToken and setConfig are safeguarded with @synchronized locks. This ensures data consistency and stability in concurrent environments.

Network Detection Capability

Four detection methods are supported: Ping, TCPPing, TraceRoute, and HttpPing. These methods can gather network metrics including connectivity, latency, and routing information to aid in troubleshooting log upload failures.

Fast Integration

Must-Knows

Key security: Securely store accessKeyId and accessKeySecret. Avoid hardcoding them in client-side code. It is recommended to have them dynamically issued by the server.
Obfuscation configuration: For the Android platform, add an obfuscation exemption rule for the LZ4 compression algorithm: -keep class net.jpountz.lz4.** { *; }.
Debug mode: Disable the SDK debug mode (iOS: config.debuggable = NO; Android: config.debuggable = false) in release builds to prevent log leakage.
Network adaptation: For Android 9.0 and above, configure the network security policy to allow cleartext traffic for specific domains or use HTTPS. For iOS, ensure network permissions are enabled and the app complies with ATS requirements.
Permission control: For Android, request necessary permissions such as network access and network status query. For iOS, add network usage descriptions to Info.plist if required.
Cache management: Set appropriate upper limits for the database and in-memory cache. This prevents excessive storage consumption and ensures compatibility with devices of varying performance levels.
Version compatibility: Verify that the SDK version is compatible with your project's minimum supported OS versions to avoid integration issues.

iOS Platform

Environment Requirements

Development tool: Xcode.
Supported versions: iOS 9.0 and above.
Dependency management: CocoaPods.

Configuration Parameters

Parameter Name
Type
Description
Default Value
endpoint
String
Region information. For the domain name to use, refer to the API Log Upload tab in Available Regions.
-
accessKeyId (secretId)
String
Access key ID. This key must be granted the SDK log upload permission.
-
accessKeySecret (secretKey)
String
Access key secret. This key must be granted the SDK log upload permission.
-
topicId
String
Log topic ID, which can be obtained from the console.
-
token
String
Temporary key (optional).
-
sendLogInterval
Int
Delay before sending logs (in seconds).
5
maxMemorySize
Int
Upper limit for in-memory cache (in bytes).
32MB (3210241024)
batchSize
Int
Threshold for batch processing log entries.
Adapts to platform characteristics by default. Customizable.
maxDatabaseSize
Long
Maximum database size limit (in bytes).
Adapts to device storage. Customizable.
debuggable
BOOL
Debug mode switch. It must be disabled for release builds.
NO

Integration Steps

Note:
The iOS SDK source code is available at: https://github.com/TencentCloud/tencentcloud-cls-sdk-ios.
1. Integrate the plugin. Add the required dependencies to your Podfile and run pod install to complete the integration.
Core log upload: pod 'TencentCloudLogProducer/Core', '2.0.0'.
Network detection plugin: pod 'TencentCloudLogProducer/NetWorkDiagnosis'.
2. Initialize the configuration.
2.1 Core log upload initialization.
Objective-C
Swift
#import "TencentCloudLogProducer/ClsLogSender.h"
#import "TencentCloudLogProducer/CLSLogStorage.h"

// Initialize the configuration.
ClsLogSenderConfig *config = [ClsLogSenderConfig configWithEndpoint:@"your_endpoint"
accessKeyId:@"your_accessKeyId"
accessKey:@"your_accessKey"];
// Set optional parameters (example).
config.sendLogInterval = 5; // Delay before sending logs. Default value: 5 seconds.
config.maxMemorySize = 32 * 1024 * 1024; // Upper limit for in-memory cache. Default value: 32MB.
config.token = @"your_temp_token"; // Temporary key (optional).

// Start the SDK.
_sender = [LogSender sharedSender];
[_sender setConfig:config];
[_sender start];
import TencentCloudLogProducer

// Initialize the configuration.
let config = ClsLogSenderConfig(
endpoint: "your_endpoint" ?? "",
accessKeyId: "your_accessKeyId" ?? "",
accessKey: "your_accessKey" ?? ""
)
config.sendLogInterval = 5 // Delay before sending logs. Default value: 5 seconds.
config.maxMemorySize = 32 * 1024 * 1024 // Upper limit for in-memory cache. Default value: 32MB.
config.token = "your_temp_token" // Temporary key (optional).

// Start the SDK.
let sender = LogSender.shared()
sender.setConfig(config)
sender.start()
2.2 Network detection plugin initialization.
Objective-C
Swift
#import "ClsNetworkDiagnosis.h"
#import "ClsAdapter.h"
#import "ClsNetDiag.h"

// Initialize the configuration.
ClsConfig *config = [[ClsConfig alloc] init];
config.debuggable = YES; // Debug mode. It should be disabled for release builds.
config.endpoint = @"ap-guangzhou.cls.tencentcs.com";
config.accessKeyId = @"your_accessKeyId";
config.accessKeySecret = @"your_accessKeySecret";
config.topicId = @"your_topicId";
config.pluginAppId = @"your_pluginAppId";

// Add custom parameters (optional).
[config setUserId:@"user1"];
[config setChannel:@"channel1"];
[config setChannelName:@"Official channel"];
[config setUserNick:@"Test user"];
[config setLongLoginNick:@"Frequently used nickname"];
[config setLongLoginUserId:@"long_login_user1"];
[config setLoginType:@"wechat"];
[config addCustomWithKey:@"customKey" andValue:@"testValue"];

// Initialize the plugin manager.
ClsAdapter *clsAdapter = [ClsAdapter sharedInstance];
[clsAdapter addPlugin:[[CLSNetworkDiagnosisPlugin alloc] init]];
[clsAdapter initWithCLSConfig:config];
import UIKit
import TencentCloudLogProducer

// Output class that implements the CLSOutputDelegate protocol.
class CLSWriter: NSObject, CLSOutputDelegate {
func write(_ line: String!) {
print("CLSWriter output: \\(line ?? "")")
}
}

// Initialize the configuration.
func initNetworkDiagnosis() {
let config = ClsConfig()
config.endpoint = "ap-guangzhou.cls.tencentcs.com"
config.accessKeyId = "your_access_key_id"
config.accessKeySecret = "your_access_key_secret"
config.topicId = "your_topic_id"
config.pluginAppId = "your_plugin_id"

// Optional: Custom parameters.
config.userId = "user1"
config.channel = "channel1"
config.addCustom(withKey: "customKey1", andValue: "testValue")

// Add the network detection plugin.
let clsAdapter = ClsAdapter.sharedInstance()
let plugin = CLSNetworkDiagnosisPlugin()
clsAdapter.add(unsafeBitCast(plugin, to: baseClsPlugin.self))
clsAdapter.initWith(config)
}

3. Log writing. The following examples demonstrate how to write logs.
Objective-C
Swift
#import "TencentCloudLogProducer/ClsLogSender.h"
#import "TencentCloudLogProducer/CLSLogStorage.h"
#import "TencentCloudLogProducer/ClsLogs.pbobjc.h"

// Build log content.
Log_Content *logContent = [Log_Content message];
logContent.key = @"user_behavior";
logContent.value = @"click_submit_button";

// Build a log item (timestamp in seconds).
Log *logItem = [Log message];
[logItem.contentsArray addObject:logContent];
logItem.time = [@(System.currentTimeMillis() / 1000) longLongValue];

// Write to the local database (auto-triggers batched sending).
[[CLSLogStorage sharedInstance] writeLog:logItem
topicId:@"your_topicId"
completion:^(BOOL success, NSError *error) {
if (success) {
NSLog(@"Log writing successful, to be sent.");
} else {
NSLog(@"Log writing failed: %@", error.localizedDescription);
}
}];
import TencentCloudLogProducer

// Build log content.
let logContent = Log_Content()
logContent.key = "user_behavior"
logContent.value = "click_submit_button"

// Build a log item (timestamp in seconds).
let logItem = Log()
logItem.contentsArray.add(logContent)
logItem.time = Int64(Date().timeIntervalSince1970)

// Write to the local database (auto-triggers batched sending).
ClsLogStorage.sharedInstance().write(logItem, topicId: "your_topicId") { success, error in
if success {
print("Log writing successful, to be sent.")
} else {
print("Log writing failed: error.debugDescription)")
}
}
4. Network detection. The following examples demonstrate how to use the network detection feature.
Ping detection.
Objective-C
Swift
// Method 1: Basic Ping detection.
[[CLSNetworkDiagnosisPlugin sharedInstance] ping:@"cloud.tencent.com"
size:64
output:self
complete:^(BOOL success, NSString *result) {
NSLog(@"Ping detection result: %@", result);
}];

// Method 2: Ping detection with specified timeout and detection count.
[[CLSNetworkDiagnosisPlugin sharedInstance] ping:@"cloud.tencent.com"
size:64
task_timeout:3000
output:self
complete:^(BOOL success, NSString *result) {
NSLog(@"Ping detection result: %@", result);
} count:10];

// Method 3: Ping detection with a custom field.
NSMutableDictionary *customFields = [NSMutableDictionary dictionary];
customFields[@"detect_scene"] = @"log_upload_failure";
[[CLSNetworkDiagnosisPlugin sharedInstance] ping:@"cloud.tencent.com"
size:64
output:self
complete:^(BOOL success, NSString *result) {
NSLog(@"Ping detection result: %@", result);
} customFiled:customFields];
//Method 1: Basic Ping detection.
ClsNetworkDiagnosis.sharedInstance().ping(
"cloud.tencent.com",
size: 64,
output: CLSWriter()
) { result in
print("Ping detection result: \\(result?.description ?? "No result")")
}

// Method 2: Ping detection with specified timeout and detection count.
ClsNetworkDiagnosis.sharedInstance().ping(
"cloud.tencent.com",
size: 64,
task_timeout: 3000, // Timeout: 3000 milliseconds.
output: CLSWriter(),
complete: { result in
print("Ping detection result: \\(result?.description ?? "No result")")
},
count: 10 // Detection count.
)

//Method 3: Ping detection with custom fields.
let customFields = NSMutableDictionary()
customFields["detect_scene"] = "log_upload_failure"
customFields["app_version"] = "1.0.0"

ClsNetworkDiagnosis.sharedInstance().ping(
"cloud.tencent.com",
size: 64,
output: CLSWriter(),
complete: { result in
print("Ping detection result: \\(result?.description ?? "No result")")
},
customFiled: customFields
)

//Method 4: Ping detection with all parameters.
let customFields = NSMutableDictionary()
customFields["detect_scene"] = "log_upload_failure"

ClsNetworkDiagnosis.sharedInstance().ping(
"cloud.tencent.com",
size: 64,
task_timeout: 3000,
output: CLSWriter(),
complete: { result in
guard let result = result else {
print("Ping detection failed.")
return
}
print("Ping detection result:")
print("- Average latency: \\(result.avgRtt ?? "") ms")
print("- Packet loss rate: \\(result.loss_rate ?? "") %")
print("- Full result: \\(result.description)")
},
count: 10,
customFiled: customFields
)

TCPPing detection.
Objective-C
Swift
// Method 1: Basic TCPPing detection.
[[CLSNetworkDiagnosisPlugin sharedInstance] tcpPing:@"cloud.tencent.com"
output:self
complete:^(BOOL success, NSString *result) {
NSLog(@"TCPPing detection result: %@", result);
}];

// Method 2: TCPPing detection with specified port, timeout, and detection count.
[[CLSNetworkDiagnosisPlugin sharedInstance] tcpPing:@"cloud.tencent.com"
port:80
task_timeout:3000
count:10
output:self
complete:^(BOOL success, NSString *result) {
NSLog(@"TCPPing detection result: %@", result);
}];

// Method 3: TCPPing detection with a custom field.
NSMutableDictionary *customFields = [NSMutableDictionary dictionary];
customFields[@"detect_scene"] = @"log_upload_failure";
[[CLSNetworkDiagnosisPlugin sharedInstance] tcpPing:@"cloud.tencent.com"
output:self
complete:^(BOOL success, NSString *result) {
NSLog(@"TCPPing detection result: %@", result);
} customFiled:customFields];
//Method 1: Basic TCPPing detection.
ClsNetworkDiagnosis.sharedInstance().tcpPing(
"cloud.tencent.com",
output: CLSWriter()
) { result in
print("TCPPing detection result: \\(result?.description ?? "No result")")
}

//Method 2: TCPPing detection with specified port, timeout, and detection count.
ClsNetworkDiagnosis.sharedInstance().tcpPing(
"cloud.tencent.com",
port: 80, // Target port.
task_timeout: 3000, // Timeout: 3000 milliseconds.
count: 10, // Detection count.
output: CLSWriter()
) { result in
print("TCPPing detection result: \\(result?.description ?? "No result")")
}

//Method 3: TCPPing detection with custom fields.
let customFields = NSMutableDictionary()
customFields["detect_scene"] = "log_upload_failure"
customFields["connection_type"] = "wifi"

ClsNetworkDiagnosis.sharedInstance().tcpPing(
"cloud.tencent.com",
output: CLSWriter(),
complete: { result in
print("TCPPing detection result: \\(result?.description ?? "No result")")
},
customFiled: customFields
)

//Method 4: TCPPing detection with all parameters.
let customFields = NSMutableDictionary()
customFields["detect_scene"] = "log_upload_failure"

ClsNetworkDiagnosis.sharedInstance().tcpPing(
"cloud.tencent.com",
port: 443, // HTTPS port.
task_timeout: 5000,
count: 10,
output: CLSWriter(),
complete: { result in
guard let result = result else {
print("TCPPing detection failed.")
return
}
print("TCPPing detection result:")
print("- Average latency: \\(result.avgRtt ?? "") ms")
print("- Success rate: \\(result.success_rate ?? "") %")
print("- Full result: \\(result.description)")
},
customFiled: customFields
)

TraceRoute detection.
Objective-C
Swift
// Method 1: Basic TraceRoute detection.
[[CLSNetworkDiagnosisPlugin sharedInstance] traceRoute:@"cloud.tencent.com"
output:self
complete:^(BOOL success, NSString *result) {
NSLog(@"TraceRoute detection result: %@", result);
}];

// Method 2: TraceRoute detection with specified maximum hops.
[[CLSNetworkDiagnosisPlugin sharedInstance] traceRoute:@"cloud.tencent.com"
output:self
complete:^(BOOL success, NSString *result) {
NSLog(@"TraceRoute detection result: %@", result);
} maxTtl:30];

// Method 3: TraceRoute detection with a custom field.
NSMutableDictionary *customFields = [NSMutableDictionary dictionary];
customFields[@"detect_scene"] = @"log_upload_failure";
[[CLSNetworkDiagnosisPlugin sharedInstance] traceRoute:@"cloud.tencent.com"
output:self
complete:^(BOOL success, NSString *result) {
NSLog(@"TraceRoute detection result: %@", result);
} customFiled:customFields];
// Method 1: Basic TraceRoute detection.
ClsNetworkDiagnosis.sharedInstance().traceRoute(
"cloud.tencent.com",
output: CLSWriter()
) { result in
print("TraceRoute detection result: \\(result?.content ?? "No result")")
}

//Method 2: TraceRoute detection with specified maximum hops.
ClsNetworkDiagnosis.sharedInstance().traceRoute(
"cloud.tencent.com",
output: CLSWriter(),
complete: { result in
guard let result = result else {
print("TraceRoute detection failed.")
return
}
print("TraceRoute detection result:")
print("- Hop count: \\(result.hop_count ?? 0)")
print("- Route details: \\(result.content ?? "")")
},
maxTtl: 30 // Maximum hop count.
)

//Method 3: TraceRoute detection with custom fields.
let customFields = NSMutableDictionary()
customFields["detect_scene"] = "log_upload_failure"
customFields["network_carrier"] = "China Mobile"

ClsNetworkDiagnosis.sharedInstance().traceRoute(
"cloud.tencent.com",
output: CLSWriter(),
complete: { result in
print("TraceRoute detection result: \\(result?.content ?? "No result")")
},
customFiled: customFields
)
//Method 4: TraceRoute detection with all parameters.
let customFields = NSMutableDictionary()
customFields["detect_scene"] = "log_upload_failure"

ClsNetworkDiagnosis.sharedInstance().traceRoute(
"cloud.tencent.com",
output: CLSWriter(),
complete: { result in
guard let result = result else {
print("TraceRoute detection failed.")
return
}
print("TraceRoute detection result:")
print("- Completion status: \\(result.status)")
print("- Hop count: \\(result.hop_count ?? 0)")
print("- Detailed route:")
print(result.content ?? "No route information")
},
maxTtl: 30,
customFiled: customFields
)


HttpPing detection.
Objective-C
Swift
// Method 1: Basic HttpPing detection.
[[CLSNetworkDiagnosisPlugin sharedInstance] httping:@"https://ap-guangzhou.cls.tencentcs.com/ping"
output:self
complate:^(BOOL success, NSString *result) {
NSLog(@"HttpPing detection result: %@", result);
}];

// Method 2: HttpPing detection with a custom field.
NSMutableDictionary *customFields = [NSMutableDictionary dictionary];
customFields[@"detect_scene"] = @"log_upload_failure";
[[CLSNetworkDiagnosisPlugin sharedInstance] httping:@"https://ap-guangzhou.cls.tencentcs.com/ping"
output:self
complate:^(BOOL success, NSString *result) {
NSLog(@"HttpPing detection result: %@", result);
} customFiled:customFields];
//Method 1: Basic HttpPing detection.
ClsNetworkDiagnosis.sharedInstance().httping(
"https://ap-guangzhou.cls.tencentcs.com/ping",
output: CLSWriter()
) { result in
print("HttpPing detection result: \\(result?.description ?? "No result")")
}

//Method 2: HttpPing detection with custom fields.
let customFields = NSMutableDictionary()
customFields["detect_scene"] = "log_upload_failure"
customFields["api_endpoint"] = "ap-guangzhou"

ClsNetworkDiagnosis.sharedInstance().httping(
"https://ap-guangzhou.cls.tencentcs.com/ping",
output: CLSWriter(),
complate: { result in
guard let result = result else {
print("HttpPing detection failed.")
return
}
print("HttpPing detection result:")
print("- HTTP status code: \\(result.statusCode ?? 0)")
print("- Response time: \\(result.responseTime ?? "") ms")
print("- Full result: \\(result.description)")
},
customFiled: customFields
)
iftshi

Android Platform

Environment Requirements

Development tool: Android Studio.
Supported versions: Android 4.4 and above.
Build tool: Gradle.

Configuration Parameters

Parameter Name
Type
Description
Default Value
endpoint
String
Region information. For the domain name to use, refer to the API Log Upload tab in Available Regions.
-
accessKeyId (secretId)
String
Access key ID. This key must be granted the SDK log upload permission.
-
accessKeySecret (secretKey)
String
Access key secret. This key must be granted the SDK log upload permission.
-
topicId
String
Log topic ID, which can be obtained from the console.
-
token
String
Temporary key (optional).
-
lingerMs
Long
Delay for batch processing (in milliseconds).
2000
TotalSizeInBytes
Long
Upper limit for in-memory cache (in bytes).
100MB (100*1024*1024)
MaxBatchSize
Long
Maximum size of a single log batch (in bytes).
512KB (512*1024)
MaxBatchCount
Int
Maximum number of log entries in a single batch.
4096
MaxSendThreadCount
Long
Maximum number of concurrent sending threads.
50
MaxBlockSec
Int
Maximum blocking time for sending (in seconds).
60
Retries
Int
Number of retry attempts after a sending failure.
10
BaseRetryBackoffMs
Long
Initial backoff interval for retries (in milliseconds).
100
MaxRetryBackoffMs
Long
Maximum backoff interval for retries (in milliseconds).
50000
MaxReservedAttempts
Int
Number of reserved sending attempt records.
11
debuggable
Boolean
Debug mode switch. It must be disabled for release builds.
false

Integration Steps

Note:
The Android SDK source code is available at: https://github.com/TencentCloud/tencentcloud-cls-sdk-android.
1. Integrate the plugin. Add the following dependencies to your module-level build.gradle file.
Core log upload: implementation(group: 'com.tencentcloudapi.cls', name: 'tencentcloud-cls-sdk-android', version: '2.0.3').
Network detection plugin: implementation(group: 'com.tencentcloudapi.cls', name: 'cls-network-diagnosis-reporter-android', version: '2.0.3').
2. Configure permissions. Add the necessary permissions to AndroidManifest.xml.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
3. Configure network security (required for Android 9.0 and above).
3.1 Create a file named network_security_config.xml in the res/xml directory.
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">ap-guangzhou.cls.tencentcs.com</domain>
</domain-config>
</network-security-config>
3.2 Add the following attribute to the application tag in AndroidManifest.xml.
android:networkSecurityConfig="@xml/network_security_config"
4. Configure obfuscation. Add an obfuscation exemption rule for the LZ4 compression algorithm in proguard-rules.pro.
-keep class net.jpountz.lz4.** { *; }
5. Initialize the configuration.
5.1 Core log upload initialization.
import com.tencentcloudapi.cls.AsyncProducerClient;
import com.tencentcloudapi.cls.AsyncProducerConfig;
import com.tencentcloudapi.cls.NetworkUtils;

public class MyApplication extends Application {
private AsyncProducerClient client;

@Override
public void onCreate() {
super.onCreate();

String endpoint = "ap-guangzhou.cls.tencentcs.com";
String secretId = "your_accessKeyId";
String secretKey = "your_accessKeySecret";
String topicId = "your_topicId";

// Initialize the configuration.
AsyncProducerConfig config = new AsyncProducerConfig(endpoint, secretId, secretKey, "", NetworkUtils.getLocalMachineIP());
config.setLingerMs(2000); // Delay for batch processing. Default value: 2 seconds.
config.setMaxBatchSize(512 * 1024); // Maximum size of a single log batch. Default value: 512KB.
config.setTotalSizeInBytes(100 * 1024 * 1024); // Cache upper limit. Default value: 100MB.
config.setRetries(10); // Number of retry attempts. Default value: 10.
config.setMaxSendThreadCount(50); // Maximum number of concurrent threads. Default value: 50.
config.setMaxBlockSec(60); // Maximum blocking time for sending. Default value: 60 seconds.

// Build the client instance.
client = new AsyncProducerClient(config);
}

public AsyncProducerClient getClient() {
return client;
}
}
5.2 Network detection plugin initialization.
import com.tencentcloudapi.cls.adapter.CLSAdapter;
import com.tencentcloudapi.cls.config.CLSConfig;
import com.tencentcloudapi.cls.plugin.netdiagnosis.CLSNetDiagnosisPlugin;

public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();

// Initialize the plugin manager.
CLSAdapter adapter = CLSAdapter.getInstance();
adapter.addPlugin(new CLSNetDiagnosisPlugin());

// Initialize the configuration.
CLSConfig config = new CLSConfig(this);
config.endpoint = "ap-guangzhou.cls.tencentcs.com";
config.accessKeyId = "your_accessKeyId";
config.accessKeySecret = "your_accessKeySecret";
config.pluginAppId = "123456";
config.topicId = "your_topicId";
config.debuggable = true; // It should be disabled for release builds.
config.setAppName("your_app_name");
config.setAppVersion("1.0.0");
config.setUserId("user1");
config.setChannel("channel1");
config.setChannelName("Official channel");
config.setUserNick("Test user");
config.setLongLoginNick("Frequently used nickname");
config.setLongLoginUserId("long_login_user1");
config.setLoginType("wechat");
config.addCustomWithKey("customKey", "testValue");

adapter.init(config);
}
}
6. Log writing. The following example demonstrates how to write logs.
import com.tencentcloudapi.cls.LogItem;
import com.tencentcloudapi.cls.LogContent;
import java.util.ArrayList;
import java.util.List;

public class LogUploadUtils {
public static void sendLog(AsyncProducerClient client, String topicId) {
// Build a list of log contents.
List<LogContent> logContents = new ArrayList<>();
LogContent content1 = new LogContent();
content1.setKey("__CONTENT__");
content1.setValue("hello world");
LogContent content2 = new LogContent();
content2.setKey("city");
content2.setValue("guangzhou");
LogContent content3 = new LogContent();
content3.setKey("logNo");
content3.setValue("10001");
LogContent content4 = new LogContent();
content4.setKey("__PKG_LOGID__");
content4.setValue(String.valueOf(System.currentTimeMillis()));

logContents.add(content1);
logContents.add(content2);
logContents.add(content3);
logContents.add(content4);

// Build a log item (timestamp in seconds).
LogItem logItem = new LogItem((int) (System.currentTimeMillis() / 1000));
logItem.setContents(logContents);

// Upload logs in batches.
List<LogItem> logItems = new ArrayList<>();
logItems.add(logItem);
client.putLogs(topicId, logItems, result -> {
if (result.isSuccess()) {
System.out.println("Log upload successful.");
} else {
System.out.println("Log upload failed: " + result.getErrorMsg());
}
});
}
}
7. Network detection. The following example demonstrates how to use the network detection feature.
Ping detection.
import com.tencentcloudapi.cls.plugin.netdiagnosis.CLSNetDiagnosis;

public class NetworkDetectUtils {
public static void pingDetect() {
// Method 1: Basic Ping detection.
CLSNetDiagnosis.getInstance().ping("www.tencentcloud.com", new CLSNetDiagnosis.Output() {
@Override
public void write(String line) {
System.out.println(line);
}
}, new CLSNetDiagnosis.Callback() {
@Override
public void onComplete(String result) {
CLSLog.d("PingResult", String.format("ping result: %s", result));
}
});

// Method 2: Ping detection with specified detection count and package size.
CLSNetDiagnosis.getInstance().ping("www.tencentcloud.com", 10, 64, new CLSNetDiagnosis.Output() {
@Override
public void write(String line) {
System.out.println(line);
}
}, new CLSNetDiagnosis.Callback() {
@Override
public void onComplete(String result) {
CLSLog.d("PingResult", String.format("ping result: %s", result));
}
});
}
}
TCPPing detection.
import com.tencentcloudapi.cls.plugin.netdiagnosis.CLSNetDiagnosis;

public class NetworkDetectUtils {
public static void tcpPingDetect() {
// Method 1: Basic TCPPing detection.
CLSNetDiagnosis.getInstance().tcpPing("www.tencentcloud.com", 80, new CLSNetDiagnosis.Output() {
@Override
public void write(String line) {
System.out.println(line);
}
}, new CLSNetDiagnosis.Callback() {
@Override
public void onComplete(String result) {
CLSLog.d("TCPPingResult", String.format("tcpPing result: %s", result));
}
});

// Method 2: TCPPing detection with specified detection count and timeout.
CLSNetDiagnosis.getInstance().tcpPing("www.tencentcloud.com", 80, 10, 3000, new CLSNetDiagnosis.Output() {
@Override
public void write(String line) {
System.out.println(line);
}
}, new CLSNetDiagnosis.Callback() {
@Override
public void onComplete(String result) {
CLSLog.d("TCPPingResult", String.format("tcpPing result: %s", result));
}
});
}
}
TraceRoute detection.
import com.tencentcloudapi.cls.plugin.netdiagnosis.CLSNetDiagnosis;

public class NetworkDetectUtils {
public static void traceRouteDetect() {
// Method 1: Basic TraceRoute detection.
CLSNetDiagnosis.getInstance().traceroute("www.tencentcloud.com", new CLSNetDiagnosis.Output() {
@Override
public void write(String line) {
System.out.println(line);
}
}, new CLSNetDiagnosis.Callback() {
@Override
public void onComplete(String result) {
CLSLog.d("TraceRouteResult", String.format("traceRoute result: %s", result));
}
});

// Method 2: TraceRoute detection with specified maximum hops and detections per hop.
CLSNetDiagnosis.getInstance().traceroute("www.tencentcloud.com", 30, 3, new CLSNetDiagnosis.Output() {
@Override
public void write(String line) {
System.out.println(line);
}
}, new CLSNetDiagnosis.Callback() {
@Override
public void onComplete(String result) {
CLSLog.d("TraceRouteResult", String.format("traceRoute result: %s", result));
}
});
}
}
HttpPing detection.
import com.tencentcloudapi.cls.plugin.netdiagnosis.CLSNetDiagnosis;

public class NetworkDetectUtils {
public static void httpPingDetect() {
CLSNetDiagnosis.getInstance().httpPing("https://www.tencentcloud.com", new CLSNetDiagnosis.Output() {
@Override
public void write(String line) {
System.out.println(line);
}
}, new CLSNetDiagnosis.Callback() {
@Override
public void onComplete(String result) {
CLSLog.d("HttpPingResult", String.format("httpPing result: %s", result));
}
});
}
}

Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback