Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.7k views
in Technique[技术] by (71.8m points)

python - How to log a django view

I'm learning to log and I'm not sure what I'm supposed to do with the logger in my view since what I've read around doesn't seem to work or I'm just not understanding something. This are my settings for the logging:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'todo': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
            'propagate': True,
        },
    },
}

This is the view and the logging part:

from rest_framework import generics, filters
from todo import models
from .serializers import TaskSerializer
from django_filters.rest_framework import DjangoFilterBackend

import logging

logger = logging.getLogger(__name__)

def myview(request):
    logger.error('Something went wrong')

class ListTask(generics.ListCreateAPIView):
    """
    API view to retrieve list of tasks or create new tasks
    """
    queryset = models.Task.objects.all()
    serializer_class = TaskSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    filterset_fields = ['date']
    search_fields = ['description']

class DetailTask(generics.RetrieveDestroyAPIView):
    """
    API view to retrieve or delete a task
    """
    queryset = models.Task.objects.all()
    serializer_class = TaskSerializer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm not sure if there is a better way, but you can override the post() and get() methods of the view and insert logging there. For example:

class ListTask(generics.ListCreateAPIView):
    """
    API view to retrieve list of tasks or create new tasks
    """
    queryset = models.Task.objects.all()
    serializer_class = TaskSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    filterset_fields = ['date']
    search_fields = ['description']

    def get(self, request, *args, **kwargs):
        # do some logging
        logger.debug("A helfpul message")
        # return super which will run the default get() method for this class
        return super().get(request, *args, **kwargs)

Have a look at: http://www.cdrf.co/

You can look at all the various DRF View classes and see which methods they support so you know what you can override if you wish to do some logging.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...