def with_lambda_profiler()

in codeguru_profiler_agent/aws_lambda/profiler_decorator.py [0:0]


def with_lambda_profiler(profiling_group_name=None, region_name=None, environment_override=dict(),
                         profiler_factory=_create_lambda_profiler, env=os.environ):
    """
    Adds profiler start and pause calls around given function execution.
    start() and pause() should never throw exceptions.
    :param profiling_group_name: name of the profiling group where the profiles will be stored.
    :param region_name: AWS Region to report to, given profiling group name must exist in that region. Note
        that this value overwrites what is used in aws_session. If not provided, boto3 will search
        configuration for the region. (e.g. "us-west-2")
    :param environment_override: custom dependency container dictionary. allows custom behavior to be injected.
        See Profiler class for details.
    """
    def function_decorator(function):
        def profiler_decorate(event, context):
            start_time = datetime.now()
            global _profiler
            if _profiler is None:
                _profiler = profiler_factory(profiling_group_name=profiling_group_name,
                                             region_name=region_name,
                                             environment_override=environment_override,
                                             context=context, env=env)
            LambdaContext.get().context = context
            if not _profiler.start():
                # if start() failed, there is high chance it will fail again
                # so we disable the profiler to prevent further attempts.
                _profiler = _EmptyProfiler()
            try:
                return function(event, context)
            finally:
                LambdaContext.get().last_execution_duration = datetime.now() - start_time
                _profiler.pause()

        return profiler_decorate

    return function_decorator