0

Before marking my question closed please help me how I can use below url solution in mine. I went through this link What is the g object in this Flask code? but I am not sure how I can use this.

I am working on python flask and I am creating logs for my application.

I want to acheive something like when a api call is been made it should log to console. Also all the functions which are called from same api function should log request to console. But I want to group them to identify them easily. So I created a uuid for that and using it to uniquely identify the logs as mentioned below

Example

def apiFunction():
    # do something
    function1()
    function2()

So my log should be like

22-03-22:19:00:55: functionName: apiFunction started [xyz-123-456]
22-03-22:19:00:55: functionName: function1 started [xyz-123-456]
22-03-22:19:00:55: functionName: function2 started [xyz-123-456]


22-03-22:19:00:55: functionName: function2 end [xyz-123-456]
22-03-22:19:00:55: functionName: function2 end [xyz-123-456]
22-03-22:19:00:55: functionName: apiFunction end [xyz-123-456]


22-03-22:19:00:55: functionName: apiFunction2 started [abc-def-123]
// and so on

So as you can see in the above approach all the functions logs belonging to apiFunction have same id in the end i.e. ([xyz-123-456])

I am able to achieve above using the below approach

unique_req_id = ""
def log_before_after_functions(is_api):
    def decorator_func(func):
        def wrapper_func(*args, **kwargs):
            logger = get_logger_object()
            global unique_req_id
            if is_api:
                unique_req_id = uuid.uuid4()
            logger.info(f"Start Function {func.__name__} {unique_req_id}")

            if is_api:                
                request_start_time = time.perf_counter()
                result = func(*args, **kwargs)
                request_end_time = time.perf_counter()
                api_response_time = request_end_time - request_start_time
                logger.info(f"End Function {func.__name__} Time: {api_response_time:.4f} seconds {unique_req_id}")

            else :
                result = func(*args, **kwargs)
                logger.info(f"End Function {func.__name__} {unique_req_id}")
            
            return result
        return wrapper_func
    return decorator_func

I am using the decorator as mentioned below

@log_before_after_functions(isApi = True)
def apiFunction():
    # do something
    function1()
    function2()

@log_before_after_functions(isApi = false)
function1():

My problem is when I hit the API from post man and from curl command at same time it gives me two different uuid for same function call. Is there a way I can get same uuid when the api is being hit same time from postman and curl command. Is there a better way to implement the below logic.

Any help will be appreciated. Thanks.

tyler
  • 217
  • 2
  • 6
  • 16

0 Answers0