如何让我的记录器在 Python Flask 应用程序中使用每个页面视图的唯一 ID 进行记录?

How can I get my logger in a Python Flask app to use unique IDs per page view for logging?

我有一个 Flask 应用程序,它带有我根据标准 Python 记录器编写的日志记录系统。

我想为每个页面视图设置一个唯一的 ID,这样我就可以跟踪整个过程并检查记录的错误和过早结束。

我尝试的第一件事是将唯一 ID 创建者放入记录器 __init__ 中 object.The 结果是所有请求都具有相同的视图。我将创建唯一 ID 的地方移到了一个方法中,这改善了情况 - 日志中出现了多个 ID,一切似乎都在工作。

但是,有时两个请求似乎使用同一个记录器对象。似乎当一个请求是 运行 时,另一个请求启动并运行 ID 生成方法。然后第一个请求也开始使用新 ID...

22:04:31 - MPvzGNAelE : in content
22:04:31 - MPvzGNAelE : in parse options
22:04:31 - MPvzGNAelE : finished parse options
22:04:31 - MPvzGNAelE : about to query API for user info. user id : 7401173, resource id: 59690
#the following is where the 2nd requests starts
22:04:31 - SbEOjmbFSa : in  frame initial 
22:04:31 - SbEOjmbFSa : in  frame 2 - cleaned IDs are 1114 127059932
22:04:31 - SbEOjmbFSa : in parse options
22:04:31 - SbEOjmbFSa : finished parse options
22:04:31 - SbEOjmbFSa : in  frame finishing - for 1114 127059932
#the following is the first request continuing with the new ID
22:04:31 - SbEOjmbFSa : api user info status is success
22:04:31 - SbEOjmbFSa : user_id is 5549565, user name is joe_spryly
22:04:31 - SbEOjmbFSa : config[data_source] is 0
22:04:31 - SbEOjmbFSa : api seems to be working, so going to retrieve items for 59690 7401173
22:04:31 - SbEOjmbFSa : getting items from API for 59690 7401173

这是我的日志对象代码...

class AS_Log(object):      
    def __init__(self):
        self.log=logging.getLogger('aman_log')
        logging.basicConfig(filename='amanset_log',level=logging.DEBUG)

    def generate_id(self):
        from random import choice
        import string
        chars=string.letters+string.digits
        self.log_id=''.join([choice(chars) for i in range(10)])

    def format_date(self,timestamp):
        return datetime.fromtimestamp(timestamp).strftime('%m-%d-%y %H:%M:%S')   

    def log_msg(self,message):
        self.log.debug('{0} - {1} : {2}'.format(self.format_date(time()),self.log_id,message))     

我像

一样在烧瓶应用程序中启动日志
as=AS_Log()

然后像

这样的每个请求调用generate_id
@app.route('/<resource_id>/<user_id>/')
def aman_frame(resource_id,user_id):
    as.generate_id()
    return amanset_frame(resource_id,user_id)

然后在amanset_frame函数中使用日志

我有一些想法,这是 Flask 中的相关应用程序上下文,但我不明白如何使用它来解决这个问题。我是否使用 app_context(),如果是,如何使用?

最终这是由于跨多个执行上下文改变共享 as.log_id 字段引起的(很可能是线程,但它可能是 greenlets 甚至 sub-processes 如果 as 在共享中与某些 uwsgi / mod_wsgi 设置一样的父解释器)。

request-1 --> mutates log_id --> does ... work ... --> response
              request-2 --> mutates log_id  --> does ... work ... --> response

解决方法是使用适当的 thread-local for the logger, so a new logger is created per thread of execution. Werkzeug has a LocalProxy,这样也更容易管理。