tencent cloud

Log Optimization Overview
Last updated:2026-02-10 16:11:36
Log Optimization Overview
Last updated: 2026-02-10 16:11:36

Introduction

This article describes how to centrally manage COS SDK logs through the logging-related methods provided by the client COS SDK, helping users understand the runtime details of the COS SDK and providing support for self-service troubleshooting.
This article introduces the standardized logging system provided by the COS SDK, which classifies and unifies log formats, supports multi-channel export, file log encryption, and flexible configuration. It helps developers manage logs more efficiently, quickly identify issues, and enhance troubleshooting efficiency.

Log Description

Log Levels

Level
Description
Scenarios
VERBOSE
The most detailed debugging information, used for tracing the details of code execution flow.
Debugging during the development phase
DEBUG
Debugging information for intermediate states of key processes.
Troubleshooting and process tracing
INFO
General information, recording the results of key operations.
User behavior statistics, business monitoring
WARN
Warning messages, indicating potential issues.
Abnormality monitoring and early warning
ERROR
Error messages indicating feature failure.
Error analysis and repair

Log Classification

Classification
Description
PROCESS
Operation process log
RESULT
Operation result log
NETWORK
Network layer log
PROBE
Network probe log (a probe is initiated when failure occurs due to network connection)
ERROR
Error stack log

Log Entity

Field
Field Key
Description
Type
Timestamp.
timestamp
Precise to the millisecond
long
Level
level
Log level
Enumeration
Category
category
Log Classification
Enumeration
Thread
threadName
Current thread name
String
Tag APIs
tag
Custom Tags, used to distinguish business modules (such as Upload and Download)
String
Message content
message
Log body information, supports formatted strings
String
Device ID
deviceID
Device ID
String
Model
deviceModel
Model
String
APP version
appVersion
APP version
String
Extended information
extras
Optional fields (such as device information and user information)
Comes with qcloud_platform: Android, iOS, and so on
Merged with deviceID, deviceModel, and appVersion during output
map<string, string>

Log Output Method

Console

Console logs compatible with various systems, organized according to the log format of each platform. The example format for Android is Time Tag Package name [Category][Thread] Message content - Extended fields map.


Local Files

Store logs to local files, supporting automatic file splitting, encrypted storage, and so on. The complete format is Level/Time [Thread] [Category Tag] [Message Content] [Extended Fields map].


Service Callback

By dynamically registering and deregistering service callbacks, a structured log object is passed in the callback for developers to perform custom processing (for example, reporting to their own log systems).


CLS

Report structured log objects to cls, supporting multiple cls credential configurations.



Basic Configuration

Android
iOS
Flutter
React Native
Web
COSLogger enables the configuration and management of logs.
Note:
Since the initialization of COSLogger depends on CosXmlBaseService, it should be called after CosXmlService or CosXmlSimpleService is initialized for the first time.
// The enablement and disablement of console and file logging can be configured via the setDebuggable method in CosXmlServiceConfig. Logging is enabled when set to true.

