AWS日記48(API Gateway - Custom Access Logs)

# はじめに
今回はAPI Gatewayの Custom Access Logsを試します
[API Gateway Custom Access Logging :: AWS Serverless Observability Workshop](https://serverless-observability.workshop.aws/en/050_logging/logging-producers/api_logs.html)を参考に、CloudWatch による API のカスタムアクセスログの設定を行います


# 設定

### CloudFormation
```yaml
---
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: SampleLogging Page

Parameters:
  ApplicationName:
    Type: String
    Default: 'SampleLoggingPage'

Resources:
  FrontPageApi:
    Type: AWS::Serverless::Api
    Properties:
      Name: SampleLoggingPageApi
      EndpointConfiguration: REGIONAL
      StageName: Prod
      AccessLogSetting:
        DestinationArn: !GetAtt FrontLogGroup.Arn
        Format: "{ 'requestId':'$context.requestId', 'ip': '$context.identity.sourceIp', 'caller':'$context.identity.caller', 'user':'$context.identity.user','requestTime':'$context.requestTime', 'xrayTraceId':'$context.xrayTraceId', 'wafResponseCode':'$context.wafResponseCode', 'httpMethod':'$context.httpMethod','resourcePath':'$context.resourcePath', 'status':'$context.status','protocol':'$context.protocol', 'responseLength':'$context.responseLength' }"
      MethodSettings:
        - MetricsEnabled: True
          ResourcePath: '/*'
          HttpMethod: '*'
  FrontPageFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: SampleLoggingPageFunction
      Handler: bootstrap
      Runtime: provided.al2
      Timeout: 5
      CodeUri: target/lambda/sample_logging/
      MemorySize: 256
      Architectures: ["arm64"]
      Description: 'SampleLogging Function'
      Events:
        testapi:
          Type: Api
          Properties:
            Path: '/api/sample'
            Method: post
            RestApiId: !Ref FrontPageApi
  FrontLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      RetentionInDays: 7
  ApiCWLRoleArn:
    Type: AWS::ApiGateway::Account
    Properties:
      CloudWatchRoleArn: !GetAtt CloudWatchRole.Arn
  CloudWatchRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          Action: 'sts:AssumeRole'
          Effect: Allow
          Principal:
            Service: apigateway.amazonaws.com
      Path: /
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs'

Outputs:
  FunctionName:
    Value: !Ref FrontPageFunction
    Description: Name of the Lambda function
  APIURI:
    Description: "URI"
    Value: !Join ['', ['https://', !Ref FrontPageApi, '.execute-api.', !Ref 'AWS::Region', '.amazonaws.com/', 'Prod/']]

```

 - 「AccessLogSetting」 の 「Format」 に、ログに出力するパラメータを設定します
 - 設定可能な$context 変数は[AWSデベロッパーガイド](https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#context-variable-reference)から確認できます

# 確認

 - APIにアクセスし、アクセスログに今回設定したパラメータが記録されていることを確認します。
![01.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/586707/cbc976d1-1e95-46cf-4d50-dc547017fb1c.jpeg)


# 終わりに
今回はAPI Gatewayのカスタムアクセスログを設定しました。
[CloudFrontのアクセスログの設定](https://docs.aws.amazon.com/ja_jp/AmazonCloudFront/latest/DeveloperGuide/AccessLogs.html)も今後試していこうと思います。

### 参考ドキュメント
[API Gateway Custom Access Logging :: AWS Serverless Observability Workshop](https://serverless-observability.workshop.aws/en/050_logging/logging-producers/api_logs.html)

[API Gateway マッピングテンプレートとアクセスのログ記録の変数リファレンス](https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html)

[API Gateway での CloudWatch による REST API のログの設定](https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/set-up-logging.html)

[AWS::Logs::LogGroup](https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/aws-resource-logs-loggroup.html)