After creating a Log Service (SLS) trigger, you can write the code of a function. This topic describes how to write a function in the Function Compute console to implement the following feature: The function is triggered when SLS collects an incremental log. Then, Function Compute collects the corresponding log and prints the collected log.

Prerequisites

Create a trigger

Write function code in Python

  1. Log on to the Function Compute console.
  2. In the top navigation bar, select a region.
  3. In the left-side navigation pane, click Service/Function.
  4. Find the target function in the target service and click the name of the function.
  5. Click the Code tab and write code in the code editor.
    This topic uses the code for a Python function as an example. The following sample code can be used as a template to extract most logical logs. You can specify accessKeyId and accessKey in the code or obtain them from context and creds.
    # -*- coding: utf-8 -*-
    import logging
    import json
    from aliyun.log import LogClient
    from time import time
    
    def logClient(endpoint, creds):
      logger = logging.getLogger()
      logger.info('creds info')
      logger.info(creds.access_key_id)
      logger.info(creds.access_key_secret)
      logger.info(creds.security_token)
      accessKeyId = 'your accessKeyId'
      accessKey = 'your accessKeyId scr'
      client = LogClient(endpoint, accessKeyId, accessKey)
      return client
    
    def handler(event, context):
      logger = logging.getLogger()
      logger.info('start deal SLS data')
      logger.info(event.decode().encode())
      info_arr = json.loads(event.decode())
      fetchdata(info_arr['source'],context)
      return 'hello world'
    
     def fetchdata(event,context):
      logger = logging.getLogger()
      endpoint = event['endpoint']
      creds = context.credentials
      client = logClient(endpoint, creds)
      if client == None :
          logger.info("client creat failed")
          return False
      project = event['projectName']
      logstore = event['logstoreName']
      start_cursor = event['beginCursor']
      end_cursor = event['endCursor']
      loggroup_count = 10
      shard_id = event['shardId']
      while True:
          res = client.pull_logs(project, logstore, shard_id, start_cursor, loggroup_count, end_cursor)
          res.log_print()
          next_cursor = res.get_next_cursor()
          if next_cursor == start_cursor :
              break
          start_cursor = next_cursor
    
        #log_data =  res.get_loggroup_json_list()
      return True                        

Event format

In Function Compute, event is an input parameter. The specific format of event is as follows:

{
    "parameter": {},
    "source": {
        "endpoint": "http://cn-shanghai-intranet.log.aliyuncs.com",
        "projectName": "log-com",
        "logstoreName": "log-en",
        "shardId": 0,
        "beginCursor": "MTUyOTQ4MDIwOTY1NTk3ODQ2Mw==",
        "endCursor": "MTUyOTQ4MDIwOTY1NTk3ODQ2NA=="
    },
    "jobName": "1f7043ced683de1a4e3d8d70b5a412843d817a39",
    "taskId": "c2691505-38da-4d1b-998a-f1d4bb8c9994",
    "cursorTime": 1529486425
}                       
Parameter Description
parameter The function configuration that you specify when configuring the trigger.
source The log block information that you want the function to read from SLS.
  • endpoint: the Alibaba Cloud region where the SLS project is located.
  • projectName: the name of the SLS project.
  • logstoreName: the name of the Logstore that stores the log block information.
  • shardId: the ID of a specified shard in the Logstore.
  • beginCursor: the location from which the function starts to consume data.
  • endCursor: the location from which the function stops consuming data.
jobName The name of an extract, transform, and load (ETL) job in SLS. The SLS trigger configured for the function corresponds to an SLS ETL job.
taskId For an ETL job, taskId is the identifier of a deterministic function call.
cursorTime The unix_timestamp indicating when SLS receives the last log.

What to do next

Debug a function