// whether to enable console logging
COSLogger.enableLogcat(true);
// whether to enable file logging
COSLogger.enableLogFile(true);
// Define a log listener
CosLogListener listener = new CosLogListener() {
@Override
public void onLog(LogEntity entity) {
Log.d("CosLogListener", entity.getLogcatString());
}
};
// Add a log listener
COSLogger.addLogListener(listener);
// Remove a log listener
COSLogger.removeLogListener(listener);
// Set the global minimum log level (channel settings take precedence over global settings)
COSLogger.setMinLevel(LogLevel.VERBOSE);
// Set the minimum log level for console logging
COSLogger.setLogcatMinLevel(LogLevel.VERBOSE);
// Set the minimum log level for file logging
COSLogger.setFileMinLevel(LogLevel.VERBOSE);
// Set the minimum log level for cls (must be configured after setCLsChannel, otherwise it will not take effect)
COSLogger.setClsMinLevel(LogLevel.VERBOSE);
// Set Device ID
COSLogger.setDeviceID("DeviceID");
// Set Device Model
COSLogger.setDeviceModel("DeviceModel");
// Set APP version number
COSLogger.setAppVersion("AppVersion");
// Set extension field
Map<String, String> extras = new HashMap<>();
extras.put("userID", "userID");
COSLogger.setExtras(extras);
// Obtain the log file list, with the parameter specifying the number of recent ones, e.g., the last 10 log files
File[] files = COSLogger.getLogFiles(10);
// Get the log file directory path
String logRootDir = COSLogger.getLogRootDir();
// Add custom masking rules
COSLogger.addSensitiveRule("(q-ak=)[^&\\\\\\\\s]+", "$1***");
// Remove masking rule
COSLogger.removeSensitiveRule("(q-ak=)[^&\\\\\\\\s]+");
QCloudLogger enables log configuration and management.
// Set console log level
[QCloudLogger sharedLogger].logLevel = QCloudLogLevelVerbose;
// Set file log level
[QCloudLogger sharedLogger].logFileLevel = QCloudLogLevelVerbose;
// Set the minimum log level for cls (QCloudCLSLoggerOutput must be configured, otherwise it will not take effect)
[QCloudLogger sharedLogger].logClsLevel = QCloudLogLevelVerbose;
// Define a log listener
QCloudCustomLoggerOutput * output = [[QCloudCustomLoggerOutput alloc]init];
output.callback = ^(QCloudLogModel * _Nonnull model, NSDictionary * _Nonnull extendInfo) {

};
// Add a log listener
[[QCloudLogger sharedLogger] addLogger:output];
// Remove a log listener
[[QCloudLogger sharedLogger] removeLogger:output];
// Set Device ID
[QCloudLogger sharedLogger].deviceID = @"deviceID";
// Set Device Model
[QCloudLogger sharedLogger].deviceModel = @"deviceModel";
// Set APP version number
[QCloudLogger sharedLogger].appVersion = @"appVersion";
// Set extension field
[QCloudLogger sharedLogger].extendInfo = @{@"userID":@"userID"};
// Get the log file directory path
NSString * logDir = [QCloudLogger sharedLogger].logDirctoryPath;
Cos() enables the configuration and management of logs via its functionality.
Note:
Since log initialization depends on CosService, logging-related features must be invoked after registerDefaultService or registerDefaultTransferManger is called.
// whether to enable console logging
await Cos().enableLogcat(true);
// whether to enable file logging
await Cos().enableLogFile(true);
// Define a log listener
loglistener(log) {
print(log.message);
}
// Add a log listener
await Cos().addLogListener(loglistener);
// Remove a log listener
await Cos().removeLogListener(loglistener);
// Set the global minimum log level (channel settings take precedence over global settings)
await Cos().setMinLevel(LogLevel.verbose);
// Set the minimum log level for console logging
await Cos().setLogcatMinLevel(LogLevel.verbose);
// Set the minimum log level for file logging
await Cos().setFileMinLevel(LogLevel.verbose);
// Set the minimum log level for cls (must be configured after setCLsChannel, otherwise it will not take effect)
await Cos().setClsMinLevel(LogLevel.verbose);
// Set Device ID
await Cos().setDeviceID("DeviceID");
// Set Device Model
await Cos().setDeviceModel("DeviceModel");
// Set APP version number
await Cos().setAppVersion("AppVersion");
// Set extension field
await Cos().setExtras({"userId":"1"});
// Get the log file directory path
String logRootDir = await Cos().getLogRootDir()
Logs are configured and managed through Cos.
Note:
Since log initialization depends on CosService, logging-related features must be invoked after registerDefaultService or registerDefaultTransferManger is called.
// whether to enable console logging
await Cos.enableLogcat(true);
// whether to enable file logging
await Cos.enableLogFile(true);
// Add a log listener
await Cos.addLogListener("cos", (log) => {
console.log(log);
})
// Remove a log listener
await Cos.removeLogListener("cos");
// Set the global minimum log level (channel settings take precedence over global settings)
await Cos.setMinLevel(LogLevel.verbose);
// Set the minimum log level for console logging
await Cos.setLogcatMinLevel(LogLevel.verbose);
// Set the minimum log level for file logging
await Cos.setFileMinLevel(LogLevel.verbose);
// Set the minimum log level for cls (must be configured after setCLsChannel, otherwise it will not take effect)
await Cos.setClsMinLevel(LogLevel.verbose);
// Set Device ID
await Cos.setDeviceID("DeviceID");
// Set Device Model
await Cos.setDeviceModel("DeviceModel");
// Set APP version number
await Cos.setAppVersion("AppVersion");
// Set extension field
await Cos.setExtras({"userId":"1"});
// Get the log file directory path
let logRootDir = await Cos.getLogRootDir();
During COS initialization, configure and manage logs.
const cos = new COS({
// Other configurations remain unchanged.
// Local log related
EnableLog: true, // Enable logging
EnableLogcat: true, // Output logs to the console
LogLevel: 'VERBOSE', // Log level
LogExtras: { userId: '123' } // Additional log information
});
cos.on('log-message', msg => {
// Log callback
console.log(msg);
});

