python - 为外部/第三方库自定义日志记录

标签 python django logging

我遵循了 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/

相关文章:

java - Hadoop 2.5.0 作业不成功,流命令失败

python - 保存日志 - SimpleHTTPServer

Python 错误 os.walk IOError

python - 如何调用派生类方法?

python - 我怎样才能用更少的冗余/复制粘贴来写这个?

python - 从 MYSQL 读取模型时出现 DjangoUnicodeDecodeError

python - 循环创建一个元组

python - 单个表上的 SQLAlchemy 多对多关系错误 : NoReferencedTableError

python - 将 requests.models.Response 转换为 Django HttpResponse

c# - 如何在 C# 中重构 log4net 语句?