

# 检索使用已弃用运行时的 Lambda 函数的相关数据
<a name="runtimes-list-deprecated"></a>

Lambda 运行时即将弃用时，Lambda 会通过电子邮件予以提醒，并在 Amazon Health Dashboard 和 Trusted Advisor 中提供通知。这些电子邮件和通知将列出使用运行时的函数的 $LATEST 版本。要列出所有使用特定运行时的函数版本，可以利用 Amazon Command Line Interface（Amazon CLI）或一种 Amazon SDK。

如果有大量函数使用即将弃用的运行时，还可以借助 Amazon CLI 或 Amazon SDK 来确定优先更新最常调用函数的顺序。

有关如何使用 Amazon CLI 和 Amazon SDK 收集使用特定运行时的函数的相关数据，请参阅以下各节的内容。

## 列出使用特定运行时的函数版本
<a name="runtimes-list-deprecated-versions"></a>

要使用 Amazon CLI 列出使用特定运行时的所有函数版本，请运行以下命令。将 `RUNTIME_IDENTIFIER` 替换为要弃用的运行时系统名称，然后选择自己的 Amazon Web Services 区域 名称。要仅列出 $LATEST 函数版本，请在命令中省略 `--function-version ALL`。

```
aws lambda list-functions --function-version ALL --region {{us-east-1}} --output text --query "Functions[?Runtime=='{{RUNTIME_IDENTIFIER}}'].FunctionArn" 
```

**提示**  
该示例命令列出了特定 Amazon Web Services 账户 在 `us-east-1` 区域中的函数。您需要为您的账户拥有函数的每个区域以及每个 Amazon Web Services 账户 重复此命令。

