Is it possible to log whenever certain api's are called

Hi.

I have an api gateway where I have setup a gateway to an s3 foldder. I do this to be able to checkc if the user has access to the file before allowing the user to download the file from the s3 bucket.

But I also need to log that a user has failed (if the authenticator denies the access) or has succeeded that call. This has to be logged to a dynamodb table. Do you know if this is possible?

I am not sure how you setup a gateway to an s3 folder, could you give details?

For your second question, I got the answer now.

Step #1

Set a Cloudwatch log group and enable events in a lambda function to steam the logs to dynamodb in serverless framework, such as:

functions:
  steamLogs:
    handler: logs/steam.steam
    environment:
      DYNAMODB_TABLE: { "Ref": "LogsDynamoDbTable" }
    events:
      - cloudwatchLog:
          logGroup: ${self:custom.service}-${self:custom.stage}-CustomAccessLogs

resources:
  Resources:
    CustomAccessLogs:
      Type: AWS::Logs::LogGroup
      Properties:
        LogGroupName: ${self:custom.service}-${self:custom.stage}-CustomAccessLogs

Currently there is a bug in serverless that it can’t reference log group name in lambda function as { "Ref": "CustomAccessLogs" }

Step #2

Enable Custom Access logs in the api gateway, I have given details in this ticket: How to setup "Custom Access Logging" for api gateway using serverless

After you enable this feature, you will get both auth denies or allowed access logs in cloudwatch. Here is a sample log:

{
    "requestId": "859692fd-fd97-11e7-a6a1-c304549351c6",
    "ip": "123.12.123.12",
    "caller": "-",
    "requestTime": "30/Dec/2017:10:47:29 +0000",
    "httpMethod": "GET",
    "resourcePath": "/todos/list",
    "status": "200",
    "protocol": "HTTP/1.1",
    "responseLength": "237"
}

So the hander logs/steam.steam will be triggered automatically for every new logs in log group CustomAccessLogs. In that hander, you can add/update codes, read the data body and create records to dynamodb.

You can customise the handler to filter the cloudwatch logs which you are interested.