This topic describes how to get started with 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

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

Sample code

  • Write Node.js code to collect logs
    In this example, the SLSQuickStart.js file 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({
        accessKeyId: "11****ut",                         // The AccessKey ID of your Alibaba Cloud account. For more information, see AccessKey pair. An Alibaba Cloud account has permissions to call all API operations. If you use the AccessKey pair of an Alibaba Cloud account, security risks may occur. We recommend that you create and use a RAM user to call API operations or perform routine O&M.  
        secretAccessKey: "TS****7Y",                     // The AccessKey secret of your Alibaba Cloud account.  
        endpoint: 'http://cn-hangzhou.log.aliyuncs.com', // The Log Service endpoint. For more information, see Endpoints. In this example, the Log Service endpoint for the China (Hangzhou) region is used. Replace the parameter value with the actual endpoint. 
        apiVersion: '2015-06-01'                         // The version of the SDK. The value is fixed as 2015-06-01. 
      })
    
    const projectName = "you_project_name"               // Required. The name of the project. 
    const logstoreName= "your_logstore_name"             // Required. The description of the project. 
    
    // 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,               
          ttl: 3,                                   // Required. The data retention period. Unit: days. If you set ttl to 3650, data is permanently stored. 
          shardCount: 2                             // Required. The number of shards. 
        }
      }
    
      sls.createLogstore(param, function (err, data) {
        if (err) {
          console.log(err)
        } else {
          console.log('The Logstore is created', data)
        }
      })
    }
    // Create indexes for a 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' },
                null
              ]
            }
          ],
          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 = {
        projectName,                                  // Required. The name of the project. 
        logStoreName: logstoreName,                   // Required. The name of the Logstore. 
        from,                                         // Required. The start time. The value of this parameter is accurate to the second. 
        to,                                           // Required. The end time. The value of this parameter is accurate to the second.
        topic: "",                                    // Optional. The topic of logs. 
        query: ""                                     // Optional. The keyword that is used to query logs. If you leave this parameter empty, all logs are queried. 
      }
    
      sls.getLogs(param, function (err, data) {
        if(err) {
          console.error('error:', err)
        } else{
          console.log('The last hour of logs 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: {…}}
    The last hour of logs are queried {request_id: '6125F34214C3A33B68052D5C', headers: {…}, body: {…}}

    For more information about sample code, see aliyun-sdk-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.