[Solved]-How to make action logging in Django with Django Rest Framework

20👍

Good day, fellow Stackoverflower !

Let’s take this step by step.

First, you need to declare a Django logger. This is basically a sort of file handler (in your case, because you want to write to a file) with some extra capabilities.

The simplest logger can be something like (in your settings.py):

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/path/to/django/debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

Next, in each file where you want to log something, you will first have to get a reference to the logger. You can do something like this :

import logging
logger = logging.getLogger(__name__)

Now that you have the logger, you can simply start logging whatever you want. The code from your example becomes :

class MySerializer(serializers.HyperlinkedModelSerializer):
    def create(self, validated_data):
        ...some code...
        logger.info('Information incoming!')
        return object

    def update(self, instance, validated_data):
        ...some code...
        logger.error('Something went wrong!')
        return instance

However, I have the feeling that you want this to be done for each serializer you have. If that’s the case, let me know and I’ll extend my answer.

Good luck!

👤AdelaN

0👍

Most of the actions are listed in the mixins.py

Leave a comment