File Log Encryption and Decryption

Encrypting

Android
iOS
Flutter
React Native
File logging can be encrypted via COSLogger.
Note:
Since the initialization of COSLogger depends on CosXmlBaseService, it should be called after CosXmlService or CosXmlSimpleService is initialized for the first time.
byte[] key = new byte[] {
// 32-byte hexadecimal representation (example value; use secure random number generation in practice)
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
};
byte[] iv ={
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F
};
COSLogger.setLogFileEncryptionKey(key, iv);
File log encryption can be configured via QCloudLogger.
// 32-byte hexadecimal representation (example value; use secure random number generation in practice)
NSData *keyData = [NSData dataWithBytes:(unsigned char[]){
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
} length:32];

NSData *ivData = [NSData dataWithBytes:(unsigned char[]){
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F
} length:16];
[QCloudLogger sharedLogger].aesKey = keyData;
[QCloudLogger sharedLogger].aesIv = ivData;
File log encryption can be configured via Cos().
Note:
Since log initialization depends on CosService, logging-related features must be invoked after registerDefaultService or registerDefaultTransferManger is called.
// Create encryption keys and initialization vectors
final key = Uint8List.fromList([
// 32-byte key (example value; use secure random number generation in practice)
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
]);

final iv = Uint8List.fromList([
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F
]);

// Call the method to set the log file encryption key
await Cos().setLogFileEncryptionKey(key, iv);
File log encryption can be enabled via Cos.
Note:
Since log initialization depends on CosService, logging-related features must be invoked after registerDefaultService or registerDefaultTransferManger is called.
// Create a 32-byte key and a 16-byte IV (example value; use secure random number generation in practice)
const key = new Uint8Array([
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
]);

const iv = new Uint8Array([
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F
]);

// Method for setting log file encryption key
await Cos.setLogFileEncryptionKey(key, iv);

Performs decryption

The format of encrypted log file content is [4-byte length header][ciphertext data][4-byte length header][ciphertext data]....
After reading the file during decryption, split the ciphertext into blocks and decrypt each block separately to obtain the original logs.
The following is a Java code sample:
public class AesLogDecryptor {
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";

public static void main(String[] args) {
try {
// The key and iv must be consistent with those configured during encryption.
byte[] key = new byte[] {
// 32-byte hexadecimal representation (example value; use secure random number generation in practice)
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
};
byte[] iv ={
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F
};
// Encrypted log file path
String encryptedFilePath = "2025-04-10-12-04-21_encrypt.log";
// Output path of the decrypted log file
String decryptedFilePath = "2025-04-10-12-04-21_encrypt.log.decrypted";

// Decrypt the file
decryptLogFile(new File(encryptedFilePath), new File(decryptedFilePath), key, iv);

System.out.println("Decryption completed, result saved to: " + decryptedFilePath);
} catch (Exception e) {
System.err.println("Error occurred during decryption: " + e.getMessage());
e.printStackTrace();
}
}

/**
* Decrypting encrypted log files
* @param encryptedFile Encrypted log file
* @param decryptedFile Decrypted output file
* @param key AES key
* @param iv Initialization vector
* @throws Exception Exception that may be thrown during decryption
*/
public static void decryptLogFile(File encryptedFile, File decryptedFile, byte[] key, byte[] iv) throws Exception {
System.err.print("iv: "+ Arrays.toString(iv));

SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);

try (DataInputStream dis = new DataInputStream(new FileInputStream(encryptedFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(decryptedFile))) {

while (dis.available() > 0) {
// Read the 4-byte length header (big-endian)
int length = dis.readInt();

// Read ciphertext data
byte[] encrypted = new byte[length];
dis.readFully(encrypted);

// Decrypt the data
String decrypted = new String(decryptSingle(encrypted, keySpec, ivSpec), StandardCharsets.UTF_8);

// Write decrypted content to the output file
writer.write(decrypted);
}
}
}

/**
* Decrypt a single data block
* @param ciphertext Ciphertext data
* @param keySpec Key specification
* @param ivSpec Initialization vector specification
* @return Decrypted byte array
* @throws Exception Exception that may be thrown during decryption
*/
private static byte[] decryptSingle(byte[] ciphertext, SecretKeySpec keySpec, IvParameterSpec ivSpec) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
return cipher.doFinal(ciphertext);
}
}

