Best practices for logging with DRF generic views in Django
When using Django Rest Framework's generic views, such as RetrieveAPIView, ListAPIView, and CreateAPIView, it's important to have a clear and consistent approach to logging. A common question is where to place the main logline.
According to the DRF documentation, the recommended approach is to override the initial()
method of the view and set up the logger there. This method is called before any other method, making it an ideal place to set up logging for the view.
Here's an example of how to set up logging in the initial()
method:
import logging
class MyView(ListAPIView):
logger = logging.getLogger(__name__)
def initial(self, request, *args, **kwargs):
self.logger.info('MyView called')
super().initial(request, *args, **kwargs)
This code sets up a logger for the view and logs a message when the view is called. The super().initial()
call ensures that the view's normal initialization process is still executed.
Another option is to override the dispatch()
method, which is called for every request. However, this can result in more log messages than necessary, as it will log for every HTTP method (GET, POST, etc.) that the view supports.
In summary, the recommended approach for logging with DRF generic views is to override the initial()
method. This ensures that the logger is set up before any other methods are called, and provides a clear and consistent approach to logging across views.