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

fra*_*ans 10 python logging module

我用a LoggerAdapter来让我的python日志记录输出Linux TID而不是长的唯一ID.但是这种方式我不修改现有logger但我创建了一个新对象:

    new_logger = logging.LoggerAdapter(
                    logger=logging.getLogger('mylogger'), 
                    extra=my_tid_extractor())
Run Code Online (Sandbox Code Playgroud)

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

    somemodule.logger = new_logger
Run Code Online (Sandbox Code Playgroud)

但这并不好 - 它仅适用于几种情况,您需要知道模块使用的记录器变量.

你是否知道一种在LoggerAdapter全球范围内提供服务的方法,例如通过呼叫s.th. 喜欢

    logging.setLogger('mylogger', new_logger)
Run Code Online (Sandbox Code Playgroud)

或者:还有其他一些方法可以让Python logging输出类似于打印的Linux线程ID ps吗?

Dmi*_*ylo 12

或者,您可以实现自定义记录器,并使其成为日志记录模块的默认值.

这是一个例子:

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')
Run Code Online (Sandbox Code Playgroud)

输出样本:

2015-01-20 19:24:09,782 [thread=5017] test
Run Code Online (Sandbox Code Playgroud)