Report Logs to CLS

Report the runtime logs of the COS SDK to Tencent Cloud CLS. You can view specific logs on the CLS console to facilitate subsequent analysis.
Note:
Client COS SDK logs will be reported to Tencent Cloud CLS. The reported logs are billed according to CLS billing rules. For details, see CLS billing overview.
1. Create a CLS log topic
Log in to Tencent Cloud CLS console, after creating a log topic, click the name to go to the Basic Information tab to obtain the log topic ID and region. For details, see CLS region description. For example: the log topic ID is c09216e3-ade5-4725-a000-000000000000, and the region is ap-guangzhou.
2. Configure within the COS SDK.
Android
iOS
Flutter
React Native
Web
Step 1: Install the CLS SDK.
At the application level (typically under the App module), add the dependency in build.gradle:
dependencies {
...
// Add these two lines
implementation 'com.tencentcloudapi.cls:tencentcloud-cls-sdk-android:1.0.5'
implementation 'com.google.guava:guava:27.0.1-android'
}
Step 2: Set the log reporting CLS channel.
Temporary Keys
Fixed Key (For Testing Only)
1. Implement a ClsLifecycleCredentialProvider subclass that implements the process of requesting temporary credentials and returning the result.
For obtaining temporary keys, you can refer to: Using temporary keys to access CLS, Obtain federated identity temporary access credentials (set the action to name/cls:pushLog in the authorization policy).
ClsLifecycleCredentialProvider clsLifecycleCredentialProvider = new ClsLifecycleCredentialProvider() {
@Override
protected ClsSessionCredentials fetchNewCredentials() throws ClsAuthenticationException {
// First, obtain a response containing key information from your temporary key server

// Then parse the response to obtain the temporary key information
String tmpSecretId = "SECRETID"; // Temporary key SecretId
String tmpSecretKey = "SECRETKEY"; // Temporary key SecretKey
String sessionToken = "SESSIONTOKEN"; // Temporary key Token
long expiredTime = 1556183496L; // Expiration timestamp of the temporary key in seconds

// Finally, return the temporary key information object
return new ClsSessionCredentials(tmpSecretId, tmpSecretKey,
sessionToken, expiredTime);
}
};
Note:
It is recommended that users use temporary keys to further enhance security through temporary authorization. When applying for temporary keys, please follow the principle of least privilege to prevent leakage of non-target resources.
If you must use permanent keys, it is recommended to follow the principle of least privilege to restrict the permission scope of the permanent keys.
2. Initialize CLS reporting
// CLS log topic ID and region
String topicId = "c09216e3-ade5-4725-a000-000000000000";
String topicEndpoint = "ap-guangzhou.cls.tencentcs.com";

// clsLifecycleCredentialProvider is the cls temporary key provider obtained in the previous step
// Set up CLS channel (temporary key)
COSLogger.setCLsChannel(topicId, topicEndpoint, clsLifecycleCredentialProvider);
You can use Tencent Cloud's fixed keys for local debugging during the development phase. Due to the risk of key leakage with this method, it must be replaced with non-anonymous mode prior to release.
// User's SecretId. It is recommended to use a sub-account key, with authorization following the principle of least privilege to reduce usage risks.
// Sub-account key obtainment can be referred to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
String secretId = "SECRETID";
// User's SecretKey. It is recommended to use a sub-account key, with authorization following the principle of least privilege to reduce usage risks.
// Sub-account key obtainment can be referred to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
String secretKey = "SECRETKEY";

// CLS log topic ID and region
String topicId = "c09216e3-ade5-4725-a000-000000000000";
String topicEndpoint = "ap-guangzhou.cls.tencentcs.com";

