def str_to_tuple(val: str): try: if val: return tuple(val.split(",")) except Exception as e: get_logger().debug(f"Error while convert str to tuple", exc_info=e) return None
def handle_timeout(self, *args): get_logger().info("The tracer reached the end of the timeout timer") to_send = [ s for s in self.http_spans if s["id"] in self.http_span_ids_to_send ] utils.report_json(region=self.region, msgs=to_send) self.http_span_ids_to_send.clear()
def end(self, ret_val=None) -> Optional[int]: TimeoutMechanism.stop() reported_rtt = None self.previous_request = None, b"" self.function_span.update({"ended": int(time.time() * 1000)}) if Configuration.is_step_function: self.add_step_end_event(ret_val) if Configuration.verbose: self.function_span.update( {"return_value": prepare_large_data(omit_keys(ret_val))}) spans_contain_errors: bool = any( _is_span_has_error(s) for s in self.http_spans + [self.function_span]) if (not Configuration.send_only_if_error) or spans_contain_errors: to_send = [self.function_span] + [ s for s in self.http_spans if s["id"] in self.http_span_ids_to_send ] reported_rtt = utils.report_json(region=self.region, msgs=to_send) else: get_logger().debug( "No Spans were sent, `Configuration.send_only_if_error` is on and no span has error" ) return reported_rtt
def add_step_end_event(self, ret_val): message_id = str(uuid.uuid4()) step_function_span = StepFunctionParser().create_span(message_id) self.http_spans.append( recursive_json_join(step_function_span, self.base_msg)) self.http_span_ids_to_send.add(step_function_span["id"]) if isinstance(ret_val, dict): ret_val[LUMIGO_EVENT_KEY] = {STEP_FUNCTION_UID_KEY: message_id} get_logger().debug( f"Added key {LUMIGO_EVENT_KEY} to the user's return value")
def parse_event(event: Dict, handlers: List[EventParseHandler] = None): handlers = handlers or [ApiGWHandler(), SNSHandler(), SQSHandler()] for handler in handlers: try: if handler.is_supported(event): return handler.parse(event) except Exception as e: get_logger().debug( f"Error while trying to parse with handler {handler.__class__.__name__} event {event}", exc_info=e, ) return event
def wrap_http_calls(): global already_wrapped if not already_wrapped: with lumigo_safe_execute("wrap http calls"): get_logger().debug("wrapping the http request") wrap_function_wrapper("http.client", "HTTPConnection.send", _request_wrapper) wrap_function_wrapper("botocore.awsrequest", "AWSRequest.__init__", _putheader_wrapper) wrap_function_wrapper("http.client", "HTTPConnection.getresponse", _response_wrapper) wrap_function_wrapper("http.client", "HTTPResponse.read", _read_wrapper) if importlib.util.find_spec("urllib3"): wrap_function_wrapper( "urllib3.response", "HTTPResponse.read_chunked", _read_stream_wrapper ) already_wrapped = True
def start_timeout_timer(self, context=None) -> None: if Configuration.timeout_timer and not Configuration.send_only_if_error: if not hasattr(context, "get_remaining_time_in_millis"): get_logger().info( "Skip setting timeout timer - Could not get the remaining time." ) return remaining_time = context.get_remaining_time_in_millis() / 1000 if TIMEOUT_BUFFER >= remaining_time: get_logger().debug( "Skip setting timeout timer - Too short timeout.") return TimeoutMechanism.start(remaining_time - TIMEOUT_BUFFER, self.handle_timeout)
def start(self, event=None, context=None): to_send = self.function_span.copy() to_send["id"] = f"{to_send['id']}_started" to_send["ended"] = to_send["started"] to_send["maxFinishTime"] = self.max_finish_time if not Configuration.send_only_if_error: report_duration = utils.report_json(region=self.region, msgs=[to_send]) self.function_span["reporter_rtt"] = report_duration self.http_spans = [] else: get_logger().debug( "Skip sending start because tracer in 'send only if error' mode ." ) self.start_timeout_timer(context)
def lambda_wrapper(*args, **kwargs): if str(os.environ.get(_KILL_SWITCH, "")).lower() == "true": return func(*args, **kwargs) if _is_context_already_wrapped(*args): return func(*args, **kwargs) _add_wrap_flag_to_context(*args) executed = False ret_val = None local_print = print local_logging_format = logging.Formatter.format try: if Configuration.enhanced_print: _enhance_output(args, local_print, local_logging_format) SpansContainer.create_span(*args, force=True) SpansContainer.get_span().start(*args) wrap_http_calls() try: executed = True ret_val = func(*args, **kwargs) except Exception as e: with lumigo_safe_execute("Customer's exception"): SpansContainer.get_span().add_exception_event(e, inspect.trace()) raise finally: SpansContainer.get_span().end(ret_val) if Configuration.enhanced_print: builtins.print = local_print logging.Formatter.format = local_logging_format return ret_val except Exception: # The case where our wrapping raised an exception if not executed: TimeoutMechanism.stop() get_logger().exception("exception in the wrapper", exc_info=True) return func(*args, **kwargs) else: raise
def verbose_logger(): """ This fixture make sure that we will see all the log in the tests. """ utils.get_logger().setLevel(logging.DEBUG) utils.config(should_report=False, verbose=True)