Node.js SDK快速入门

本文介绍如何快速使用日志服务Node.js SDK完成常见操作,包括创建项目(Project)、创建日志库(Logstore)、写入日志和查询日志等。

前提条件

注意事项

本示例以华东1(杭州)的公网Endpoint为例,其公网Endpointhttps://cn-hangzhou.log.aliyuncs.com。如果您通过与Project同地域的其他阿里云产品访问日志服务,请使用内网Endpointhttps://cn-hangzhou-intranet.log.aliyuncs.com。关于日志服务支持的地域与Endpoint的对应关系,请参见服务入口

示例

  • 直接编写Node.js代码采集日志

    本示例中,创建一个SLSQuickStart.js文件,并调用接口分别完成创建Project、创建Logstore、创建索引、写入日志数据和查询日志数据。以下为示例代码:

    
    const Client = require('@alicloud/log')
    const sls = new Client({
        // 本示例从环境变量中获取AccessKey IDAccessKey Secret。
        accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
        accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
        //日志服务的域名。此处以杭州为例,其它地域请根据实际情况填写。 
        endpoint: 'cn-hangzhou.log.aliyuncs.com'
    })
    // 必选,Project名称。
    const projectName = "aliyun-test-node-project"
    // 必选,Logstore名称。
    const logstoreName = "request_log"
    
    
    async function test() {
        // 创建Project
        await sls.createProject(projectName, {
            description: 'test'
        })
        // 创建Logstore
        await sls.createLogStore(projectName, logstoreName, {
            // 必选,设置数据保存时长,单位为天。如果ttl配置为3650,表示永久保存。
            ttl: 3600,
            // 必选,设置Shard数量。
            shardCount: 2
        })
        // 创建index
        const index = {
            "keys": {
                "request_method": {
                    // 是否大小写敏感  false为大小写不敏感。
                    "caseSensitive": false,
                    // 是否对该字段开启统计分析
                    "doc_value": true,
                    "token": ["\n", "\t", ";", ",", "=", ":"],
                    "type": "text"
                }, "status": {
                    // 是否大小写敏感  false为大小写不敏感。
                    "caseSensitive": false,
                    // 是否对该字段开启统计分析
                    "doc_value": true,
                    "token": ["\n", "\t", ";", ",", "=", ":"],
                    "type": "long"
                }
            },
        }
        await sls.createIndex(projectName, logstoreName, index)
        // 写入日志
        const logGroup = {
            logs: [
              { content: { request_method: 'GET', status: '200' }, timestamp: Math.floor(new Date().getTime() / 1000) },
              { content: { request_method: 'GET', status: '500' }, timestamp: Math.floor(new Date().getTime() / 1000) },
              { content: { request_method: 'GET', status: '200' }, timestamp: Math.floor(new Date().getTime() / 1000) },
              { content: { request_method: 'POST', status: '500'}, timestamp: Math.floor(new Date().getTime() / 1000) }
            ],
            tags: [{ tag1: 'testTag' }],
            topic: 'testTopic',
            source: 'testSource'
          };
          await sls.postLogStoreLogs(projectName, logstoreName, logGroup);
          // 查询日志
          const from = new Date();
          from.setDate(from.getDate() - 1);
          const to = new Date();
          const res = await sls.getLogs(projectName, logstoreName, from, to);
          console.log(res)
    }
    // 运行function。
    test()
    

    返回结果示例如下:

    [
      {
        request_method: 'GET',
        status: '200',
        __topic__: 'testTopic',
        __source__: 'testSource',
        '__tag__:tag1': 'testTag',
        __time__: '1744882259'
      },
      {
        request_method: 'GET',
        status: '500',
        __topic__: 'testTopic',
        __source__: 'testSource',
        '__tag__:tag1': 'testTag',
        __time__: '1744882259'
      },
      {
        request_method: 'GET',
        status: '200',
        __topic__: 'testTopic',
        __source__: 'testSource',
        '__tag__:tag1': 'testTag',
        __time__: '1744882259'
      },
      {
        request_method: 'POST',
        status: '500',
        __topic__: 'testTopic',
        __source__: 'testSource',
        '__tag__:tag1': 'testTag',
        __time__: '1744882259'
      }
    ]

    更多示例代码如下表,方便您参考或直接使用。

    GitHub源码

    说明

    integration.test.js

    创建Project、创建Logstore、创建索引、写入日志、查询日志、查询Logstore、获取日志分布情况等相关示例。

  • 通过Logtail采集Node.js日志

    通过Logtail方式,以采集Node.jslog4js日志为例,采集Node.js日志。更多信息,请参见采集Node.js日志