使用.yaml配置文件记录模块时显示请求模块记录消息

时间:2018-02-21 13:47:22

标签: python logging yaml

在使用.yaml文件配置requests模块时,如何显示logging模块日志消息?

以前我使用以下内容显示来自requests的日志记录输出,但我现在丢失了:

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(levelname)s - %(message)s")
#logging.disable(logging.CRITICAL)

我的.yaml文件已取代上述代码:

version: 1
disable_existing_loggers: False
handlers:
  console:
    class: logging.StreamHandler
    stream: ext://sys.stderr
    formatter: basic
  audit_file:
    class: logging.FileHandler
    filename: bot_log.logging
    encoding: utf-8
    formatter: basic
formatters:
  basic:
    style: "{"
    format: "{asctime:s} {levelname:s}: {name:s}: {message:s}"
    datefmt: "%Y-%m-%d %H:%M:%S"
loggers:
  verbose:
    handlers: [console]
    level: DEBUG
    propagate: False
  audit:
    handlers: [audit_file]
    level: DEBUG
root:
  handlers: [console]
  level: INFO

我现在如何在我的应用程序中加载和配置logging

if __name__ == "__main__":
    with LoggingConfig():
        with TradeHub() as th:
            th.run()

1 个答案:

答案 0 :(得分:1)

requests本身不会记录任何内容,所有日志记录都是从urllib3包中发出的。只需为requests.packages.urllib3记录器添加配置部分:

loggers:
  verbose:
    handlers: [console]
    level: DEBUG
    propagate: False
  audit:
    handlers: [audit_file]
    level: DEBUG
  requests.packages.urllib3:
    propagate: True
    level: DEBUG
root:
  handlers: [console]
  level: INFO

虽然afaik所有urllib3的日志记录输出都有DEBUG级别,但只要您的root记录器具有{{1},您就不会抓住任何内容水平。例如,此代码段不会打印任何内容(INFO是配置文件):

logging.yaml

将根记录器的级别更改为import logging.config import yaml import requests if __name__ == '__main__': with open('logging.yaml', 'rt') as f: config = yaml.safe_load(f.read()) logging.config.dictConfig(config) requests.get('https://stackoverflow.com') 以获得调试输出:

DEBUG