Skip to content
This repository was archived by the owner on Jan 22, 2026. It is now read-only.

Commit c7994d5

Browse files
Add sample code for a Python Lambda to be integrated with CodeGuru Profiler.
1 parent 6a3783e commit c7994d5

2 files changed

Lines changed: 63 additions & 0 deletions

File tree

sample-demo-lambda-app/README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Amazon CodeGuru Profiler Python Demo Lambda Application
2+
3+
Here's a sample code you can run in a Python Lambda in your account. Further instructions will follow.
4+
5+
To setup Amazon CodeGuru Profiler, enable `Code Profiling` for your Lambda's configuration in the `Monitoring and operation tools` tab.
6+
- https://docs.aws.amazon.com/codeguru/latest/profiler-ug/setting-up-short.html#setting-up-step-2
7+
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import boto3
2+
import logging
3+
import os
4+
5+
from random import randrange
6+
from urllib.request import urlopen
7+
8+
# It is not recommended to enable DEBUG logs in production,
9+
# this is just to show an example of a recommendation
10+
# by Amazon CodeGuru Profiler.
11+
logging.getLogger('botocore').setLevel(logging.DEBUG)
12+
13+
SITE = 'http://www.python.org/'
14+
CW_NAMESPACE = 'ProfilerPythonDemo'
15+
S3_BUCKET = os.environ['S3_BUCKET']
16+
17+
18+
def lambda_handler(event, context):
19+
# Make some network calls using urllib and s3 client.
20+
with urlopen(SITE) as response:
21+
s3_client = boto3.client('s3')
22+
s3_client.put_object(Body=response.read(),
23+
Bucket=S3_BUCKET,
24+
Key='response.txt')
25+
26+
# Publish metrics.
27+
content_length = int(response.headers['Content-Length'])
28+
put_metric('ResponseContentLength', content_length)
29+
put_metric(str(response.status)[0] + 'xxStatus', 1)
30+
31+
# Generate some CPU-intensive work.
32+
num = randrange(content_length)
33+
count = 0
34+
for _ in range(num):
35+
x = randrange(num)
36+
if check_prime(x):
37+
count += 1
38+
39+
return count
40+
41+
42+
def put_metric(name, value):
43+
cw_client = boto3.client('cloudwatch')
44+
metric_data_num = [{'MetricName': name, 'Value': value}]
45+
cw_client.put_metric_data(Namespace=CW_NAMESPACE, MetricData=metric_data_num)
46+
47+
48+
def check_prime(num):
49+
if num == 1 or num == 0:
50+
return False
51+
sq_root = 2
52+
while sq_root * sq_root <= num:
53+
if num % sq_root == 0:
54+
return False
55+
sq_root += 1
56+
return True

0 commit comments

Comments
 (0)