【问题标题】:How to see graphene-django DEBUG logs如何查看graphene-django DEBUG日志
【发布时间】:2019-03-13 16:11:06
【问题描述】:

我在使用 Graphene 和 Django 查看 DEBUG 级别日志时遇到问题。我在settings.py中设置了以下内容:

记录 = { “版本”:1, 'disable_existing_loggers':错误, “处理程序”:{ '安慰': { '类':'logging.StreamHandler', }, }, “记录器”:{ 'django': { '处理程序':['控制台'], '级别':'调试' }, 'django.request': { '处理程序':['控制台'], '级别':'调试' }, }, }

但是,当我尝试查看 Django 服务器的日志时,我看到的只是:

❯❯❯ kubectl 日志 -f server-6b65f48895-bmp6w 服务器 要执行的操作: 应用所有迁移:admin、auth、contenttypes、django_celery_beat、django_celery_results、server、sessions、social_django 运行迁移: 没有要申请的迁移。 正在执行系统检查... 系统检查未发现任何问题(0 静音)。 2018 年 10 月 8 日 - 23:59:00 Django 2.0.6 版,使用设置'backend.settings' 在 http://0.0.0.0:8000/ 启动开发服务器 使用 CONTROL-C 退出服务器。 “POST /graphql HTTP/1.1”400 113 “POST /graphql HTTP/1.1”400 113 “POST /graphql HTTP/1.1”400 113 “POST /graphql HTTP/1.1”400 113 “POST /graphql HTTP/1.1”400 113 “POST /graphql HTTP/1.1”400 113 “POST /graphql HTTP/1.1”400 113 “POST /graphql HTTP/1.1”400 113 “POST /graphql HTTP/1.1”400 113 “POST /graphql HTTP/1.1”400 113

我如何查看DEBUG 级别的日志以了解为什么我的服务器一直在为 400 服务?

我未设置 Django DEBUG 环境变量。我正在尝试调试生产问题。

【问题讨论】:

    标签: django graphql graphene-python


    【解决方案1】:

    根据@donnyy 的回答,我想出了以下实现

    from promise import is_thenable
    from functools import partial
    import logging
    import sys
    import json
    logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
    
    class DebugMiddleware(object):
        def on_error(self, error ,info):
            log_request_body(info)
    
        def resolve(self, next, root, info, **args):
    
            result = next(root, info, **args)
            if is_thenable(result):
                result.catch(partial(self.on_error, info=info))
            return result
    
    
    def log_request_body(info):
        body = info.context._body.decode('utf-8')
        try:
            json_body = json.loads(body)
            logging.error(' User: %s \n Action: %s \n Variables: %s \n Body: %s',
                          info.context.user,
                          json_body['operationName'],
                          json_body['variables'],
                          json_body['query'])
        except:
            logging.error(body)
    
    

    【讨论】:

      【解决方案2】:

      这是我拼凑起来的一个快速中间件,用于捕获 graphql 查询 400 错误。

      settings.py

      MIDDLEWARE = [
          "path_to_file_below.GraphqlErrorLogMiddleware",
          ...
      ]
      
      # Some basic logging from the Django Documentation
      LOGGING = {
          "version": 1,
          "disable_existing_loggers": False,
          "handlers": {"console": {"class": "logging.StreamHandler"}},
          "root": {"handlers": ["console"], "level": "DEBUG"},
      }
      
      
      class GraphqlErrorLogMiddleware(object):
          """
          Logs errors for invalid graphql queries
          """
      
          def __init__(self, get_response):
              self.get_response = get_response
      
          def __call__(self, request):
              response = self.get_response(request)
      
              try:
                  if (
                      400 >= response.status_code
                      and response.status_code != 403
                      and "graphql" in request.path.lower()
                  ):
                      response_json = json.loads(response.content)
      
                      if "errors" in response_json:
                          log_response(
                              message=f"Graphql Error: {response_json['errors']}",
                              response=response,
                              level="error",
                          )
              except Exception as e:
                  logging.debug(f"Error logging Graphql Error: {e}")
      
              return response
      

      【讨论】:

        【解决方案3】:

        前段时间我被同样的问题搞砸了,然后找到了解决方法:

        from promise import is_thenable
        
        
        class DebugMiddleware(object):
            def on_error(self, error):
                print(error)
        
            def resolve(self, next, root, info, **args):
                result = next(root, info, **args)
                if is_thenable(result):
                    result.catch(self.on_error)
        
                return result
        

        并告诉graphene 将其用作中间件:

        GRAPHENE = {
            ...
            'MIDDLEWARE': [
                'path.to.containing.module.DebugMiddleware',
                ...
            ]
        }
        

        在这里您可以访问解决时出现的错误。

        最初的问题(没有模块记录)可能是由于禁用了graphql logger,但是我在这个方向上的探索没有任何结果:(

        【讨论】:

        • 感谢您的帮助!你介意分享一下如何正确连接吗?
        • 什么是“is_thenable”?
        • 一个实用函数来确定指定的对象是否是一个promise。添加了缺少的导入
        猜你喜欢
        • 2011-01-08
        • 2012-09-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-05
        相关资源
        最近更新 更多