This topic describes some common terms of Function Compute, including the function entry point, handler function, function input parameters, log records, and troubleshooting.

Function entry point

When you create a function, you must specify an entry point for the function. Function Compute starts executing a function from its entry point. The entry point of a function in Function Compute is in the format of [File name].[Function name].

For example, when you create a Node.js function with Handler set to index.handler, Function Compute loads the handler function defined in the index.js file.

Handler function

A handler function refers to a function that is specified by a function entry point. The handler function is similar to the main() function in local development. Handler functions must comply with the programming model provided by Function Compute.

A handler function can be an event function or an HTTP function.

  • An event function can be used as a common handler function that provides a segment of service logic code. All handler functions are event functions except those for HTTP functions.
  • An HTTP function is a function that is configured with an HTTP trigger. HTTP functions can directly process HTTP requests and return HTTP responses. They are suitable for creating web applications. The programming model for HTTP functions is different from that for event functions.

The following example shows an event function that runs in a Python runtime:

def handler(event, context):
    return 'hello world'            

In this model, the custom event parameter and the platform-defined context parameter are the input parameters of the handler function. The handler function must parse the parameters and be able to call other functions defined in the code. Except for the definition, the handler function has the same code organization logic as a local function.

For more information about the handler function model for each programming language, see the corresponding programming language.

Initializer function

Function Compute dynamically executes functions on different Docker instances based on requests. When a function is called in succession, the function can be executed on the same Docker instance for multiple times. An initializer function is used to ensure that the same instance is executed successfully only once.

In database-related scenarios, you can add time-consuming service logic to the initializer function, such as the service logic for creating a connection pool and loading function dependency libraries. This prevents such service logic from being repeated each time the function is called, reducing the latency of the function.

Prior to handler functions, initializer functions are executed after Function Compute allocates functions to be executed on different Docker instances. Although HTTP functions and event functions have different programming models, their corresponding initializer functions have the same programming model.

For more information about the initializer function model for each programming language, see the corresponding programming language.

Input parameters of functions

Input parameters of a function are the content passed to the function when the function is called. Input parameters of a function usually consist of the event parameter and the context parameter. However, the number of input parameters may vary with the programming language and environment.

  • event parameter

    The event parameter is a custom input parameter for a function. It is passed to the function in the format of byte streams. The data structure of the event parameter can be customized and can be a simple string, a JSON object, or a picture (which is binary data). Function Compute does not interpret the content of the event parameter. You must convert byte streams to the corresponding data type in the function.

    The value of the event parameter varies according to trigger conditions:

    • If a function is triggered by an event source service, the event source service passes the event to the function as an event parameter in a format predefined by the Function Compute platform. You can write code in this format and obtain information from the event parameter. For example, when you use an Object Storage Service (OSS) trigger, OSS passes the information about the bucket and its files to the event parameter in JSON format.
    • If a function is directly called by using the SDK, you can customize the event parameter between the caller and the function code. The caller passes in data in the defined format and the function code obtains the data in the same format. For example, you can define {"key":"val"}, a data structure in JSON format, as the event parameter. When a caller passes in the data {"key":"val"}, the function code converts byte streams to data in JSON format and then calls event["key"] to obtain the value val.

    The following example describes how to use the event parameter in Python:

    import json
    def handler(event, context):
        evt = json.loads(event)
        return 'success'
  • context parameter

    The context parameter is a function input parameter defined by the Function Compute platform. Designed by Function Compute, the data structure of the context parameter contains the function runtime information. The data structure is described as follows:

    • Function structure
         requestId: '9cda63c3-1ac9-45ba-8a59-2593bb9bc101',  
         credentials: {    
            accessKeyId: 'xxx',    
            accessKeySecret: 'xxx',    
            securityToken: 'xxx'  
         function: {    
            name: 'xxx',    
            handler: 'index.handler',    
            memory: 512,    
            timeout: 60,    
            initializer: 'index.initializer',    
            initializationTimeout: 10  
         service: {    
            name: 'xxx',    
            logProject: 'xxx',    
            logStore: 'xxx',    
            qualifier: 'xxx',    
            versionId: 'xxx'  
         region: 'xxx',  
         accountId: 'xxx'
    • Scenarios
      • Obtain the temporary key information of a user from context.credentials and use the temporary key in context to access other Alibaba Cloud services. In this example, the key is used to access OSS. This avoids the use of hard-coded keys in code.
      • Obtain the basic information of the current execution from context. Such basic information includes requestId, serviceName, functionName, and qualifier.
    • Example

      The following example describes how to use the personal information in context to access OSS in Python:

      import json
      import oss2
      def handler(event, context):    
          creds = context.credentials    
          auth = oss2.StsAuth(creds.access_key_id, creds.access_key_secret, creds.security_token)    
          bucket = oss2.Bucket(auth, 'oss-endpoint', 'your-bucket-name')    
          bucket.put_object('object-name', 'Awesome FC')    
          return 'success'

Log records

Function Compute is integrated with log records. Function Compute stores all function call records and the logs printed in function code into Logstores. You can make a record of function logs by running the logging statements provided by Function Compute. This helps you debug the function and locate problems in the system.

  • You need to configure a Logstore at the service level so that Function Compute sends function logs to the specified Logstore.
  • Function Compute automatically creates and configures a Logstore for functions and services that are created in the Function Compute console.
Programming language Log printing statement in the function code Logging statement provided by Function Compute Reference
Node.js console.log() console.log() Print logs
Python print() logging.getLogger().info() Print logs
Java System.out.println() context.getLogger().info() Print logs
PHP echo "" . PHP_EOL $GLOBALS['fcLogger']->info() Print logs
C# Console.WriteLine("") context.Logger.LogInformation() Print logs

Logs printed by using the built-in log printing statements of programming languages are also collected to Logstores. To facilitate log filtering, each log printed by using the logging statements provided by Function Compute is tagged with a request ID.

# Logs printed by using the built-in log printing statements of programming languages
# print('hello world')
message:  hello world

# Log printed by using the logging statements provided by Function Compute
#'hello world')
message:  2020-03-13T04:06:49.099Z f84a9f4f-2dfb-41b0-9d6c-1682a2f3a650 [INFO] hello world

Log elements

A function execution log contains the service name, function name, the current function version, alias, and code logs.

For example, the data structure of a function execution log is as follows:

__tag__:__receive_time__:  1584072413
__topic__:  myService
functionName:  myFunction
message:  2020-03-13T04:06:49.099Z f84a9f4f-2dfb-41b0-9d6c-1682a2f3a650 [INFO] hello world
qualifier:  LATEST
serviceName:  myService
  • When the execution of a function starts, the system prints FC Invoke Start RequestId: f84a9f4f-2dfb-41b0-9d6c-1682a2f3a650, indicating that function execution starts.
  • When the execution of a function is completed, the system prints FC Invoke End RequestId: f84a9f4f-2dfb-41b0-9d6c-1682a2f3a650, indicating that function execution ends.

Handle errors

Errors in Function Compute are classified into HandledInvocationError and UnhandledInvocationError.

  • HandledInvocationError

    Only the errors returned by callback in Node.js functions are of the HandledInvocationError type. Error information is contained in responses.

    'use strict';
      module.exports.handler = function(event, context, callback) {
        console.log('hello world');
        callback('this is error', 'hello world');

    For example, the following information shows a response that contains error information.

    {"errorMessage":"this is error"}          
  • UnhandledInvocationError

    All function errors are of the UnhandledInvocationError type except those of the HandledInvocationError type.

    The stackTrace property of an UnhandledInvocationError error is printed in logs. You can view the logs to find the corresponding StackTrace based on the context.