gpt4 book ai didi

python - 登录异步函数时如何使用request_id?

转载 作者:行者123 更新时间:2023-12-01 21:27:48 27 4
gpt4 key购买 nike

在异步函数中,每个记录器语句都会获取自己的 request_id。

import logging
log = logging.getLogger('test_logger')

def sync_fun():
log.info("test 1")
log.info("test 2")
log.info("test 3")

@after_response.enable
def async_fun():
log.info("test 1")
log.info("test 2")
log.info("test 3")

output of sync_fun:
[06/Nov/2019 10:42:00.234] [None] [130C6C47F1E24164AAC0440C719630] [INFO] Test 1
[06/Nov/2019 10:42:00.234] [None] [130C6C47F1E24164AAC0440C719630] [INFO] Test 2
[06/Nov/2019 10:42:00.234] [None] [130C6C47F1E24164AAC0440C719630] [INFO] Test 3

130C6C47F1E24164AAC0440C719630 是一个 request_id,对于所有记录器语句都是通用的。

output of async_fun:
[06/Nov/2019 10:42:00.234] [None] [AB352B8F2DF9459ABDD2FBF51EB05F] [INFO] Test 1
[06/Nov/2019 10:42:00.234] [None] [V9E9B6DF5F9C442195EA7C1379FBFA] [INFO] Test 2
[06/Nov/2019 10:42:00.234] [None] [DCA311A92724443C9AD7E951288917] [INFO] Test 3

async_fun 是一个异步函数,所有记录器语句的请求 ID 都不同。

如何为异步函数中的每个记录器语句获取相同的 request_id。

我已经创建了日志过滤器。这里我生成request_id。并且在记录时使用相同的请求 ID。

from threading import local
_thread_locals = local()

class LoggingMiddleware(object):
def process_request(self, request):
if request.user.username:
_thread_locals.user = request.user.username
_thread_locals.user_email = request.user.email
_thread_locals.user_id = request.user.id
#assign request id to all requests (to track cron requests also)
_thread_locals.request_id = str(uuid.uuid4().get_hex().upper()[0:30])


def process_response(self, request, response):
if hasattr(_thread_locals, 'user'):
del _thread_locals.user
if hasattr(_thread_locals, 'request_id'):
del _thread_locals.request_id
if hasattr(_thread_locals, 'user_email'):
del _thread_locals.user_email
if hasattr(_thread_locals, 'user_id'):
del _thread_locals.user_id
return response

def process_exception(self, request, exception):
logger.exception('unhandled error - ')

def get_current_user_details():
user_details = {
'username': getattr(_thread_locals, 'user', None),
'email' : getattr(_thread_locals, 'user_email', None),
'id' : getattr(_thread_locals, 'user_id', None)
}
return user_details

def get_current_user():
return getattr(_thread_locals, 'user', None)

def get_current_request_id():
return getattr(_thread_locals, 'request_id', None)

class RequestIDFilter(logging.Filter):
def filter(self, record):
current_user = get_current_user()
current_request_id = get_current_request_id()
record.user = current_user if current_user else None
record.request_id = current_request_id if current_request_id else str(uuid.uuid4().get_hex().upper()[0:30])
return True

最佳答案

您可以使用singleton pattern它将提供类的单个实例。

代码:

import logging

#Implement Singleton Pattern For Logger
class loggerSingleton(object):
def __new__(myClass):
if not hasattr(myClass, 'instance'):
myClass.instance = super(loggerSingleton, myClass).__new__(myClass)
myClass.instance.log = logging.getLogger('test_logger')
return myClass.instance

#Let's try to create two instances
singletonLog1 = loggerSingleton()
singletonLog2 = loggerSingleton()

#Let's check if we have single instances
print(singletonLog1.log is singletonLog2.log)

#print the logger ID's from two initializations
print(singletonLog1.log)
print(singletonLog2.log)

输出:

> True
> <logging.Logger object at 0x7f8995fcb6d8>
> <logging.Logger object at 0x7f8995fcb6d8>

大多数情况下,包括像您这样的奇点,我更喜欢使用单例模式。

关于python - 登录异步函数时如何使用request_id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58730275/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com