您还可以使用一种 Amazon SDK 列出使用特定运行时的函数。以下示例代码使用 V3 适用于 JavaScript 的 Amazon SDK 和 适用于 Python (Boto3) 的 Amazon SDK 来返回使用特定运行时的函数的函数 ARN 列表。该示例代码还会返回列出的各函数的 CloudWatch 日志组。您可以使用该日志组来查找该函数的上次调用日期。有关更多信息，请参阅下文的[识别最常用和最近调用的函数](#runtimes-list-deprecated-statistics)小节。

------
#### [ Node.js ]

**Example 用于列出使用特定运行时的函数的 JavaScript 代码**  

```
import { LambdaClient, ListFunctionsCommand } from "@aws-sdk/client-lambda";
const lambdaClient = new LambdaClient();

const command = new ListFunctionsCommand({
    FunctionVersion: "ALL",
    MaxItems: 50
});
const response = await lambdaClient.send(command);

for (const f of response.Functions){
    if (f.Runtime == '{{<your_runtime>}}'){ // Use the runtime id, e.g. 'nodejs24.x' or 'python3.14'
        console.log(f.FunctionArn);
        // get the CloudWatch log group of the function to
        // use later for finding the last invocation date
        console.log(f.LoggingConfig.LogGroup);
    }   
}
// If your account has more functions than the specified
// MaxItems, use the returned pagination token in the 
// next request with the 'Marker' parameter
if ('NextMarker' in response){
    let paginationToken = response.NextMarker;
  }
```

------
#### [ Python ]

**Example 用于列出使用特定运行时的函数的 Python 代码**  

```
import boto3
from botocore.exceptions import ClientError

def list_lambda_functions(target_runtime):

    lambda_client = boto3.client('lambda')
    
    response = lambda_client.list_functions(
        FunctionVersion='ALL',
        MaxItems=50
    )
    if not response['Functions']:
            print("No Lambda functions found")
    else: 
        for function in response['Functions']:   
            if function['PackageType']=='Zip' and function['Runtime'] == target_runtime: 
                print(function['FunctionArn'])
                # Print the CloudWatch log group of the function
                # to use later for finding last invocation date
                print(function['LoggingConfig']['LogGroup'])

    if 'NextMarker' in response:
       pagination_token = response['NextMarker']

if __name__ == "__main__":
    # Replace python3.12 with the appropriate runtime ID for your Lambda functions
    list_lambda_functions('{{python3.12}}')
```

------

要了解有关使用 Amazon SDK 通过 [ListFunctions](https://docs.amazonaws.cn/lambda/latest/api/API_ListFunctions.html) 操作列出函数的更多信息，请参阅您首选编程语言的 [SDK 文档](https://www.amazonaws.cn/developer/tools/)。

您还可以使用 Amazon Config 高级查询功能列出使用受影响运行时系统的所有函数。此查询仅返回函数的 $LATEST 版本，但您可以使用单个命令聚合查询以列出所有区域和多个 Amazon Web Services 账户 中的函数。要了解更多信息，请参阅《Amazon Config 开发人员指南》中的[查询 Amazon Auto Scaling 资源的当前配置状态](https://docs.amazonaws.cn/config/latest/developerguide/querying-AWS-resources.html)。**

## 识别最常用和最近调用的函数
<a name="runtimes-list-deprecated-statistics"></a>

如果 Amazon Web Services 账户 包含的函数使用即将弃用的运行时，则可能需要优先更新经常调用的函数或最近调用的函数。

如果只有几个函数，则可以使用 CloudWatch Logs 控制台通过查看函数的日志流来收集这些信息。有关更多信息，请参阅 [View log data sent to CloudWatch Logs](https://docs.amazonaws.cn/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#ViewingLogData)。

要查看最近调用函数的次数，您还可以利用 Lambda 控制台中显示的 CloudWatch 指标信息。要查看此信息，请执行以下操作：

1. 打开 Lamba 控制台的[函数](https://console.amazonaws.cn/lambda/home#/functions)页面。

1. 选择您想要查看调用统计信息的函数。

1. 选择**监控**选项卡。

1. 使用日期范围选择器设置要查看统计数据的时间段。最近调用显示在**调用**窗格中。

对于有大量函数的账户，借助 Amazon CLI 或一种 Amazon SDK，通过 [DescribeLogStreams](https://docs.amazonaws.cn/AmazonCloudWatchLogs/latest/APIReference/API_DescribeLogStreams.html) 和 [GetMetricStatistics](https://docs.amazonaws.cn/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html) API 操作以编程方式收集这些数据可能更高效。

以下示例提供了使用 V3 适用于 JavaScript 的 Amazon SDK 和 适用于 Python (Boto3) 的 Amazon SDK 的代码片段，用于识别特定函数的上次调用日期，并确定过去 14 天内特定函数的调用次数。

------
#### [ Node.js ]

**Example 用于查找函数上次调用时间的 JavaScript 代码**  

```
import { CloudWatchLogsClient, DescribeLogStreamsCommand } from "@aws-sdk/client-cloudwatch-logs";
const cloudWatchLogsClient = new CloudWatchLogsClient();
const command = new DescribeLogStreamsCommand({
    logGroupName: '{{<your_log_group_name>}}',
    orderBy: 'LastEventTime',
    descending: true,
    limit: 1
});
try {
    const response = await cloudWatchLogsClient.send(command);
    const lastEventTimestamp = response.logStreams.length > 0 ? 
        response.logStreams[0].lastEventTimestamp : null;
    // Convert the UNIX timestamp to a human-readable format for display
    const date = new Date(lastEventTimestamp).toLocaleDateString();
    const time = new Date(lastEventTimestamp).toLocaleTimeString();
    console.log(`${date} ${time}`);
    
} catch (e){
    console.error('Log group not found.')
}
```

------
#### [ Python ]

**Example 用于查找函数上次调用时间的 Python 代码**  

```
import boto3
from datetime import datetime

cloudwatch_logs_client  = boto3.client('logs')

response = cloudwatch_logs_client.describe_log_streams(
    logGroupName='{{<your_log_group_name>}}',
    orderBy='LastEventTime',
    descending=True,
    limit=1
)

try:
    if len(response['logStreams']) > 0:
        last_event_timestamp = response['logStreams'][0]['lastEventTimestamp']
        print(datetime.fromtimestamp(last_event_timestamp/1000)) # Convert timestamp from ms to seconds
    else:
        last_event_timestamp = None
except:
    print('Log group not found')
```

------

**提示**  
您可以使用 [ListFunctions](https://docs.amazonaws.cn/lambda/latest/api/API_ListFunctions.html) API 操作来查找函数的日志组名称。有关如何执行此操作的示例，请参阅[列出使用特定运行时的函数版本](#runtimes-list-deprecated-versions)中的代码。

------
#### [ Node.js ]

**Example 用于查找过去 14 天内调用次数的 JavaScript 代码**  

```
import { CloudWatchClient, GetMetricStatisticsCommand } from "@aws-sdk/client-cloudwatch";
const cloudWatchClient = new CloudWatchClient();
const command = new GetMetricStatisticsCommand({
    Namespace: 'AWS/Lambda',
    MetricName: 'Invocations',
    StartTime: new Date(Date.now()-86400*1000*14), // 14 days ago
    EndTime: new Date(Date.now()),
    Period: 86400 * 14, // 14 days.
    Statistics: ['Sum'],
    Dimensions: [{
        Name: 'FunctionName',
        Value: '{{<your_function_name>}}'
    }]
});
const response = await cloudWatchClient.send(command);
const invokesInLast14Days = response.Datapoints.length > 0 ? 
    response.Datapoints[0].Sum : 0;

console.log('Number of invocations: ' + invokesInLast14Days);
```

------
#### [ Python ]

**Example 用于查找过去 14 天内调用次数的 Python 代码**  

```
import boto3
from datetime import datetime, timedelta

cloudwatch_client = boto3.client('cloudwatch')

response = cloudwatch_client.get_metric_statistics(
    Namespace='AWS/Lambda',
    MetricName='Invocations',
    Dimensions=[
        {
            'Name': 'FunctionName',
            'Value': '{{<your_function_name>}}'
        },
    ],
    StartTime=datetime.now() - timedelta(days=14),
    EndTime=datetime.now(),
    Period=86400 * 14, # 14 days
    Statistics=[
        'Sum'
    ]
)

if len(response['Datapoints']) > 0:
    invokes_in_last_14_days = int(response['Datapoints'][0]['Sum'])
else:
    invokes_in_last_14_days = 0

print(f'Number of invocations: {invokes_in_last_14_days}')
```

------