2017-03-03 79 views
2

请考虑这个虚拟代码。Python日志记录模块输出不必要的信息

$ cat dummy.py 
import logging 
import time 

from boto3.session import Session 

# Logging Configuration 
fmt = '%(asctime)s [%(levelname)s] [%(module)s] - %(message)s' 
logging.basicConfig(level='INFO', format=fmt, datefmt='%m/%d/%Y %I:%M:%S') 
logger = logging.getLogger() 

def main(): 
    session = Session(region_name='us-west-2') 
    client = session.client('ec2') 
    response = client.describe_instances(InstanceIds=['i-11111111111111111']) 

    logger.info('The instnace size is: %s', response[ 
       'Reservations'][0]['Instances'][0]['InstanceType']) 

if __name__ == '__main__': 
    main() 

输出:

$ python3 dummy.py 
03/03/2017 08:47:00 [INFO] [credentials] - Found credentials in shared credentials file: ~/.aws/credentials 
03/03/2017 08:47:01 [INFO] [connectionpool] - Starting new HTTPS connection (1): ec2.us-west-2.amazonaws.com 
03/03/2017 08:47:02 [INFO] [dummy] - The instnace size is: t2.micro 

问题: 如何避免下面线被打印?

03/03/2017 08:47:00 [INFO] [credentials] - Found credentials in shared credentials file: ~/.aws/credentials 
03/03/2017 08:47:01 [INFO] [connectionpool] - Starting new HTTPS connection (1): ec2.us-west-2.amazonaws.com 

如果我改变logging.basicConfig(level='INFO',...logging.basicConfig(level='WARNING',...然后,这些消息不打印,但随后我得到的消息记录与WARNING严重性。

我只想要logging模块打印我明确使用logger.info ....写入的消息,而没有其他东西。因此,我需要关于如何避免不必要的消息被打印的指示。

+0

你不能仅仅为自己申请一个过滤器吗? – River

+0

尽管可能不是一个确切的重复,你应该能够在[这个问题]中找到你要找的东西(http://stackoverflow.com/questions/11029717/how-do-i-disable-log-messages-来自该请求库)。 – glibdud

+0

@glibdud,你提到的问题不是解决方案/解决方法,我已经在我的文章中提到过。谢谢你的时间。 – slayedbylucifer

回答

0

解决方案:

import logging 
import time 

from boto3.session import Session 

# Logging Configuration 
fmt = '%(asctime)s [%(levelname)s] [%(module)s] - %(message)s' 
logging.basicConfig(format=fmt, datefmt='%m/%d/%Y %I:%M:%S') 
logger = logging.getLogger('LUCIFER') 
logger.setLevel(logging.INFO) 


def main(): 
    COUNTER = 3 
    session = Session(region_name='us-west-2') 
    client = session.client('ec2') 
    response = client.describe_instances(InstanceIds=['i-0a912622af142b510']) 

    logger.info('The instnace size is: %s', response[ 
       'Reservations'][0]['Instances'][0]['InstanceType']) 

if __name__ == '__main__': 
    main() 

输出:

$ python3 dummy.py 
03/03/2017 10:30:15 [INFO] [dummy] - The instnace size is: t2.micro 

说明: 早些时候,我设置根记录的INFO水平。因此,没有水平集的所有其他记录仪都会获得此水平propagated并开始记录。在解决方案中,我特别在记录器LUCIFER上启用此级别。

参考: 来自:https://docs.python.org/3/howto/logging.html

子logger消息传播了与他们的祖先记录器相关的处理程序。因此,不必为应用程序使用的所有记录器定义和配置处理程序。为顶级记录器配置处理程序并根据需要创建子记录器就足够了。 (你可以,但是,通过设置一个记录器为False的繁殖属性关闭传播。)

AND

除了直接与记录器相关联的任何处理程序,与所述记录器的所有祖先有关的所有处理程序被调用来分派消息(除非记录器的传播标志被设置为假值,此时传递给祖先处理程序停止)。

相关问题