【问题标题】:issues with python logging.getLogger(__name__)python logging.getLogger(__name__) 的问题
【发布时间】:2015-02-06 17:45:06
【问题描述】:

我正在尝试从我正在使用的库 (PyAPNs) 中获取日志。它当然不能开箱即用。我查看了库代码以了解它们用于记录器的内容,它们使用 logging.getLogger() 方法。

预先存在的 PyAPNs 库日志记录代码:

_logger=logging.getLogger(__name__)

这是我试图让它发挥作用的一个坏主意,但我没有运气:

我的应用程序的代码(例如坏主意):

from apns import APNs

class Notifier():

def __init__(self, logger):

    self.logger = logger
    self.apns_client = APNs(arg_list)
    self.apns_client._logger = self.logger

def send_message:

    ...        
    self.apns_client.gateway_server.send_notification(token, payload, identfier=id)        
    ...

这没用

从 celery 任务调用库 (send_message)。所有日志记录在 Notifier 类和 celery 任务中都可以正常工作,只是 PyAPNs 库中没有任何内容进入我的记录器。

有人可以帮助我了解这里可能发生的情况吗?

【问题讨论】:

  • 这个想法很糟糕,你不应该和私人成员搞混。您可以使用根记录器捕获所有内容,也可以使用getLogger(their_module.__name__) 获取他们的记录器并进行适当的配置。我假设他们的记录器没有在单独的进程中运行,这是另一回事。
  • 关于配置他们的记录器以通过我的班级记录器记录的任何建议?记录器设置相当广泛,并且位于应用程序代码的另一个领域。
  • 创建一个日志处理程序,将消息转发到您的记录器并将其附加到他们的记录器。

标签: python logging flask uwsgi celery-task


【解决方案1】:

如果您想为库的记录器自定义日志处理程序,只需配置在

1) 上层记录器(例如根记录器)。参考logging-cookbook

rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.DEBUG)
socketHandler = logging.handlers.SocketHandler('localhost',
                    logging.handlers.DEFAULT_TCP_LOGGING_PORT)
# don't bother with a formatter, since a socket handler sends the event as
# an unformatted pickle
rootLogger.addHandler(socketHandler)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

2) 或者捕获库的记录器并显式配置它

apns_logger = logging.getLogger(apns.__name__)
apns_logger.addHandler(xxx)

3) 或者使用过滤器过滤掉第三方模块的记录器How can I access the current executing module or class name in Python?

【讨论】:

    猜你喜欢
    • 2016-04-16
    • 1970-01-01
    • 2018-11-15
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    相关资源
    最近更新 更多