All Products
Search
Document Center

Simple Log Service:Get started with Simple Log Service SDK for Flutter

Last Updated:Mar 25, 2024

This topic describes how to use Simple Log Service SDK for Flutter to collect logs.

Prerequisites

Simple Log Service SDK for Flutter is installed. For more information, see Install Simple Log Service SDK for Flutter.

Initialize the SDK

In common scenarios, you can initialize the SDK based on the following code. If you want to specify the size of each log packet that needs to be sent to Simple Log Service and enable the resumable upload feature, you can configure the LogProducerConfiguration class. For more information, see Configure the parameters in the LogProducerConfiguration class.

import 'package:aliyun_log_dart_sdk/aliyun_log_dart_sdk.dart';

AliyunLogDartSdk? _aliyunLogSdk;

void _initProducer() async {
  // Specify the Simple Log Service endpoint, project name, and Logstore name. You can dynamically configure the parameters. 
    LogProducerConfiguration configuration = LogProducerConfiguration(
      endpoint: 'your endpoint', project: 'your project', logstore: 'your logstore'
    ); 
  // The AccessKey pair that is used to access Simple Log Service. For more information, see AccessKey pair. The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Simple Log Service is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
    configuration.accessKeyId = 'your access key id';
    configuration.accessKeySecret = 'your access key secret';
    configuration.securityToken = 'your access key token'; // Specify the Security Token Service (STS) token. This parameter is required only if you use STS to obtain a temporary AccessKey pair. 
    _aliyunLogSdk = AliyunLogDartSdk();
    LogProducerResult result = await _aliyunLogSdk!.initProducer(configuration);
}

For more information about how to obtain the required information for SDK initialization, see the following topics:

Report logs

You can use the addLog method to report custom business logs.

LogProducerResult code = await _aliyunLogSdk!.addLog({
 'str': 'str value',
 'int': 12,
 'double': 12.12,
 'boolean': true,
 'map': {'key': 'value', 'inntt': 3333},
 'array': ['a1', 'a2'],
 'null': null,
 'content': 'Chinese'
});

If code == LogProducerResult.ok is returned, logs are reported. If error codes are returned, you can troubleshoot the errors by following the instructions provided in the Error codes section of this topic.

Obfuscation rules

If obfuscation is enabled for your Flutter project, you must add the following rules to the obfuscation configuration file of the flutter project. Otherwise, Android projects may not run as expected. By default, obfuscation is enabled for Flutter V1.16.2 and later. iOS projects are not affected by the rules.

-keep class com.aliyun.sls.android.producer.* { *; }
-keep interface com.aliyun.sls.android.producer.* { *; }

Configure dynamic parameters

Simple Log Service SDK for Flutter supports dynamic configuration of parameters such as Endpoint, Project, Logstore, and AccessKey.

  • Sample code that is used to dynamically configure the Endpoint, Project, and Logstore parameters:

    await _aliyunLogSdk!.setEndpoint('new-endpoint');
    await _aliyunLogSdk!.setProject('new-project-name');
    await _aliyunLogSdk!.setLogstore('new-logstore-name');
  • Sample code that is used to dynamically configure the AccessKey parameter:

    // The SecurityToken parameter is optional. This parameter is required only if you use STS to obtain a temporary AccessKey pair. 
    await _aliyunLogSdk!.setAccessKey('your accesskey id', 'your accesskey secret', securityToken: 'your accesskey token');
  • Sample code that is used to dynamically configure the Source, Topic, and Tag parameters:

    await _aliyunLogSdk!.setSource('flutter');
    await _aliyunLogSdk!.setTopic('flutter-test');
    await _aliyunLogSdk!.addTag('tag1', 'value1');
    await _aliyunLogSdk!.addTag('tag2', 'value2');
  • Sample code that is used to dynamically configure other parameters:

    Important

    The AliyunLogDartSdk.updateConfiguration() method does not support dynamic configuration of resumable upload-related parameters.

    LogProducerConfiguration configuration = LogProducerConfiguration();
    configuration.dropDelayLog = true;
    configuration.dropUnauthorizedLog = true;
    // You can dynamically configure the parameters in the LogProducerConfiguration class in the same manner. 
    await _aliyunLogSdk!.updateConfiguration(configuration);

