使logging.LoggerAdapter可用于其他模块的优雅方法

2024-09-29 21:58:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用LoggerAdapter让python日志输出Linux tid,而不是长的惟一id。但这样我不会修改现有的logger,而是创建一个新对象:

    new_logger = logging.LoggerAdapter(
                    logger=logging.getLogger('mylogger'), 
                    extra=my_tid_extractor())

现在我希望这个LoggerAdapter被某些模块使用。只要我知道全局变量用作记录器,我就可以这样做:

    somemodule.logger = new_logger

但这并不好-它只在几种情况下工作,您需要知道模块使用的记录器变量。

你知道一种使LoggerAdapter在全球可用的方法吗,例如,通过调用s.th。就像

    logging.setLogger('mylogger', new_logger)

或者:是否有其他方法让Python logging输出Linux线程id,比如由ps打印?


Tags: 模块对象方法idnewmylinuxlogging
2条回答

我认为您需要override 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 

或者,您可以实现自定义记录器,并在日志模块中将其设为默认值。

以下是示例:

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

相关问题 更多 >

    热门问题