//Set up fixed key CLS channel (for testing only; not recommended to use fixed keys in production environments)
COSLogger.setCLsChannel(topicId, topicEndpoint, secretId, secretKey);
Step 3: Configure Network Permissions.
Log upload is based on http, therefore http access must be enabled for the xxx.cls.tencentcs.com domain.
1. Create an xml folder under the res directory, then create a network_security_config.xml file with the following content:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<!--cls-->
<domain includeSubdomains="true">cls.tencentcs.com</domain>
</domain-config>
</network-security-config>
2. Add the following attribute to the application Tag in the AndroidManifest.xml file:
<application
...
android:networkSecurityConfig="@xml/network_security_config"
...
/>
Step 1: Install the CLS SDK.
Add the CLS SDK dependency in the podfile file.
pod "QCloudTrack/Cls"
Step 2: Set the log reporting CLS channel.
Temporary Keys
Fixed Key (For Testing Only)
1. Implement a ClsLifecycleCredentialProvider subclass that implements the process of requesting temporary credentials and returning the result.
For obtaining temporary keys, you can refer to: Using temporary keys to access CLS, Obtain federated identity temporary access credentials (set the action to name/cls:pushLog in the authorization policy).
QCloudCLSLoggerOutput * clsOutput = [[QCloudCLSLoggerOutput alloc]initWithTopicId:@"c09216e3-ade5-4725-a000-000000000000" endpoint:@"ap-guangzhou.cls.tencentcs.com"];
[clsOutput setupCredentialsRefreshBlock:^QCloudCredential * _Nonnull{
dispatch_semaphore_t semp = dispatch_semaphore_create(0);
NSMutableURLRequest * mrequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"Temporary key server address"]];
__block QCloudCredential * credential = nil;
// First, obtain the response containing key information from your temporary key server
[[[NSURLSession sharedSession]dataTaskWithRequest:mrequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data) {
credential = [QCloudCredential new];
NSDictionary * result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSDictionary * credentials = result[@"credentials"];
credential.secretID = credentials[@"tmpSecretId"];
credential.secretKey = credentials[@"tmpSecretKey"];
credential.token = credentials[@"sessionToken"];
credential.expirationDate = [NSDate dateWithTimeIntervalSinceNow:[credentials[@"sessionToken"] integerValue]];
}
dispatch_semaphore_signal(semp);
}]resume];
dispatch_semaphore_wait(semp, DISPATCH_TIME_FOREVER);
return credential;
}];
[[QCloudLogger sharedLogger] addLogger:clsOutput];
Note:
It is recommended that users use temporary keys to further enhance security through temporary authorization. When applying for temporary keys, please follow the principle of least privilege to prevent leakage of non-target resources.
If you must use permanent keys, it is recommended to follow the principle of least privilege to restrict the permission scope of the permanent keys.
2. Initialize CLS reporting
// CLS log topic ID and region
String topicId = "c09216e3-ade5-4725-a000-000000000000";
String topicEndpoint = "ap-guangzhou.cls.tencentcs.com";

