在不修改boto文件的情况下禁用boto日志记录
我正在使用Boto库与AWS进行交互。我想要关闭日志记录。(或者把日志重定向到/dev/null或者其他文件)。我找不到明显的方法来做到这一点。我试过这个,但似乎没有什么效果:
import boto
boto.set_file_logger('boto', 'logs/boto.log')
这里说是可以做到的,http://developer.amazonwebservices.com/connect/thread.jspa?messageID=52727췷,但据我所知,文档里并没有说明具体怎么做。
9 个回答
18
这是我截至今天(2020年1月31日)找到的唯一有效的解决方案:
for name in ['boto', 'urllib3', 's3transfer', 'boto3', 'botocore', 'nose']:
logging.getLogger(name).setLevel(logging.CRITICAL)
logger = logging.getLogger(__name__)
这个解决方案使用了
boto3.set_stream_logger('', logging.CRITICAL)
但它会把我所有非boto的日志都搞没了。它会影响Python标准日志的根日志记录器。
你可以自己试试:
import logging
import boto3
import sys
logger = logging.getLogger(__name__)
boto3.set_stream_logger('', logging.CRITICAL)
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout,
format='%(asctime)s - %(levelname)s - %(message)s')
if __name__ == '__main__':
s3_client = boto3.client('s3')
response = s3_client.list_buckets()
logger.info(f'bucket list: {response}')
无论你在哪里初始化 logger
,都不会显示输出。只要把 boto3.set_stream_logger('', logging.CRITICAL)
这一行去掉,非boto3的日志就会重新出现!所以,唯一有效的解决方案就是不要使用 boto3.set_stream_logger()
这种方法,而是按照我建议的方式来做。
71
我把评论里的boto3答案(也就是charneykaye和gene_wood的回答)搬到了正式的回答里:
import logging
logger = logging.getLogger()
logger.addHandler(logging.StreamHandler()) # Writes to console
logger.setLevel(logging.DEBUG)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
logging.getLogger('s3transfer').setLevel(logging.CRITICAL)
logging.getLogger('urllib3').setLevel(logging.CRITICAL)
import boto3
s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
print(bucket.name)
要获取所有的日志记录器,可以参考leobarcellos的回复:
import logging
loggers_dict = logging.Logger.manager.loggerDict
110
你可以试试
import logging
logging.getLogger('boto').setLevel(logging.CRITICAL)
这样可以屏蔽所有错误信息(除了严重错误)。
Boto使用日志配置文件(比如 /etc/boto.cfg
和 ~/.boto
),你可以看看能不能通过这些文件来满足你的需求。
set_file_logger
这个调用只是把你自己定义的文件添加到日志设置中,所以不能用它来关闭日志记录。