Logger
Logger utility
Usage Documentation
CLASS | DESCRIPTION |
---|---|
Logger |
Creates and setups a logger to format statements in JSON. |
FUNCTION | DESCRIPTION |
---|---|
log_uncaught_exception_hook |
Callback function for sys.excepthook to use Logger to log uncaught exceptions |
set_package_logger |
Set an additional stream handler, formatter, and log level for aws_lambda_powertools package logger. |
Logger ¶
Logger(
service: str | None = None,
level: str | int | None = None,
child: bool = False,
sampling_rate: float | None = None,
stream: IO[str] | None = None,
logger_formatter: PowertoolsFormatter | None = None,
logger_handler: Handler | None = None,
log_uncaught_exceptions: bool = False,
json_serializer: Callable[[dict], str] | None = None,
json_deserializer: Callable[
[dict | str | bool | int | float], str
]
| None = None,
json_default: Callable[[Any], Any] | None = None,
datefmt: str | None = None,
use_datetime_directive: bool = False,
log_record_order: list[str] | None = None,
utc: bool = False,
use_rfc3339: bool = False,
serialize_stacktrace: bool = True,
buffer_config: LoggerBufferConfig | None = None,
**kwargs,
)
Creates and setups a logger to format statements in JSON.
Includes service name and any additional key=value into logs It also accepts both service name or level explicitly via env vars
Environment variables
POWERTOOLS_SERVICE_NAME : str service name POWERTOOLS_LOG_LEVEL: str logging level (e.g. INFO, DEBUG) POWERTOOLS_LOGGER_SAMPLE_RATE: float sampling rate ranging from 0 to 1, 1 being 100% sampling
PARAMETER | DESCRIPTION |
---|---|
service
|
service name to be appended in logs, by default "service_undefined"
TYPE:
|
level
|
The level to set. Can be a string representing the level name: 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' or an integer representing the level value: 10 for 'DEBUG', 20 for 'INFO', 30 for 'WARNING', 40 for 'ERROR', 50 for 'CRITICAL'. by default "INFO"
TYPE:
|
child
|
create a child Logger named
TYPE:
|
sampling_rate
|
sample rate for debug calls within execution context defaults to 0.0
TYPE:
|
stream
|
valid output for a logging stream, by default sys.stdout |
logger_formatter
|
custom logging formatter that implements PowertoolsFormatter
TYPE:
|
logger_handler
|
custom logging handler e.g. logging.FileHandler("file.log")
TYPE:
|
log_uncaught_exceptions
|
logs uncaught exception using sys.excepthook
TYPE:
|
buffer_config
|
logger buffer configuration See: https://docs.python.org/3/library/sys.html#sys.excepthook
TYPE:
|
Parameters propagated to LambdaPowertoolsFormatter
json_serializer : Callable, optional
function to serialize obj
to a JSON formatted str
, by default json.dumps
json_deserializer : Callable, optional
function to deserialize str
, bytes
, bytearraycontaining a JSON document to a Python
obj,
by default json.loads
json_default : Callable, optional
function to coerce unserializable values, by default
str()`
Only used when no custom formatter is set
utc : bool, optional
set logging timestamp to UTC, by default False to continue to use local time as per stdlib
log_record_order : list, optional
set order of log keys when logging, by default ["level", "location", "message", "timestamp"]
Example
Setups structured logging in JSON for Lambda functions with explicit service name
1 2 3 4 5 |
|
Setups structured logging in JSON for Lambda functions using env vars
1 2 3 4 5 6 7 |
|
Append payment_id to previously setup logger
1 2 3 4 5 6 |
|
Create child Logger using logging inheritance via child param
1 2 3 4 5 6 7 8 |
|
Logging in UTC timezone
1 2 3 4 5 |
|
Brings message as the first key in log statements
1 2 3 4 5 |
|
Logging to a file instead of standard output for testing
1 2 3 4 5 |
|
RAISES | DESCRIPTION |
---|---|
InvalidLoggerSamplingRateError
|
When sampling rate provided is not a float |
METHOD | DESCRIPTION |
---|---|
append_context_keys |
Context manager to temporarily add logging keys. |
clear_buffer |
Clear the internal buffer cache. |
clear_state |
Removes all custom keys that were appended to the Logger. |
flush_buffer |
Flush all buffered log records associated with current execution. |
get_correlation_id |
Gets the correlation_id in the logging json |
inject_lambda_context |
Decorator to capture Lambda contextual info and inject into logger |
refresh_sample_rate_calculation |
Refreshes the sample rate calculation by reconfiguring logging settings. |
set_correlation_id |
Sets the correlation_id in the logging json |
structure_logs |
Sets logging formatting to JSON. |
ATTRIBUTE | DESCRIPTION |
---|---|
handlers |
List of registered logging handlers |
registered_formatter |
Convenience property to access the first logger formatter
TYPE:
|
registered_handler |
Convenience property to access the first logger handler
TYPE:
|
Source code in aws_lambda_powertools/logging/logger.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 |
|
handlers
property
¶
handlers: list[Handler]
List of registered logging handlers
Notes
Looking for the first configured handler? Use registered_handler property instead.
registered_formatter
property
¶
registered_formatter: BasePowertoolsFormatter
Convenience property to access the first logger formatter
registered_handler
property
¶
registered_handler: Handler
Convenience property to access the first logger handler
append_context_keys ¶
append_context_keys(
**additional_keys: Any,
) -> Generator[None, None, None]
Context manager to temporarily add logging keys.
PARAMETER | DESCRIPTION |
---|---|
**additional_keys
|
Key-value pairs to include in the log context during the lifespan of the context manager.
TYPE:
|
Example
Logging with contextual keys
1 2 3 4 |
|
Source code in aws_lambda_powertools/logging/logger.py
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 |
|
clear_buffer ¶
clear_buffer() -> None
Clear the internal buffer cache.
This method removes all items from the buffer cache, effectively resetting it to an empty state.
RETURNS | DESCRIPTION |
---|---|
None
|
|
Source code in aws_lambda_powertools/logging/logger.py
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 |
|
clear_state ¶
clear_state() -> None
Removes all custom keys that were appended to the Logger.
Source code in aws_lambda_powertools/logging/logger.py
832 833 834 835 836 837 838 |
|
flush_buffer ¶
flush_buffer() -> None
Flush all buffered log records associated with current execution.
Notes
Retrieves log records for current trace from buffer Immediately processes and logs each record Warning if some cache was evicted in that execution Clears buffer after complete processing
RAISES | DESCRIPTION |
---|---|
Any exceptions from underlying logging or buffer mechanisms
|
|
will be propagated to caller
|
|
Source code in aws_lambda_powertools/logging/logger.py
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 |
|
get_correlation_id ¶
get_correlation_id() -> str | None
Gets the correlation_id in the logging json
RETURNS | DESCRIPTION |
---|---|
(str, optional)
|
Value for the correlation id |
Source code in aws_lambda_powertools/logging/logger.py
915 916 917 918 919 920 921 922 923 924 925 |
|
inject_lambda_context ¶
inject_lambda_context(
lambda_handler: AnyCallableT,
log_event: bool | None = None,
correlation_id_path: str | None = None,
clear_state: bool | None = False,
flush_buffer_on_uncaught_error: bool = False,
) -> AnyCallableT
inject_lambda_context(
lambda_handler: None = None,
log_event: bool | None = None,
correlation_id_path: str | None = None,
clear_state: bool | None = False,
flush_buffer_on_uncaught_error: bool = False,
) -> Callable[[AnyCallableT], AnyCallableT]
inject_lambda_context(
lambda_handler: AnyCallableT | None = None,
log_event: bool | None = None,
correlation_id_path: str | None = None,
clear_state: bool | None = False,
flush_buffer_on_uncaught_error: bool = False,
) -> Any
Decorator to capture Lambda contextual info and inject into logger
PARAMETER | DESCRIPTION |
---|---|
clear_state
|
Instructs logger to remove any custom keys previously added
TYPE:
|
lambda_handler
|
Method to inject the lambda context
TYPE:
|
log_event
|
Instructs logger to log Lambda Event, by default False
TYPE:
|
correlation_id_path
|
Optional JMESPath for the correlation_id
TYPE:
|
Environment variables
POWERTOOLS_LOGGER_LOG_EVENT : str
instruct logger to log Lambda Event (e.g. "true", "True", "TRUE"
)
Example
Captures Lambda contextual runtime info (e.g memory, arn, req_id)
1 2 3 4 5 6 7 |
|
Captures Lambda contextual runtime info and logs incoming request
1 2 3 4 5 6 7 |
|
RETURNS | DESCRIPTION |
---|---|
decorate
|
Decorated lambda handler
TYPE:
|
Source code in aws_lambda_powertools/logging/logger.py
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 |
|
refresh_sample_rate_calculation ¶
refresh_sample_rate_calculation() -> None
Refreshes the sample rate calculation by reconfiguring logging settings.
RETURNS | DESCRIPTION |
---|---|
None
|
|
Source code in aws_lambda_powertools/logging/logger.py
391 392 393 394 395 396 397 398 399 400 |
|
set_correlation_id ¶
set_correlation_id(value: str | None) -> None
Sets the correlation_id in the logging json
PARAMETER | DESCRIPTION |
---|---|
value
|
Value for the correlation id. None will remove the correlation_id
TYPE:
|
Source code in aws_lambda_powertools/logging/logger.py
905 906 907 908 909 910 911 912 913 |
|
structure_logs ¶
structure_logs(
append: bool = False,
formatter_options: dict | None = None,
**keys,
) -> None
Sets logging formatting to JSON.
Optionally, it can append keyword arguments to an existing logger, so it is available across future log statements.
Last keyword argument and value wins if duplicated.
PARAMETER | DESCRIPTION |
---|---|
append
|
append keys provided to logger formatter, by default False
TYPE:
|
formatter_options
|
LambdaPowertoolsFormatter options to be propagated, by default {}
TYPE:
|
Source code in aws_lambda_powertools/logging/logger.py
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 |
|
log_uncaught_exception_hook ¶
log_uncaught_exception_hook(
exc_type, exc_value, exc_traceback, logger: Logger
) -> None
Callback function for sys.excepthook to use Logger to log uncaught exceptions
Source code in aws_lambda_powertools/logging/logger.py
1293 1294 1295 |
|
set_package_logger ¶
set_package_logger(
level: str | int = logging.DEBUG,
stream: IO[str] | None = None,
formatter: Formatter | None = None,
) -> None
Set an additional stream handler, formatter, and log level for aws_lambda_powertools package logger.
Package log by default is suppressed (NullHandler), this should only used for debugging. This is separate from application Logger class utility
Example
Enables debug logging for Powertools for AWS Lambda (Python) package
1 2 |
|
PARAMETER | DESCRIPTION |
---|---|
level
|
log level, DEBUG by default |
stream
|
log stream, stdout by default |
formatter
|
log formatter, "%(asctime)s %(name)s [%(levelname)s] %(message)s" by default
TYPE:
|
Source code in aws_lambda_powertools/logging/logger.py
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 |
|