首页 > 解决方案 > 没有看到包日志 python logger

问题描述

我正在编写一个烧瓶应用程序并使用 pytest 进行测试。我正在使用记录器来记录我的应用程序旁边的一些 python 包。其中一个包是flask_oidc。flask_oidc 使用 logger 来记录调试消息。我想访问其中一些日志。

例如,现在我想访问一些在 flask_oidc 的process_callback中设置的调试日志。

def _process_callback(self, statefield):
        """
        Exchange the auth code for actual credentials,
        then redirect to the originally requested page.
        """
        # retrieve session and callback variables
        try:
            session_csrf_token = session.get('oidc_csrf_token')

            state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8')))
            csrf_token = state['csrf_token']

            code = request.args['code']
        except (KeyError, ValueError):
            logger.debug("Can't retrieve CSRF token, state, or code",
                         exc_info=True) # I want to see this log
            return True, self._oidc_error()

        # check callback CSRF token passed to IdP
        # against session CSRF token held by user
        if csrf_token != session_csrf_token:
            logger.debug("CSRF token mismatch") # I want to see this log as well
            return True, self._oidc_error()

在我的烧瓶应用程序中,我将记录器设置为这样

dictConfig({
    'version': 1,
    'formatters': {'default': {
        'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
    }},
    'handlers': {'wsgi': {
        'class': 'logging.StreamHandler',
        'stream': 'ext://flask.logging.wsgi_errors_stream',
        'formatter': 'default'
    }},
    'root': {
        'level': 'DEBUG',
        'handlers': ['wsgi']
    }
})

对于我的 pytest,我有这个当前设置(暂时)

@pytest.mark.parametrize("idToken, accessToken", oidc_tokens)
def test_noc_oidc_token(idToken, accessToken):
    with app.app_context():
        result = client.get("/oidc-token")
        # print(result.json["oidc_id_token"])
        # No id token
        assert result.status_code == 401
    with app.app_context():
        with client.session_transaction() as session:
            result = client.get("/sso")
            # print(result.__dict__)
            location = result.headers.getlist('location')[0]
            result = client.get(location)
            csrf_token = session.get("oidc_csrf_token")
            print(result)
            signedToken = app.oidc.cookie_serializer.dumps(idToken) #Required modification in backend.py
            with mock.patch("flask_oidc.OpenIDConnect._is_id_token_valid", return_value=True):
                with mock.patch("oauth2client.client.OAuth2WebServerFlow.step2_exchange", return_value=signedToken):
                    data = {"state": {"csrf_token": csrf_token}, "code": "falafel"}
                    result = client.get("/oidc_callback", query_string = data)

我运行 pytest 使用:pytest -rPv --disable-warnings --cov=. 我可以看到来自我的应用程序的日志,但我看不到来自包的任何内容。我设置记录器的方式有问题吗?这是我第一次使用 python 的 logger 模块,所以我对它很陌生。是否可以查看包日志或者这不可能?

标签: pythonflaskloggingpytest

解决方案


推荐阅读