// clsLifecycleCredentialProvider is the cls temporary key provider obtained in the previous step
// Set up CLS channel (temporary key)
COSLogger.setCLsChannel(topicId, topicEndpoint, clsLifecycleCredentialProvider);
You can use Tencent Cloud's fixed keys for local debugging during the development phase. Due to the risk of key leakage with this method, it must be replaced with non-anonymous mode prior to release.
// User's SecretId. It is recommended to use a sub-account key, with authorization following the principle of least privilege to reduce usage risks.
// Sub-account key obtainment can be referred to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
NSString * secretId = @"SECRETID";
// User's SecretKey. It is recommended to use a sub-account key, with authorization following the principle of least privilege to reduce usage risks.
// Sub-account key obtainment can be referred to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
NSString * secretKey = @"SECRETKEY";
QCloudCLSLoggerOutput * clsOutput = [[QCloudCLSLoggerOutput alloc]initWithTopicId:@"c09216e3-ade5-4725-a000-000000000000" endpoint:@"ap-guangzhou.cls.tencentcs.com"];
[clsOutput setupPermanentCredentialsSecretId:secretId secretKey:secretKey];
[[QCloudLogger sharedLogger] addLogger:clsOutput];
Note:
Log upload is based on http, therefore http access must be enabled for the xxx.cls.tencentcs.com domain.
To support HTTP requests, it is necessary to add "App Transport Security Settings" -> "Allow Arbitrary Loads" in the project's info.plist file and set it to YES.
Step 1: Install the CLS SDK.
Android
iOS
In the Android directory, at the application level (typically under the App module), add the dependency in build.gradle:
dependencies {
...
// Add these two lines
implementation 'com.tencentcloudapi.cls:tencentcloud-cls-sdk-android:1.0.5'
implementation 'com.google.guava:guava:27.0.1-android'
}
Add the dependency in the podfile at the application level (typically under the App module) in the iOS directory:
pod "QCloudTrack/Cls"
Step 2: Set the log reporting CLS channel.
Temporary Keys
Fixed Key (For Testing Only)
1. Implement a subclass of IFetchCLsChannelCredentials to handle the process of requesting temporary credentials and returning the result.
For obtaining temporary keys, you can refer to: Using temporary keys to access CLS, Obtain federated identity temporary access credentials (set the action to name/cls:pushLog in the authorization policy).
class CLSFetchCLsChannelCredentials implements IFetchCLsChannelCredentials{
@override
Future<SessionQCloudCredentials> fetchCLsChannelSessionCredentials() async {
// First, obtain the response containing key information from your temporary key server
// Then parse the response to obtain the temporary key information
String tmpSecretId = "SECRETID"; // Temporary key SecretId
String tmpSecretKey = "SECRETKEY"; // Temporary key SecretKey
String sessionToken = "SESSIONTOKEN"; // Temporary key Token
long expiredTime = 1556183496L; // Expiration timestamp of the temporary key, in seconds
// Finally, return the temporary key information object
return SessionQCloudCredentials(
secretId: tmpSecretId,
secretKey: tmpSecretKey,
token: sessionToken,
expiredTime: expiredTime
);
}
}
Note:
It is recommended that users use temporary keys to further enhance security through temporary authorization. When applying for temporary keys, please follow the principle of least privilege to prevent leakage of non-target resources.
If you must use permanent keys, it is recommended to follow the principle of least privilege to restrict the permission scope of the permanent keys.
2. Initialize CLS reporting
// CLS log topic ID and region
String topicId = "c09216e3-ade5-4725-a000-000000000000";
String topicEndpoint = "ap-guangzhou.cls.tencentcs.com";

// CLSFetchCLsChannelCredentials is the cls temporary key provider obtained in the previous step
// Set up CLS channel (temporary key)
await Cos().setCLsChannelSessionCredential(topicId, topicEndpoint, CLSFetchCLsChannelCredentials());
You can use Tencent Cloud's fixed keys for local debugging during the development phase. Due to the risk of key leakage with this method, it must be replaced with non-anonymous mode prior to release.
// User's SecretId. It is recommended to use a sub-account key, with authorization following the principle of least privilege to reduce usage risks.
// Sub-account key obtainment can be referred to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
String secretId = "SECRETID";
// User's SecretKey. It is recommended to use a sub-account key, with authorization following the principle of least privilege to reduce usage risks.
// Sub-account key obtainment can be referred to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
String secretKey = "SECRETKEY";

// CLS log topic ID and region
String topicId = "c09216e3-ade5-4725-a000-000000000000";
String topicEndpoint = "ap-guangzhou.cls.tencentcs.com";

//Set up fixed key CLS channel (for testing only; not recommended to use fixed keys in production environments)
await Cos().setCLsChannelStaticKey(topicId, topicEndpoint, secretId, secretKey);
Step 3: Configure Network Permissions.
Log upload is based on http, therefore http access must be enabled for the xxx.cls.tencentcs.com domain.
Android
iOS
In the Android directory, at the application level (typically under the App module)
1. Create an xml folder under the res directory, then create a network_security_config.xml file with the following content:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<!--cls-->
<domain includeSubdomains="true">cls.tencentcs.com</domain>
</domain-config>
</network-security-config>
2. Add the following attribute to the application Tag in the AndroidManifest.xml file:
<application
...
android:networkSecurityConfig="@xml/network_security_config"
...
/>
Log upload is based on http, therefore http access must be enabled for the xxx.cls.tencentcs.com domain.
To support HTTP requests, it is necessary to add "App Transport Security Settings" -> "Allow Arbitrary Loads" in the project's info.plist file and set it to YES.
Step 1: Install the CLS SDK.
Android
iOS
In the Android directory, at the application level (typically under the App module), add the dependency in build.gradle:
dependencies {
...
// Add these two lines
implementation 'com.tencentcloudapi.cls:tencentcloud-cls-sdk-android:1.0.5'
implementation 'com.google.guava:guava:27.0.1-android'
}
Add the dependency in the podfile at the application level (typically under the App module) in the iOS directory:
pod "QCloudTrack/Cls"
Step 2: Set the log reporting CLS channel.
Temporary Keys
Fixed Key (For Testing Only)
For obtaining temporary keys, you can refer to: Using temporary keys to access CLS, Obtain federated identity temporary access credentials (set the action to name/cls:pushLog in the authorization policy).
// CLS log topic ID and region
let topicId = "c09216e3-ade5-4725-a000-000000000000";
let topicEndpoint = "ap-guangzhou.cls.tencentcs.com";

