前回の記事でAPI GatewayとLambdaで動的Webコンテンツを表示できるようになりました。次に、CloudWatchを使って、API Gatewayのログを出力できるようにします。ログを出力できるようにすると、デバッグ等に役立ちます。
CloudWatchにAPI Gatewayのログを書き込めるようにするため、CloudWatchに書き込み権限を持つIAMロールを作成して、API Gatewayに作成したIAMロールを割り当てます。その後、API GatewayでCloudWatchログ書き込みを有効化します。
API GatewayのAWS IAMロールを作成
AWS IAMのコンソールに移動します。ロールを作成し、API Gatewayを選択します。
![](https://ueyama.blog/wp-content/uploads/2021/05/image-16-1024x529.png)
![](https://ueyama.blog/wp-content/uploads/2021/05/image-17-1024x746.png)
デフォルトで、AmazonAPIGatewayPushToCloudWatchLogs というAWS管理ポリシーがアタッチされています。何もせず、[次のステップ:タグ]をクリックします。
![](https://ueyama.blog/wp-content/uploads/2021/05/image-22-1024x645.png)
![](https://ueyama.blog/wp-content/uploads/2021/05/image-23-1024x648.png)
ロール名を入力します。
![](https://ueyama.blog/wp-content/uploads/2021/05/image-24-1024x651.png)
ロールを作成できました。作成したロールをクリックします。
![](https://ueyama.blog/wp-content/uploads/2021/05/image-25-1024x443.png)
ARNをメモしておきます。
![](https://ueyama.blog/wp-content/uploads/2021/05/image-26-1024x454.png)
API GatewayにCloudWatch書き込み権限のあるIAMロールを設定
API Gatewayのコンソールに移動し、[設定]から先ほど作成したIAMロールのARNを入力します。
![](https://ueyama.blog/wp-content/uploads/2021/05/image-28-1024x648.png)
API GatewayでCloudWatchログ書き込みを有効化
CloudWatchのARNを調べるために、CloudWatchのコンソールにアクセスします。https://console.aws.amazon.com/cloudwatch/
![](https://ueyama.blog/wp-content/uploads/2021/05/image-31-1024x378.png)
赤枠内の語尾の :* を除いて、コピーします。
例)arn:aws:logs:ap-northeast-1:623598XXXXXX:log-group:/aws/lambda/japanesecalendar
![](https://ueyama.blog/wp-content/uploads/2021/05/image-32-1024x366.png)
- [CloudWatchログを有効化]にチェックを入れます。
- ログレベルは、今回ERROR以外のログを見たいので、INFOレベルにします。
- [アクセスログの有効化]にチェックを入れます。[Access Log Destination ARN]には、さきほどコピーしたCloudWatchのARNを入力します。
- [ログの形式]は今回はJSONを選択します。
保存ボタンを押しても、「保存できました」などのメッセージが出ませんが、保存できています。
![](https://ueyama.blog/wp-content/uploads/2021/05/image-34-1024x563.png)
CloudWatchコンソールで API Gateway のログイベントを表示
API Gatewayのコンソールにアクセスし、呼び出しURLをコピーします。末尾にパラメータを追加して、ブラウザでアクセスしてみます。
https://XXXX.execute-api.ap-northeast-1.amazonaws.com/dev/japanese?input_text=reiwa2
![](https://ueyama.blog/wp-content/uploads/2021/05/image-35-1024x393.png)
CloudWatchのコンソールにアクセスして、該当のロググループをクリックします。
https://console.aws.amazon.com/cloudwatch/
![](https://ueyama.blog/wp-content/uploads/2021/05/image-36-1024x380.png)
ログが表示されました!
![](https://ueyama.blog/wp-content/uploads/2021/05/image-37-1024x539.png)
参考資料
API Gateway での CloudWatch による REST API のログの設定
AWS公式 CloudWatch コンソールで API Gateway のログイベントを表示する
API GatewayのアクセスログをCloudWatchに記録する
コメント