日志记录的优雅方式.LoggerAdapter可用于其他模块 [英] Elegant way to make logging.LoggerAdapter available to other modules

查看:42
本文介绍了日志记录的优雅方式.LoggerAdapter可用于其他模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use a LoggerAdapter to let my python logging output Linux TIDs instead of the long unique IDs. But this way I don't modify an existing logger but I create a new object:

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

现在,我希望某些模块使用此 LoggerAdapter .只要我知道将全局变量用作记录器,我就可以执行以下操作:

Now I want this LoggerAdapter be used by certain modules. As long as I know a global variable being used as logger I can do something like this:

    somemodule.logger = new_logger

但这不是很好-仅在几种情况下有效,您需要了解模块使用的记录器变量.

But this is not nice - it works only in a couple of cases and you need to know the logger variables used by the modules.

您知道一种使 LoggerAdapter 在全球范围内可用的方法,例如通过打电话给某人喜欢

Do you know a way to make a LoggerAdapter available globally e.g. by calling s.th. like

    logging.setLogger('mylogger', new_logger)

或者:还有其他方法可以让Python logging 输出Linux线程ID,如 ps 打印的吗?

Or alternatively: is there some other way to let Python logging output Linux thread IDs like printed by ps?

推荐答案

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

Alternatively, you can to implement custom logger, and make it default in logging module.

以下是示例:

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可用于其他模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