Skip to content

Commit 7392794

Browse files
author
Michal Ploski
committed
Add quickstart section in Readme.md
1 parent 7a7ba0a commit 7392794

File tree

3 files changed

+127
-0
lines changed

3 files changed

+127
-0
lines changed

README.md

+127
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,137 @@ A suite of Python utilities for AWS Lambda functions to ease adopting best pract
2929
* **[Idempotency](https://awslabs.github.io/aws-lambda-powertools-python/latest/utilities/idempotency/)** - Convert your Lambda functions into idempotent operations which are safe to retry
3030
* **[Feature Flags](https://awslabs.github.io/aws-lambda-powertools-python/latest/utilities/feature_flags/)** - A simple rule engine to evaluate when one or multiple features should be enabled depending on the input
3131

32+
3233
### Installation
3334

3435
With [pip](https://pip.pypa.io/en/latest/index.html) installed, run: ``pip install aws-lambda-powertools``
3536

37+
## Quick Start
38+
With [SAM](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) installed create, hello-world application and instruct it to include powertools library in the runtime.
39+
```sh
40+
sam init --runtime python3.9 --dependency-manager pip --app-template hello-world --name sam-app
41+
echo "aws-lambda-powertools" > sam-app/hello-world/requirements.txt
42+
```
43+
### Structured Logging
44+
Copy following code into `sam-app/hello-world/app.py`. Build the package and invoke our Lambda code locally `sam build && sam local invoke HelloWorldFunction -e events/event.json`
45+
```python
46+
from aws_lambda_powertools import Logger
47+
48+
logger = Logger()
49+
50+
51+
def send_message(message: str):
52+
logger.info(f"Message returned: {message}")
53+
return {"message": message}
54+
55+
56+
@logger.inject_lambda_context(log_event=True)
57+
def lambda_handler(event, context):
58+
return send_message(message="hello")
59+
60+
```
61+
62+
As a result we should see two records in our logs following the same structured pattern. First one includes the whole event and context thanks to `inject_lambda_context` decorator. Second is the result of invoking `logger.info method`
63+
64+
### X-Ray Tracing
65+
66+
```python
67+
from aws_lambda_powertools import Tracer
68+
69+
tracer = Tracer()
70+
71+
72+
@tracer.capture_method
73+
def send_message(message: str):
74+
tracer.put_annotation(key="message", value=message)
75+
return {"message": message}
76+
77+
78+
@tracer.capture_lambda_handler
79+
def lambda_handler(event, context):
80+
return send_message(message="hello")
81+
```
82+
As tracing doesn't work locally we need to deploy our lambda to the account of your choice.
83+
Modify `template.yaml` to add enable tracing for our lambda
84+
```yaml
85+
Resources:
86+
HelloWorldFunction:
87+
Type: AWS::Serverless::Function
88+
Properties:
89+
...
90+
Tracing: Active
91+
...
92+
```
93+
Configure aws credentials to ensure you deploy it to the specific account
94+
then build and deploy your code: `sam build && sam deploy --guided`.
95+
Invoke your remote function ``aws lambda invoke --function-name <function-name> response.json``
96+
As a result you should see traces for your lambda in X-RAY console
97+
<include zdjecie z segmentem>
98+
<include zdjecie z annotations>
99+
100+
### Custom Metrics
101+
Let's extend our code with application metrics.
102+
103+
```python
104+
from aws_lambda_powertools import Metrics
105+
from aws_lambda_powertools.metrics import MetricUnit
106+
107+
metrics = Metrics(namespace="ApplicationMetrics", service="exampleAPP")
108+
109+
110+
def send_message(message: str):
111+
metrics.add_metric(name="SuccessfulMessageGeneration", unit=MetricUnit.Count, value=1)
112+
return {"message": message}
113+
114+
115+
@metrics.log_metrics
116+
def lambda_handler(event, context):
117+
return send_message(message="hello")
118+
```
119+
120+
In order to see CloudWatch Embedded Metric Format logs you can invoke lambda locally: `sam local invoke HelloWorldFunction -e events/event.json`
121+
```
122+
{"_aws":{"Timestamp":1634299249318,"CloudWatchMetrics":[{"Namespace":"ApplicationMetrics","Dimensions":[["service"]],"Metrics":[{"Name":"SuccessfulMessageGeneration","Unit":"Count"}]}]},"service":"exampleAPP","SuccessfulMessageGeneration":[1.0]}
123+
```
124+
if you deploy this changes into your account those logs will be picked up by cloudwatch and corresponding metrics will be generated
125+
``sam build && sam deploy``
126+
Metrics:
127+
<screenshot>
128+
129+
130+
## Event Handler for Amazon API Gateway:
131+
You might also add event handler router capabilities into your lambda. This way you might configure different methods in your lambda code to be triggered by different API paths.
132+
133+
```python
134+
from aws_lambda_powertools.event_handler.api_gateway import ApiGatewayResolver
135+
136+
app = ApiGatewayResolver()
137+
138+
139+
@app.get("/hi")
140+
def get_message():
141+
return {"message": "Hi!"}
142+
143+
144+
@app.get("/hello")
145+
def get_hello_message():
146+
return {"message": "Hello!"}
147+
148+
149+
def lambda_handler(event, context):
150+
return app.resolve(event, context)
151+
```
152+
153+
Let's test it locally:
154+
```sh
155+
sam build && sam local start-api &
156+
curl http://127.0.0.1:3000/hi
157+
{"message":"Hi!"}%
158+
(venv) ➜ aws-lambda-powertools-python git:(develop) ✗ curl http://127.0.0.1:3000/hello
159+
{"message":"Hello!"}%
160+
```
161+
162+
36163
## Examples
37164

38165
* [Serverless Shopping cart](https://github.com/aws-samples/aws-serverless-shopping-cart)
210 KB
Loading
160 KB
Loading

0 commit comments

Comments
 (0)