我遵循了 django 文档的建议,并像这样使用日志记录:
import logging
logger = logging.getLogger(__name__)
def today(...):
logger.info('Sun is shining, the weather is sweet')
使用我当前的配置,输出如下所示:
2016-08-11 14:54:06 mylib.foo.today: INFO Sun is shining, the weather is sweet
不幸的是,一些我无法修改的库使用这样的日志记录:
import logging
def third_party(...):
logging.info('Make you want to move your dancing feet')
不幸的是,输出看起来像这样:
2016-08-09 08:28:04 root.third_party: INFO Make you want to move your dancing feet
我想看这个:
2016-08-09 08:28:04 other_lib.some_file.third_party: INFO Make you want to move your dancing feet
区别:
root.third_party ==> other_lib.some_file.third_party
如果代码使用 logging.info()
而不是 logger.info()
,我想查看长版本(不是 root
)
更新
这不是 Elegant setup of Python logging in Django 的副本,因为它的解是:
引用开始
在每个模块中,我定义一个记录器使用
logger = logging.getLogger(__name__)
引用结束。
不,我不会修改使用 logging.info()
而不是 logger.info()
的第三方代码。
跟进问题
Avoid logger=logging.getLogger(__name__)
without loosing way to filter logs
最佳答案
正如 Wayne Werner 所建议的,我会使用日志记录格式选项。这是一个例子。
文件 1:external_module
import logging
def third_party():
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
logger.info("Hello from %s!"%__name__)
文件 2:main
import external_module
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(module)s.%(funcName)s: %(levelname)s %(message)s')
logger = logging.getLogger(__name__)
def cmd():
logger.info("Hello from %s!"%__name__)
external_module.third_party()
cmd()
输出:
2016-08-11 09:18:17,993 main.cmd: INFO Hello from __main__!
2016-08-11 09:18:17,993 external_module.third_party(): INFO Hello from external_module!
关于python - 为外部/第三方库自定义日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38897399/