This topic describes some basic information about coding in Function Compute, including handlers, instance lifecycle hooks, log records, and error handling.

Handler

When you create a function, you must specify a handler for the function. The Function Compute runtime loads and invokes the handler to process requests. Handlers are classified into the following types:
  • Event handler

    Processes event requests that are triggered by event sources except HTTP triggers.

  • HTTP handler

    Processes the requests that are triggered by HTTP triggers. For more information, see Configure and use an HTTP trigger.

You can configure the handler for a function by using the Request Handler parameter in the Function Compute console. For more information, see Update a function.

Lifecycle hooks for function instances

On-demand function instances are dynamically created. The on-demand instances are frozen when they are idle and destroyed after they are not used for a period of time. The instance lifecycle hooks are invoked when the states of instances change. The following lifecycle hooks can be configured in Function Compute: Initializer hooks, PreFreeze hooks, and PreStop hooks. For more information, see Function instance lifecycle.

Initializer hook

An Initializer hook is invoked after the function instance is started and before the handler runs. Function Compute ensures that the Initializer hook is successfully invoked only once within the lifecycle of a function instance. For example, if the Initializer hook fails to be invoked, the system retries the Initializer hook until the Initializer hook is successfully invoked, and then runs your handler. In database-related scenarios, you can add time-consuming service logic to the Initializer hook, such as the service logic to create connection pools and load function dependency libraries. This prevents the repeated execution of the service logic each time the function is invoked and reduces the latency of the function.

PreFreeze hook

A PreFreeze hook is executed before a function instance is frozen. You can use the PreFreeze hook to perform specified operations before the instance is frozen. For example, you can configure a PreFreeze hook to make sure that metrics are sent before an instance is frozen.

PreStop hook

A PreStop hook is executed before a function instance is destroyed. You can use the PreStop hook to perform specified operations before an instance is destroyed. For example, you can configure a PreStop hook to make sure that database connections are closed and states are reported and updated before an instance is destroyed.

Log record

Note
  • After you configure a Logstore for a service, Function Compute stores the function logs in the Logstore. For more information, see Configure the logging feature.
  • By default, Function Compute configures a Logstore for you when you create a service in the console.

Function Compute is integrated with log records. Function Compute stores all function invocation records and the logs printed in the function code in Logstores. You can record function logs by executing the logging statements provided by Function Compute. This helps you debug the function and troubleshoot issues. The following table describes the log printing statements for different programming languages.

Programming language Built-in log printing statement of the programming language Function Compute logging statement References
Node.js console.log() context.logger.info() 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() Log printing
C# Console.WriteLine("") context.Logger.LogInformation() Print logs

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

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

# Log printed by using the logging statements provided by Function Compute
# logger.info('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 version, alias, and code logs.

The following example shows the data structure of a function execution log:

__source__:  
__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
versionId:         
  • When the execution of a function starts, the system prints FC Invoke Start RequestId: f84a9f4f-2dfb-41b0-9d6c-1682a2f3a650, which indicates that function execution starts.
  • When the execution of a function is complete, the system prints FC Invoke End RequestId: f84a9f4f-2dfb-41b0-9d6c-1682a2f3a650, which indicates that function execution ends.

Error handling

Errors in Function Compute are classified into two types: HandledInvocationError and UnhandledInvocationError.

  • HandledInvocationError

    Only the errors returned by the callback parameter in Node.js are of the HandledInvocationError type. The 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');
      }          

    The following example shows a response that contains the error information:

    null          
  • UnhandledInvocationError

    The errors that are not returned by the callback parameter are of the UnhandledInvocationError type.

    The stack trace of an UnhandledInvocationError error is printed in logs. You can view the logs to find the stack trace based on the context.