Skip to content

Commit 7505fcb

Browse files
committed
docs(logger): document enriching logs with logrecord attributes
1 parent 10ec915 commit 7505fcb

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

docs/core/logger.md

+19
Original file line numberDiff line numberDiff line change
@@ -604,6 +604,25 @@ By default all registered loggers will be modified. You can change this behavior
604604
---8<-- "examples/logger/src/cloning_logger_config.py"
605605
```
606606

607+
**How can I add standard library logging attributes to a log record?**
608+
609+
The Python standard library log records contains a [large set of atttributes](https://docs.python.org/3/library/logging.html#logrecord-attributes), however only a few are included in the powertools log record by default.
610+
611+
If you need to add additional records, these can be included as `kwargs` to `Logger`, or to `LambdaPowertoolsFormatter` when they are being instantiated, or to managed later with the `append_keys` or `remove_keys` methods.
612+
613+
=== "collect.py"
614+
615+
```python hl_lines="3 8 10"
616+
---8<-- "examples/logger/src/append_and_remove_keys.py"
617+
```
618+
=== "Example CloudWatch Logs excerpt"
619+
620+
```json hl_lines="6 15-16"
621+
---8<-- "examples/logger/src/append_and_remove_keys.json"
622+
```
623+
624+
For log records originating from powertools `Logger`, the `name` attribute will be the same as `service`, for log records coming from standard library logger, it will be the name of the logger (i.e. what was used as name argument to `logging.getLogger`).
625+
607626
**What's the difference between `append_keys` and `extra`?**
608627

609628
Keys added with `append_keys` will persist across multiple log messages while keys added via `extra` will only be available in a given log message operation.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
[
2+
{
3+
"level": "INFO",
4+
"location": "<module>:16",
5+
"message": "Name should be equal service value",
6+
"name": "payment",
7+
"service": "payment",
8+
"timestamp": "2022-07-01 07:09:46,330+0000"
9+
},
10+
{
11+
"level": "INFO",
12+
"location": "<module>:23",
13+
"message": "This will include process ID and name",
14+
"name": "payment",
15+
"process": "9",
16+
"processName": "MainProcess",
17+
"service": "payment",
18+
"timestamp": "2022-07-01 07:09:46,330+0000"
19+
}
20+
]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from aws_lambda_powertools import Logger
2+
3+
logger = Logger(service="payment", name="%(name)s")
4+
5+
logger.info("Name should be equal service value")
6+
7+
additional_log_attributes = {"process": "%(process)d", "processName": "%(processName)s"}
8+
logger.append_keys(**additional_log_attributes)
9+
logger.info("This will include process ID and name")
10+
logger.remove_keys(["processName"])
11+
12+
# further messages will not include processName

0 commit comments

Comments
 (0)