I have a mixin that defines finalize_response()
method intended to override in another class:
我有一个mixin定义了finalize_response()方法,旨在覆盖另一个类:
class APILoggingMixin(object):
"""
Provides logging functionality by overriding finalize_response().
Intended to be mixed in with any rest_framework.views.APIView
"""
def finalize_response(self, request, response, *args, **kwargs):
logger.info('Some message.')
return super(APILoggingMixin, self).finalize_response(request, response, *args, **kwargs)
And a class which implements the finalize_response()
method. In the same module, the logger
global var is defined:
还有一个实现finalize_response()方法的类。在同一模块中,定义了记录器全局变量:
import logging
logger = logging.getLogger(__name__)
class CategoryDetail(APILoggingMixin, generics.RetrieveUpdateDestroyAPIView):
"""
Retrieve, update or delete a Category.
"""
model = Category
serializer_class = CategorySerializer
permission_classes = (permissions.IsAuthenticated,)
How can I access the logger
variable in the mixin?
如何在mixin中访问记录器变量?
1 个解决方案
#1
1
Realizing that APILoggingMixin.finalize_response
takes self
which is a CategoryDetail
instance, we could attach logger to CategoryDetail
意识到APILoggingMixin.finalize_response需要self,这是一个CategoryDetail实例,我们可以将logger附加到CategoryDetail
class CategoryDetail(...):
logger = logger
class APILoggingMixin(object):
def finalize_response(self, ...):
self.logger.info('Some message.')
# Or through get_logger()
class CategoryDetail(...):
def get_logger(self):
return logger
class APILoggingMixin(object):
def finalize_response(self, ...):
self.get_logger().info('Some message.')
def get_logger(self):
raise NotImplementedError
# Or take advantage of the fact that `self.__module__` equals to `__name__` in the module of `CategoryDetail`
class APILoggingMixin(object):
def finalize_response(self, ...):
logger = logging.getLogger(self.__module__)
logger.info('Some message.')
#1
1
Realizing that APILoggingMixin.finalize_response
takes self
which is a CategoryDetail
instance, we could attach logger to CategoryDetail
意识到APILoggingMixin.finalize_response需要self,这是一个CategoryDetail实例,我们可以将logger附加到CategoryDetail
class CategoryDetail(...):
logger = logger
class APILoggingMixin(object):
def finalize_response(self, ...):
self.logger.info('Some message.')
# Or through get_logger()
class CategoryDetail(...):
def get_logger(self):
return logger
class APILoggingMixin(object):
def finalize_response(self, ...):
self.get_logger().info('Some message.')
def get_logger(self):
raise NotImplementedError
# Or take advantage of the fact that `self.__module__` equals to `__name__` in the module of `CategoryDetail`
class APILoggingMixin(object):
def finalize_response(self, ...):
logger = logging.getLogger(self.__module__)
logger.info('Some message.')