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

    An event handler is used to process the event requests triggered by various event sources other than HTTP triggers, such as OSS triggers, Log Service triggers, and Message Queue for Apache RocketMQ triggers.

  • HTTP handler

    An HTTP handler processes the requests that are triggered by HTTP triggers. For more information, see Configure an HTTP trigger that invokes a function with HTTP requests.

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

Lifecycle hooks for function instances

The provisioned instances can be created based on your business requirements. The provisioned instances are frozen when they are idle and destroyed after being frozen for a period of time. You can configure lifecycle hooks for instances to perform callback operations on the instances when the instance status changes. 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 for the first time, 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 for creating connection pools and loading 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 records

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 integrates with Log Service to store all the records of function invocations and the logs printed in the function code to the Logstore. You can use log statements provided by the Function Compute to record function logs to facilitate debugging and problem locating. The following table describes the log printing statements for different programming languages.

Programming language Built-in log printing statement of the programming language Logging statement provided by Function Compute 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() Error handling

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:

    {"errorMessage":"this is error"}               
  • 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.

Operating system environment

Function Compute uses the Debian9 LTS operating system. Only the x86_64 architecture is supported.

You can modify the operating system environment by configuring layers or environment variables. For example, you can configure environment variables to change the time zone. By default, function instances run in the UTC time. If you set the value of the environment variable TZ to Asia/Shanghai, the time zone of Function Compute changes to UTC+8. For more information, see Manage layers and Environment variables.