Basic information

更新时间:
复制 MD 格式

Function Compute handles code execution through a set of core runtime concepts: handlers, lifecycle hooks, logging, and error handling. This page explains how each works so you can write and debug functions effectively.

Handlers

Every function requires a handler — the entry point that the Function Compute runtime loads and calls to process requests. Set the handler using the Handler parameter in the Function Compute console. For setup details, see Create a function.

Function Compute supports two handler types:

  • Event handler: processes requests from event sources such as Object Storage Service (OSS), Simple Log Service, and ApsaraMQ for RocketMQ — anything except HTTP triggers.

  • HTTP handler: processes HTTP requests directly. See Configure and use an HTTP trigger for details.

Best practices for handlers

Keep initialization code outside the handler function body. SDK clients, database connections, and loaded dependencies initialized at instance startup are reused across invocations — reducing per-call latency and cost. The Initializer hook (described below) is the recommended place for this work.

Do not store user data or security-sensitive state in global variables. Function Compute may reuse an instance across multiple invocations, and global state persists between calls.

Lifecycle hooks for function instances

In on-demand mode, Function Compute automatically creates instances as requests arrive. When idle, instances are frozen and eventually destroyed after a period of inactivity.

The instance lifecycle follows this sequence:

Created → Initialized (Initializer) → Running → PreFreeze → Frozen → PreStop → Destroyed

Lifecycle hooks let you run code at key transitions in this cycle. Function Compute provides three hooks: Initializer, PreFreeze, and PreStop. For the complete lifecycle model, see Function instance lifecycle.

Initializer hook

The Initializer hook runs after instance initialization, before the handler processes any request. It runs exactly once per instance lifetime.

If the hook fails, the current instance is destroyed and a new one is created to retry.

Use the Initializer hook for setup work that's expensive to repeat on every invocation: creating connection pools, loading dependencies, or running database initialization tasks. Offloading this work to initialization reduces per-call latency.

PreFreeze hook

The PreFreeze hook runs just before an instance is frozen. Use it to complete any in-flight operations before the instance becomes inactive — for example, ensuring that metrics are flushed before the freeze.

PreStop hook

The PreStop hook runs just before an instance is destroyed. Use it to clean up gracefully — for example, closing database connections or reporting final status before the instance exits.

Log management

Note

You must configure a service-level Logstore before function logs can be stored. See Configure logging for setup instructions. If you enable logging when creating a service in the Function Compute console, a Logstore is set up automatically.

Function Compute integrates with Simple Log Service to store both invocation logs and logs printed from your function code.

Both the language's built-in print statement and the FC-provided logging statement write to the Logstore. The difference is that FC logging statements tag each entry with a request ID, making log filtering and correlation across invocations straightforward.

Programming languageBuilt-in statementFC logging statementReferences
Node.jsconsole.log()context.logger.info()Print logs
Pythonprint()logging.getLogger().info()Print logs
JavaSystem.out.println()context.getLogger().info()Print logs
PHPecho "" . PHP_EOL$GLOBALS['fcLogger']->info()Log printing
C#Console.WriteLine("")context.Logger.LogInformation()Error handling

The output format differs between the two approaches. A plain print() produces a bare message; the FC logging statement includes a timestamp, request ID, and log level:

# Built-in print statement
# print('hello world')
message:  hello world

# FC logging statement
# logger.info('hello world')
message:  2020-03-13T04:06:49.099Z f84a9f4f-2dfb-41b0-9d6c-1682a2f3a650 [INFO] hello world

Use the FC logging statement when you need to correlate log output across multiple invocations or filter logs by request ID.

Log structure

Each function execution log entry contains the service name, function name, version, alias, and message content. The full structure looks like this:

__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:

Field descriptions:

FieldDescription
__source__The origin of the log entry
__tag__:__receive_time__Unix timestamp when the log was received by Simple Log Service
__topic__Maps to the service name
functionNameThe function that generated the log
serviceNameThe service that the function belongs to
qualifierThe version alias used for this invocation (for example, LATEST)
versionIdThe numeric version ID, if applicable
messageThe log content, including timestamp, request ID, log level, and text

In addition to code logs, Function Compute automatically writes two system log lines per invocation:

  • FC Invoke Start RequestId: <id> — printed when execution begins

  • FC Invoke End RequestId: <id> — printed when execution completes

Use these boundary markers to identify all log output for a single request: filter by request ID to see every line logged during that invocation.

Error handling

Function Compute classifies invocation errors into two types.

HandledInvocationError

This type applies only to errors explicitly returned via the callback parameter in Node.js. The error information is included in the response body.

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

Example error response:

{"errorMessage":"this is error"}

UnhandledInvocationError

All other errors — runtime exceptions, timeouts, out-of-memory errors — are classified as UnhandledInvocationError. The stackTrace for these errors is printed in the function logs. Use the request ID to find the relevant log entries and locate the stack trace.

To diagnose an UnhandledInvocationError:

  1. Locate the FC Invoke Start RequestId line in your logs for the failed invocation.

  2. Filter all log entries by that request ID.

  3. Find the stackTrace output to identify the root cause.

Operating system environment

Function Compute runs on Debian 9 LTS. Only the x86_64 architecture is supported.

Customize the environment using layers or environment variables. For example, function instances run in UTC by default. To switch to UTC+8, set the TZ environment variable to Asia/Shanghai.

For more information, see Manage layers. For available variables and their effects, see Environment variables.