Configure callback for log sending

Simple Log Service SDK for Flutter supports callback for log sending. When a log is sent or fails to be sent, callback information is generated. You can use the callback information to view the status of the SDK or update the parameter settings of the SDK.

_aliyunLogSdk!.setLogCallback((resultCode, errorMessage, logBytes, compressedBytes) {
	// A parameter error occurs. You need to update parameter settings. 
	if (LogProducerResult.parametersInvalid == resultCode) {
	// For example, you can modify the Endpoint parameter. 
	_aliyunLogSdk!.setEndpoint('your endpoint');
	// A parametersInvalid error occurs. This is because no AccessKey pair is specified or the specified AccessKey pair is invalid. 
	_aliyunLogSdk!.setAccessKey('your access key id', 'your access key secret', securityToken: 'your token');
}

 	// An authorization timeout error occurs. You need to update your AccessKey pair. 
	if (LogProducerResult.sendUnauthorized == resultCode) {
		_aliyunLogSdk!.setAccessKey('your access key id', 'your access key secret', securityToken: 'your token');
	}
});

Enable resumable upload

Important

If you want to enable the resumable upload feature, you must enable the feature when you initialize AliyunLogDartSdk. After you initialize the SDK, you cannot dynamically modify the parameters related to resumable upload.

Sample code that is used to enable resumable upload when AliyunLogDartSdk is initialized:

configuration.persistent = true; // Enable resumable upload. 
configuration.persistentFilePath = 'flutter/demo'; // The path to the cache of binary logs. 
configuration.persistentForceFlush = false; // Disable forceful refresh. We recommend that you disable forceful refresh because it deteriorates system performance. 
configuration.persistentMaxFileCount = 10; // The maximum number of files that can be cached. Default value: 10. 
configuration.persistentMaxFileSize = 1024 * 1024; // The maximum size of each cached file. Default value: 1024 * 1024. 
configuration.persistentMaxLogCount = 64 * 1024; // The maximum number of logs that can be cached. Default value: 64 * 1024. 
_aliyunLogSdk = AliyunLogDartSdk();
LogProducerResult result = await _aliyunLogSdk!.initProducer(configuration);

Configure the parameters in the LogProducerConfiguration class

The following table describes the parameters that you can configure in the LogProducerConfiguration class.

Parameter

Type

Description

endpoint

string

The Simple Log Service endpoint for the region in which the project resides. Example: cn-hangzhou.log.aliyuncs.com. For more information about how to obtain an endpoint, see Endpoints.

project

string

The name of the project. For more information, see Project.

logstore

string

The name of the Logstore. For more information, see Logstore.

accesskeyId

string

The AccessKey ID that is used to access Simple Log Service. For more information about how to obtain an AccessKey ID, see AccessKey pair.

accessKeySecret

string

The AccessKey secret that is used to access Simple Log Service. For more information about how to obtain an AccessKey secret, see AccessKey pair.

securityToken

string

The STS token that is used to obtain a temporary AccessKey pair. If you use STS to obtain a temporary AccessKey pair, you must configure this parameter. For more information about how to obtain an STS token, see AssumeRole.

debuggable

bool

Specifies whether to enable the debugging mode. Default value: false.

If you encounter data collection issues, we recommend that you enable the debugging mode.

maxBufferLimit

int

The maximum available memory. Default value: 64 * 1024 * 1024. Unit: bytes.

connectTimeout

int

The timeout period for a network connection. Default value: 10. Unit: seconds. We recommend that you retain the default value.

sendTimeout

int

The timeout period for a sending operation. Default value: 15. Unit: seconds. We recommend that you retain the default value.

ntpTimeOffset

int

The difference between the device time and standard time. Default value: 0. Unit: seconds. We recommend that you retain the default value. The SDK supports automatic time correction.

maxLogDelayTime

int

