Python 使logging.LoggerAdapter可用于其他模块的优雅方式
我使用Python 使logging.LoggerAdapter可用于其他模块的优雅方式,python,logging,module,Python,Logging,Module,我使用LoggerAdapter让python日志输出Linux TID,而不是长的唯一ID。但通过这种方式,我不会修改现有的记录器,而是创建一个新对象: new_logger = logging.LoggerAdapter( logger=logging.getLogger('mylogger'), extra=my_tid_extractor()) 现在我想让某些模块使用这个LoggerAdapter
LoggerAdapter
让python日志输出Linux TID,而不是长的唯一ID。但通过这种方式,我不会修改现有的记录器
,而是创建一个新对象:
new_logger = logging.LoggerAdapter(
logger=logging.getLogger('mylogger'),
extra=my_tid_extractor())
现在我想让某些模块使用这个LoggerAdapter
。只要我知道全局变量用作记录器,我就可以这样做:
somemodule.logger = new_logger
但这并不好——它只在几种情况下起作用,您需要知道模块使用的记录器变量
您是否知道如何使日志适配器在全球范围内可用,例如通过呼叫s.th。像
logging.setLogger('mylogger', new_logger)
或者:是否有其他方法让Python
日志记录
输出Linux线程ID,如由ps
打印?或者,您可以实现自定义日志记录程序,并在日志记录模块中将其设为默认值
下面是一个例子:
import logging
import ctypes
SYS_gettid = 186
libc = ctypes.cdll.LoadLibrary('libc.so.6')
FORMAT = '%(asctime)-15s [thread=%(tid)s] %(message)s'
logging.basicConfig(level=logging.DEBUG, format=FORMAT)
def my_tid_extractor():
tid = libc.syscall(SYS_gettid)
return {'tid': tid}
class CustomLogger(logging.Logger):
def _log(self, level, msg, args, exc_info=None, extra=None):
if extra is None:
extra = my_tid_extractor()
super(CustomLogger, self)._log(level, msg, args, exc_info, extra)
logging.setLoggerClass(CustomLogger)
logger = logging.getLogger('test')
logger.debug('test')
输出样本:
2015-01-20 19:24:09,782 [thread=5017] test
我认为您需要重写LoggerAdapter.process()方法 因为默认的LoggerAdapter.process方法将不起任何作用,下面是一个示例:
import logging
import random
L=logging.getLogger('name')
class myLogger(logging.LoggerAdapter):
def process(self,msg,kwargs):
return '(%d),%s' % (self.extra['name1'](1,1000),msg) ,kwargs
#put the randint function object
LA=myLogger(L,{'name1':random.randint})
#now,do some logging
LA.debug('some_loging_messsage')
out>>DEBUG:name:(167),some_loging_messsage