从多个位置进行Python日志记录调用模块 [英] Python logging calling module from multiple places

查看:63
本文介绍了从多个位置进行Python日志记录调用模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用python的日志记录模块和点'.为我的项目设置日志记录层次结构.此处描述的名称结构: https://docs.python.org/2/library/logging.html#logging.getLogger

I would like to set up a logging hierarchy for my project using python's logging module and the dot '.' name structure described here: https://docs.python.org/2/library/logging.html#logging.getLogger

对于给定的模块(bar.py),我想要设置记录器,例如:

For a given module (bar.py), I would like to set up the logger something like:

log = logging.getLogger('x.bar')

然后在整个bar.py模块中可以使用log.(debug/info/warning/etc ...)的位置.我知道bar.py永远不会直接运行,但是可能会从其他几个模块中调用bar.py -因此我不知道在代码片段中将'x'设置为什么是什么.我希望bar.py从调用方(x)继承日志记录处理程序和格式化程序.

Where I can then use log.(debug/info/warning/etc...) throughout the bar.py module. I know that bar.py will never be run directly, but functions within it could possibly be called from several other modules - so I don't know advance what to set 'x' to in the code snippet. I want bar.py to inherit the logging handlers and formatters from it's caller (x).

推荐答案

通过 logging.getLogger('mymodule')实例化模块级记录器的标准方法并非为您量身定做行为.相反,您应该做的是让调用者将记录器作为参数传递给模块中的函数

The standard approach of having a module-wide logger instantiated via logging.getLogger('mymodule') is not tailored for your intended behaviour. What you should do instead is to let the callers pass the logger as an argument to the functions in your module

# mymodule.py
def foo(plogger, a, b):
    logger=plogger.getChild('bar')
    ...

这篇关于从多个位置进行Python日志记录调用模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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