The difference between the log time and local time. Default value: 7. Unit: days. If this value is exceeded, the SDK resolves the issue based on the setting of the dropDelayLog parameter. We recommend that you retain the default value.

dropDelayLog

bool

Specifies whether to discard a log whose difference between the log time and local time exceeds the value of the maxLogDelayTime parameter. Default value: false. The value of the __time__ field is reset to the current time.

dropUnauthorizedLog

bool

Specifies whether to discard a log that records a failed authentication. Default value: false.

source

string

The log source, which is the same as the value of the __source__ field. Default value: Android or iOS.

topic

string

The log topic, which is the same as the value of the __topic__ field. No default value is provided.

_tags

string

The tag metadata, which is the same as the value of the __tag__:xxx:yyy field. No default value is provided. You can use the LogProducerConfiguration.addTag() or AliyunLogDartSdk.addTag() method to add tags.

packetLogBytes

int

The size of each log packet that needs to be sent. Valid values: 1 to 5242880. Unit: bytes. Default value: 1024 * 1024.

packetLogCount

int

The maximum number of logs in each log packet that needs to be sent. Valid values: 1 to 4096. Default value: 1024.

packetTimeout

int

The timeout period for log packet wait before sending. A log packet is immediately sent upon a timeout. Default value: 3000. Unit: milliseconds.

persistent

boolean

Specifies whether to enable resumable upload. Default value: false. We recommend that you enable resumable upload.

persistentForceFlush

boolean

Specifies whether to enable forceful refresh for each call of the addLog method. Valid values:

true: We recommend that you do not enable forceful refresh because it deteriorates system performance.

false (default): If your business requires high reliability, we recommend that you enable forceful refresh.

persistentFilePath

string

The path to the cache of binary logs when you enable resumable upload. Default value: an empty string.

Important

Make sure that the path exists. Specify different paths for different AliyunLogDartSdk instances.

persistentMaxFileCount

int

The maximum number of persistent files. Default value: 10.

persistentMaxFileSize

int

The maximum size of each persistent file. Default value: 1024 * 1024.

persistentMaxLogCount

int

The maximum number of logs that can be cached. Default value: 64 * 1024.

Error codes

Error code

Description

Solution

invalid

The SDK is destroyed or invalid.

  1. Check whether the SDK is initialized.

  2. Check whether the destroy() method is called.

writeError

A data write error occurred because the write traffic of the project has reached the upper limit.

Adjust the upper limit of write traffic for the project. For more information, see Adjust resource quotas.

dropError

The cache is full.

Modify the maxBufferLimit, persistentMaxLogCount, and persistentMaxFileSize parameters and try again. You can modify the parameters by following the instructions that are provided in the "Configure the parameters in the LogProducerConfiguration class" section of this topic.

sendNetworkError

A network error occurred.

Check the network connection and try again.

sendQuotaError

The write traffic of the project has reached the upper limit.

Adjust the upper limit of write traffic for the project. For more information, see Adjust resource quotas.

sendUnauthorized

The AccessKey is expired or invalid, or the permission policy of the RAM user to which the AccessKey pair belongs is incorrectly configured.

Check the AccessKey pair.

Make sure that the RAM user has the management permissions on Simple Log Service resources. For more information, see Step 2: Grant permissions to the RAM user.

sendServerError

A service error occurred.

Submit a ticket to contact technical support.

sendDiscardError

Data is discarded. In most cases, the error is caused by inconsistency between the device time and server time.

The SDK automatically re-sends the data.

sendTimeError

The device time is not synchronized with the server time.

The SDK automatically fixes the error.

sendExitBuffered

When the SDK is destroyed, the cached data has not been sent.

We recommend that you enable resumable upload to prevent data loss.

parametersInvalid

A parameter error occurred in SDK initialization.

Check the settings of parameters such as AccessKey, Endpoint, Project, and Logstore.

persistentError

Cached data failed to be written to the system disk.

  1. Check whether the cache file path is correctly configured.

  2. Check whether the cache file is full.

  3. Check whether the system disk space is sufficient.

unknown

An unknown error occurred.

Try again later. If the error persists, submit a ticket to contact technical support.