// Set up CLS channel (temporary key)
Cos.setCLsChannelSessionCredential(topicId, topicEndpoint, async () => {
// First, obtain the response containing key information from your temporary key server
// Then parse the response to obtain the temporary key information
let tmpSecretId = "SECRETID"; // Temporary key SecretId
let tmpSecretKey = "SECRETKEY"; // Temporary key SecretKey
let sessionToken = "SESSIONTOKEN"; // Temporary key Token
let expiredTime = 1556183496L; // Expiration timestamp of the temporary key, in seconds
// Finally, return the temporary key information object
const sessionCredentials = {
tmpSecretId: tmpSecretId,
tmpSecretKey: tmpSecretKey,
expiredTime: expiredTime,
sessionToken: sessionToken
};
return sessionCredentials;
});
Note:
It is recommended that users use temporary keys to further enhance security through temporary authorization. When users apply for temporary keys, please follow the principle of least privilege to prevent leakage of non-target resources.
If you must use permanent keys, it is recommended to follow the principle of least privilege to restrict the permission scope of the permanent keys.
You can use Tencent Cloud's fixed keys for local debugging during the development phase. Due to the risk of key leakage with this method, it must be replaced with non-anonymous mode prior to release.
// User's SecretId. It is recommended to use a sub-account key, with authorization following the principle of least privilege to reduce usage risks.
// Sub-account key obtainment can be referred to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
let secretId = "SECRETID";
// User's SecretKey. It is recommended to use a sub-account key, with authorization following the principle of least privilege to reduce usage risks.
// Sub-account key obtainment can be referred to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
let secretKey = "SECRETKEY";

// CLS log topic ID and region
let topicId = "c09216e3-ade5-4725-a000-000000000000";
let topicEndpoint = "ap-guangzhou.cls.tencentcs.com";

//Set up fixed key CLS channel (for testing only; not recommended to use fixed keys in production environments)
await Cos.setCLsChannelStaticKey(topicId, topicEndpoint, secretId, secretKey)
Step 3: Configure Network Permissions.
Log upload is based on http, therefore http access must be enabled for the xxx.cls.tencentcs.com domain.
Android
iOS
In the Android directory, at the application level (typically under the App module)
1. Create an xml folder under the res directory, then create a network_security_config.xml file with the following content:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<!--cls-->
<domain includeSubdomains="true">cls.tencentcs.com</domain>
</domain-config>
</network-security-config>
2. Add the following attribute to the application Tag in the AndroidManifest.xml file:
<application
...
android:networkSecurityConfig="@xml/network_security_config"
...
/>
Log upload is based on http, therefore http access must be enabled for the xxx.cls.tencentcs.com domain.
To support HTTP requests, it is necessary to add "App Transport Security Settings" -> "Allow Arbitrary Loads" in the project's info.plist file and set it to YES.
Step 1: Access link to download the CLS reporting sdk.
const ClsClient = require('demo/common/cls.min.js');
Step 2: Set the log reporting CLS channel.
const clsClient = new ClsClient({
topicId: 'c09216e3-ade5-4725-a000-000000000000', // log topic id
region: 'ap-guangzhou', // region of the log topic, such as ap-guangzhou
maxRetainDuration: 30, // Default 30s
maxRetainSize: 20, // Default 20 entries
});
const cos = new COS({
ClsLogger: clsClient, // Output logs to cls
});


Best Practices

Below provides practical recommendations for some common scenarios. Developers can flexibly adjust them based on their own business contexts.
Development Debugging: Console logs + DEBUG level
Retrieval or Active Reporting: Local file logs + DEBUG level
Background daily collection and aggregation: business callback or CLS + DEBUG or INFO level
Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback