All Products
Search
Document Center

Simple Log Service:Get started with Simple Log Service SDK for Node.js

Last Updated:Oct 26, 2023

This topic describes how to get started with Simple Log Service SDK for Node.js and perform common operations. For example, you can create a project, create a Logstore, write logs, and query logs.

Prerequisites

  • A Resource Access Management (RAM) user is created, and the required permissions are granted to the RAM user. For more information, see Create a RAM user and grant permissions to the RAM user.

  • The ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured. For more information, see Configure environment variables.

    Important
    • The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use the AccessKey pair of a RAM user to call API operations or perform routine O&M.

    • We recommend that you do not save the AccessKey ID or AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and the security of all resources within your account may be compromised.

  • Simple Log Service SDK for Node.js is installed. For more information, see Install Simple Log Service SDK for Node.js.

Sample code

  • Write Node.js code to collect logs

    In this example, a file named SLSQuickStart.js is created. The sample code in this file provides an example on how to call API operations to create a project, create a Logstore, create indexes, write logs, and query logs. Example:

    const ALY = require('aliyun-sdk')
    var sls = new ALY.SLS({
        // In this example, the AccessKey ID and AccessKey secret are obtained from environment variables. 
        "accessKeyId": process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,                  
        "secretAccessKey": process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,         
        // The Simple Log Service endpoint. In this example, the Simple Log Service endpoint for the China (Hangzhou) region is used. Replace the parameter value with the actual endpoint.  
        endpoint: 'http://cn-hangzhou.log.aliyuncs.com', 
        // The version of the SDK. The value is fixed. 
        apiVersion: '2015-06-01'                         
      })
    // Required. The name of the project. 
    const projectName = "you_project_name"
    // Required. The name of the Logstore. 
    const logstoreName= "your_logstore_name"             
    
    // Create a project. 
    function createProject () {
      const param = {
        projectDetail: {
          projectName,                                  
          description: "description about project"      
        }
      }
    
      sls.createProject(param, function(err, data) {
        if (err) {
          console.error('error:', err)
        } else {
          console.log('The project is created', data)
        }
      })
    }
    
    // Create a Logstore. 
    function createLogStore() {
      const param = {
        projectName,                                
        logstoreDetail: {
          logstoreName: logstoreName,               
          // Required. The retention period of data. Unit: days. If you set the ttl parameter to 3650, data is permanently stored. 
          ttl: 3,                                   
          // Required. The number of shards. 
          shardCount: 2                             
        }
      }
    
      sls.createLogstore(param, function (err, data) {
        if (err) {
          console.log(err)
        } else {
          console.log(' The Logstore is created', data)
        }
      })
    }
    // Create indexes for the Logstore. 
    function createIndex () {
      const param = {
        projectName,
        logstoreName,
        indexDetail: {
          line: {
            token: [";"],
            include_keys: ["key2", "key3"],
            caseSensitive:false
          }
        }
      }
    
      sls.createIndex(param, function(err, data) {
        if (err) {
          console.log(err)
        } else {
          console.log('Indexes for the Logstore are created', data)
        }
      })
    }
    // Write logs. 
    function writeLog () {
      const param = {
        projectName,                                  
        logStoreName: logstoreName,                   
        logGroup: { 
        // Required. The logs that you want to write. 
          logs: [
            {
              time:  Math.floor(new Date().getTime() / 1000),
              contents: [
                { key: 'a', value: '1' },
                { key: 'a', value: '2' },
                { key: 'a', value: '3' }
              ]
            }
          ],
          topic: 'vv',
          source: '127.0.0.1'
        }
      }
    
      sls.putLogs(param, function (err, data) {
        if (err) {
          console.error('error:', err)
        } else {
          console.log('Logs are written', data)
        }
      })
    }
    
    // Query logs. 
    function queryLog () {
      // Query logs of the last hour.
      const to = Math.floor(new Date().getTime() / 1000)
      const from = to - 3600
    
      const param = {
        // Required. The name of the project. 
        projectName,     
        // Required. The name of the Logstore. 
        logStoreName: logstoreName,  
        // Required. The start time. The value is accurate to the second. 
        from,   
        // Required. The end time. The value is accurate to the second. 
        to,  
        // Optional. The topic of logs. 
        topic: "",  
        // Optional. The keyword that is used to query logs. If you leave this parameter empty, all logs are queried. 
        query: ""                                    
      }
    
      sls.getLogs(param, function (err, data) {
        if(err) {
          console.error('error:', err)
        } else{
          console.log('Logs of the last hour are queried', data)
        }
      })
    }
    // Call the following functions: 
    createProject()
    
    setTimeout(() => {
      createLogStore()
    }, 10 * 1000)
    
    setTimeout(() => {
      createIndex()
    }, 20 * 1000)
      
    setTimeout(() => {
      writeLog()
    }, 80 * 1000)
      
    setTimeout(() => {
      queryLog()
    }, 90 * 1000)

    Sample output:

    The project is created {request_id: '6125F2E882518E4618E7C316', headers: {…}, body: {…}}
    The Logstore is created {request_id: '6125F2F295D4E2210BE5BD59', headers: {…}, body: {…}}
    Indexes for the Logstore are created {request_id: '6125F2FCE681A8360B6B3365', headers: {…}, body: {…}}
    Logs are written {request_id: '6125F3380EBCCCA1834DBD83', headers: {…}, body: {…}}
    Logs of the last hour are queried {request_id: '6125F34214C3A33B68052D5C', headers: {…}, body: {…}}

    For more information about sample code, see Alibaba Cloud Simple Log Service SDK for Node.js.

  • Use Logtail to collect Node.js logs

    You can use Logtail to collect Node.js logs from the log4js module in Node.js. For more information, see Collect Node.js logs.