首页 > 解决方案 > 如何使用外部函数/包装器在 python 中的错误/信息日志中捕获额外属性?

问题描述

            startTime = time.time()
                    params = {'user': request.user.username,
                              'class_name': request.__class__.__name__,
                              'method_name': sys._getframe().f_code.co_name,
                              'module_name': __name__,
                              'ip_address': socket.gethostbyname(socket.gethostname()),
                              'process_time': time.time() - startTime}

我需要捕获我的方法的错误日志/信息日志,并将上述参数传递给该方法,以捕获我正在捕获日志的特定方法的额外属性(用户类名称方法名称模块名称 IP 地址进程时间)。下面给出的是我要捕获日志的主要方法。

            db_logger = logging.getLogger('db')
            class Request(APIView):
                @api_view(['GET'])
                def test_api_method(request):
                    db_logger.info("Entering into function", params)

            """"params is the extra attributes that I have mentioned above. I need to pass like this"""""

                    try:
                        1 / 0
                    except Exception as e:
                        db_logger.exception(e, params)
                    return Response({'data': True}, status=status.HTTP_200_OK)

可以使用装饰器或任何常用函数传递参数。请查看此内容并建议您的代码。

标签: python-3.xdjango-rest-frameworkerror-handling

解决方案


推荐阅读