Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Patch botocore to log API calls + parameters
import boto3
import botocore
from botocore.client import BaseClient, Config, ClientMeta
import json
def log_api(self, operation_name, api_params):
meta: ClientMeta = self.meta
print(
json.dumps(
{
"service": meta.service_model.service_id,
"operation": operation_name,
"params": api_params,
"region": meta.region_name,
},
indent=4,
)
)
return original_call(self, operation_name, api_params)
original_call = BaseClient._make_api_call
BaseClient._make_api_call = log_api
if __name__ == "__main__":
# example using S3 Head bucket
s3 = boto3.client("s3", config=Config(signature_version=botocore.UNSIGNED))
bucket = s3.head_bucket(Bucket="flaws.cloud")
print(bucket["ResponseMetadata"]["HTTPHeaders"]["x-amz-bucket-region"])
"""
expected output from log_api is:
{
"service": "S3",
"operation": "HeadBucket",
"params": {
"Bucket": "flaws.cloud"
},
"region": "us-east-1"
}
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment