def observability_init_middleware(handler: Callable, event: Dict[str, Any], context: LambdaContext, logger: Logger, metrics: Metrics, log_structure: Dict[str, str] = None, *args, **kwargs) -> Any: """ An aws_lambda_powertools middleware function setting up standard logging and metrics handling for lambda functions. """ if log_structure: logger.structure_logs(append=True, **log_structure) metrics.add_metadata(key='handler_name', value=handler.__module__) try: result = handler(event, context) except Exception as err: metrics.add_metric(name='function_failed', unit='Count', value=1) logger.error({ 'msg': 'Function failed', 'error': str(err), 'event': event }) raise else: metrics.add_metric(name='function_succeeded', unit='Count', value=1) return result
def test_logger_children_propagate_changes(stdout, service_name): # GIVEN Loggers are initialized # create child logger before parent to mimick # importing logger from another module/file # as loggers are created in global scope child = Logger(stream=stdout, service=service_name, child=True) parent = Logger(stream=stdout, service=service_name) # WHEN a child Logger adds an additional key child.structure_logs(append=True, customer_id="value") # THEN child Logger changes should propagate to parent # and subsequent log statements should have the latest value parent.info("Hello parent") child.info("Hello child") parent_log, child_log = capture_multiple_logging_statements_output(stdout) assert "customer_id" in parent_log assert "customer_id" in child_log assert child.parent.name == service_name