

# 非推奨のランタイムを使用する Lambda 関数に関するデータを取得する
<a name="runtimes-list-deprecated"></a>

Lambda ランタイムが非推奨に近づくと、Lambda は E メールでアラートを送信し、 Health Dashboard と Trusted Advisor で通知を提供します。これらの E メールと通知には、 ランタイムを使用する関数の \$1LATEST バージョンが一覧で記載されます。特定のランタイムを使用するすべての関数バージョンを一覧にするには、 AWS Command Line Interface (AWS CLI) またはいずれかの AWS SDK を使用できます。

非推奨になるランタイムを使用している関が多数ある場合は、 AWS CLIまたは AWS SDK を使用して、最も頻繁に使用される関数の更新を優先することもできます。

AWS CLI および AWS SDK を使用して、特定のランタイムを使用する関数に関するデータを収集する方法については、以下のセクションを参照してください。

## 特定のランタイムを使用する関数バージョンの一覧表示
<a name="runtimes-list-deprecated-versions"></a>

AWS CLI を使用して、特定のランタイムを使用するすべての関数バージョンを一覧表示するには、次のコマンドを実行します。`RUNTIME_IDENTIFIER` を廃止予定のランタイムの名前に置き換えて、お使いの AWS リージョン を選択してください。関数の \$1LATEST バージョンだけを一覧表示するには、`--function-version ALL` をコマンドから省略します。

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

**ヒント**  
コマンド例では、特定の AWS アカウント の `us-east-1` リージョン内の関数を一覧表示します。このコマンドを、アカウントが機能している各リージョンと各 AWS アカウント で繰り返す必要があります。

AWS SDK のいずれかを使用して、特定のランタイムを使用する関数を一覧表示することもできます。次のサンプルコードでは、V3 AWS SDK for JavaScript と AWS SDK for Python (Boto3) を使用して、特定のランタイムを使用する関数として関数 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')
```

------

AWS SDK で [ListFunctions](https://docs.aws.amazon.com/lambda/latest/api/API_ListFunctions.html) アクションを使用して関数をリストする方法の詳細については、目的のプログラミング言語の [SDK ドキュメント](https://aws.amazon.com/developer/tools/)を参照してください。

AWS Config の高度なクエリ機能を使用して、影響を受けるランタイムを使用するすべての関数を一覧表示することもできます。このクエリは関数の \$1LATEST バージョンのみを返しますが、1 つのコマンドでクエリを集約して、すべてのリージョンの複数の AWS アカウント にある関数を一覧表示できます。詳細については、「*AWS Config デベロッパーガイド*」の「[Querying the Current Configuration State of AWS Auto Scaling Resources](https://docs.aws.amazon.com/config/latest/developerguide/querying-AWS-resources.html)」を参照してください。

## 最も頻繁に使用される関数と、最近呼び出された関数の特定
<a name="runtimes-list-deprecated-statistics"></a>

AWS アカウント に、非推奨になる予定のランタイムを使用する関数が含まれている場合は、頻繁に呼び出される関数や最近呼び出された関数の更新を優先できます。

関数が少ない場合は、CloudWatch Logs コンソールを使用して関数のログストリームを確認することで、この情報を収集できます。詳細については、「[CloudWatch Logs に送信されたログデータを表示する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#ViewingLogData)」を参照してください。

最近の関数呼び出し数を確認するには、Lambda コンソールに表示される CloudWatch メトリクス情報を使用することもできます。この情報を表示するには、次の手順を実行します。

1. Lambda コンソールの [[関数]](https://console.aws.amazon.com/lambda/home#/functions) ページを開きます。

1. 呼び出し統計を表示する関数を選択します。

1. [**Monitor**] (モニタリング) タブを選択します。

1. 日付範囲ピッカーを使用して、統計を表示する期間を設定します。最近の呼び出しは、**[呼び出し]** ペインに表示されます。

多くの関数を持つアカウントの場合は、AWS CLI または AWS SDK のいずれかを使用して、[DescribeLogStreams](https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeLogStreams.html) および [GetMetricStatistics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html) API アクションを使用してプログラムでこのデータを収集する方が効率的です。

次の例では、V3 AWS SDK for JavaScript と AWS SDK for Python (Boto3) を使用して、特定の関数の最後の呼び出し日を確認し、過去 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.aws.amazon.com/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}')
```

------