5

我的情况是,我有一个调用 logging.debug(xxx) 的包。我想禁用这个包的所有日志记录语句。有没有办法通过配置做到这一点?

例如,我运行的每个查询都在开发服务器的控制台中打印出来:

调试:根:选择实体。路径,Entities.entity FROM "dev~xxxx!!Entities" AS Entities INNER JOIN "dev~xxxx!!EntitiesByProperty" AS ebp_0 ON Entities。路径= ebp_0。路径INNER JOIN "dev~xxxx!!EntitiesByProperty" AS ebp_1 ON Entities。路径= ebp_1。路径INNER JOIN "dev~xxxx!!EntitiesByProperty" AS ebp_2 ON Entities。路径= ebp_2。路径在哪里 ebp_0.kind = :1 AND ebp_0.name = :2 AND ebp_0.value = :3 AND ebp_1.kind = :4 AND ebp_1.name = :5 AND ebp_1.value = :6 AND ebp_2.kind = :7 AND ebp_2.name = :8 AND ebp_2.value = :9 按实体排序。路径ASC

所以我知道如何通过修改sdk源来禁用它,基本上注释掉里面的日志语句__StarSchemaQueryPlan

logging.debug(query)

有没有办法在不接触 SDK 代码的情况下禁用日志记录?我们目前没有定义任何 loggingConfigurations,而是使用 basicConfiguror。


最终解决方案谢谢@lucemia:

class Filter(object):
    def filter(self, record):
        if record.funcName=='__StarSchemaQueryPlan' and record.module=='datastore_sqlite_stub':
            return 0
        else:
            return 1
4

1 回答 1

8

您可以尝试修改日志级别。

由于该模块使用默认记录器。以下代码将禁用所有级别小于关键的日志。

import logging
logger = logging.getLogger() # get the default logger
logger.setLevel(50) # set the skip all log which is smaller than critical (50)

测试用例

a_lib.py

import logging

def main():
    logging.error("test")
    logging.critical('c')

a_test_case.py

import a_lib
import logging

logger = logging.getLogger()
logger.setLevel(50)
a_lib.main()

结果

> python a_test.py
CRITICAL:root:c

编辑 1

另一种方法是使用过滤器

import logging

# define a new filter
class Filter():
    def filter(self, record):
        # extract property of record such as record.funcName, record.module
        # http://docs.python.org/2/library/logging.html#logrecord-attributes


        if record.module == "a_lib":
            # if the record is from a module you don't want to log
            return 0
        else:
           # for record you want to log
            return 1



 # apply this filter

 filter = Filter()
 logger= logging.getLogger()
 logger.addFilter(filter)
于 2012-12-19T17:51:21.517 回答