登录异步功能时如何使用request_id?

在异步函数中,每个logger语句都获得自己的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,exception):
        logger.exception('unhandled error - ')

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

def get_current_user():
    return getattr(_thread_locals,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
yang01104891 回答:登录异步功能时如何使用request_id?

您可以使用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>

在大多数情况下,其中包括与您的情况类似的奇点,我更喜欢使用Singleton模式。

,

假设您正在使用:

    来自https://github.com/defrex/django-after-response
  • {\"custlist\":[{\"cust_name\":\"Vincent\",\"cust_id\":\"klq:206f387:2d08m92t6\"},{\"cust_name\":\"Joyce\",\"cust_id\":\"125g:1474grx:2d03t9dld\"}]}
  • 来自https://github.com/dabapps/django-log-request-id
  • public void Test() { string str = {\"custlist\":[{\"cust_name\":\"Vincent\",\"cust_id\":\"125g:1474grx:2d03t9dld\"}]}; List<Customer> list = Json2List<Customer>(str); foreach (Customer c in list) { console.writeline ("name=" + c.cust_name); console.writeline ("id=" + c.cust_id); } } public List<T> Json2List<T>(string s) { string json_listname = Regex.Match(s,"\"" + @"(\w+?)" + "\":").Groups[0].Value; JObject jObject = JObject.Parse(s); List<JToken> jTokenList = jObject.GetValue(json_listname).ToList(); List<T> LstT = new List<T>(); foreach (JToken jt in jTokenList) { T obj = jt.ToObject<T>(); LstT.Add(obj); } return LstT; } public class Customer { public string cust_name { get; set; } public string cust_id { get; set; } }

您可以修补after_response以通过并设置log_request_id

after_response
本文链接:https://www.f2er.com/3152190.html

大家都在问