The STS plug-in of web tracking SDK for JavaScript uses Alibaba Cloud Security Token Service (STS) temporary credentials to upload logs without enabling the web tracking feature for the Logstore, which helps prevent dirty data.
Background information
Without STS temporary authorization, you must enable the web tracking feature for the Logstore, which allows anonymous writes from browsers and may generate dirty data. The following steps describe how the STS plug-in uploads logs:
A browser requests a temporary identity credential (STS token) from a business server.
The service server requests an STS token from the STS service.
An AccessKey pair of the Resource Access Management (RAM) user is configured in the server and the RAM user is attached the AliyunSTSAssumeRoleAccess policy.
The server uses the AccessKey pair of the RAM user to call the AssumeRole operation of STS to obtain the STS token of the RAM role. You can use the
Policyparameter of AssumeRole to restrict the permissions of different STS tokens based on the user or device.
STS returns an STS token to the business server.
The service server returns an STS token to the browser.
The browser uses the obtained STS token to assume the RAM role and uploads logs collected from the browser to the Logstore.
Simple Log Service returns a response to the browser after the log is uploaded.
Prerequisites
The RAM user is created and the AliyunSTSAssumeRoleAccess policy is attached to the RAM user. For more information, see Create a RAM user.
For more information about how to configure the AccessKey pair of the RAM user in environment variables of the business server, see Configure environment variables on Linux, macOS, and Windows.
You have created a RAM role for a trusted Alibaba Cloud account and granted the RAM role the permission to write data to the specified project. For more information, see Create a RAM role for a trusted Alibaba Cloud account and RAM custom policy examples.
{ "Version": "1", "Statement": [ { "Action": [ "log:Post*" ], "Resource": "acs:log:*:*:project/<The name of the specified project.>/*", "Effect": "Allow" } ] }
Step 1: Install and configure the SDK
The npm method is used in this topic to install the web tracking SDK for JavaScript to collect website logs. If you want to use the Alibaba Cloud CDN method, see WebTracking JavaScript SDK.
Install Node.js.
Run the following command on the business server to install dependencies.
npm install --save @aliyun-sls/web-track-browser npm install --save @aliyun-sls/web-sts-pluginAdd the following code to your program to configure the SDK.
import SlsTracker from '@aliyun-sls/web-track-browser' import createStsPlugin from '@aliyun-sls/web-sts-plugin' const opts = { host: '${host}', // The Simple Log Service endpoint for the region. Example: cn-hangzhou.log.aliyuncs.com. project: '${project}', // The name of the project. logstore: '${logstore}', // The name of the Logstore. time: 10, // The interval at which logs are sent. Default value: 10. Unit: seconds. count: 10, // The maximum number of logs that can be sent in each request. Default value: 10. topic: 'topic',// The custom topic of logs. source: 'source', tags: { tags: 'tags', }, } const stsOpt = { accessKeyId: '', accessKeySecret: '', securityToken: '', // The following is a simple example of an STS token refresh function. refreshSTSToken: () => new Promise((resolve, reject) => { const xhr = new window.XMLHttpRequest() xhr.open('GET', 'localhost:7000/test/sts', true) xhr.send() xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { let credential = JSON.parse(xhr.response) // The purpose of the function is to configure the temporary key and token of stsOpt. stsOpt.accessKeyId = credential.AccessKeyId stsOpt.accessKeySecret = credential.AccessKeySecret stsOpt.securityToken = credential.SecurityToken resolve() } else { reject('Wrong status code.') } } } }), // refreshSTSTokenInterval: 300000, // stsTokenFreshTime: undefined, } // Create a tracker. const tracker = new SlsTracker(opts) // Create the STS plug-in. const stsPlugin = createStsPlugin(stsOpt) // Use the STS plug-in. tracker.useStsPlugin(stsPlugin) // Assume that you want to upload a single log. tracker.send({ eventType:'view_product', productName: 'Tablet', price: 500 })The following table describes the web tracking parameters.
Parameter
Required
Description
host
Yes
The endpoint of the region where Simple Log Service resides. In this example, the Simple Log Service endpoint for the China (Hangzhou) region is used. Replace the parameter value with the actual endpoint. For more information, see Endpoints.
project
Yes
The name of the project.
logstore
Yes
The name of the Logstore.
time
No
The interval at which logs are sent. Default value: 10. Unit: seconds.
count
No
The maximum number of logs that can be sent in each request. Default value: 10.
topic
No
The topic of logs. Specify a custom value to identify logs.
source
No
The source of logs. Specify a custom value to identify logs.
tags
No
Custom tags to identify logs.
The following table describes the STS parameters.
Parameter
Required
Description
accessKeyId
accessKeySecret
securityToken
Yes
The business server uses the AccessKey pair of the RAM user to call the AssumeRole operation. The response parameters include
AccessKeySecret,AccessKeyId, andSecurityToken.In the input parameters of the AssumeRole operation,
DurationSecondsspecifies the validity period of the token andPolicyspecifies the permission scope of the token.
refreshSTSToken
Yes
A function that periodically obtains new STS tokens to update the credential fields. Supports Promise and async functions.
refreshSTSTokenInterval
No
The interval at which tokens are refreshed, in milliseconds. Default value: 300,000 (5 minutes).
stsTokenFreshTime
No
The timestamp of the most recent token acquisition. You do not need to set this parameter.
Step 2: Upload logs
When you upload a single log, the log is uploaded as a separate object. When you upload multiple logs, the logs are uploaded as an array that contains multiple objects.
Upload a single log. The type is
object. Example:tracker.send({ eventType:'view_product', productName: 'Tablet', price: 500 })Immediately upload a single log. The time and count parameters do not take effect. The type is
object. Example:tracker.sendImmediate({ eventType:'view_product', productName: 'Tablet', price: 500 })Upload multiple logs at a time. The type is
array. Example:tracker.sendBatchLogs([ { eventType: 'view_product', productName: 'Tablet', price: 500 }, { eventType: 'view_product', productName: 'Laptop', price: 1200 } ])Immediately upload multiple logs at a time. The time and count parameters do not take effect. The type is
array. Example:tracker.sendBatchLogsImmediate([ { eventType:'view_product', productName: 'Tablet', price: 500 }, { eventType:'view_product', productName: 'Laptop', price: 1200 } ])
Step 3: View the upload result
You can view the upload result by using the console or calling API operations.
console:
Log on to the Simple Log Service console.
In the Projects section, click the project you want.
On the tab, click the logstore you want. Then click Consumption Preview to view the logs.
API:
Call the CreateIndexoperation to create full-text indexes or field indexes. If you want to use the SELECT statement, you must create field indexes.
Call the GetLogsV2operation to query logs in a logstore. The returned result is an array of logs. Each element in the array is a log.
References
This topic uses the web tracking SDK for JavaScript to collect website logs. For more information about how to use web tracking SDK for JavaScript to collect mini program logs, see WebTracking JavaScript SDK for mini programs.
FAQ
The SDK starts without errors, but when sending logs, it reports the TypeError: Cannot read properties of undefined (reading 'sigBytes'). What do I do if this issue occurs?
Possible cause: a CryptoJS encryption issue. Because the third-party package is difficult to modify, we recommend using web tracking for unauthenticated writes. For more information, see Collect client-side logs with WebTracking.