Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make action logging in Django with Django Rest Framework

Good day everyone!

I need to make logging of the actions in Django 1.10.4 with Django Rest Framework and save them in a file.

I have different serializers and functions in them. I've read documentation and not quite understood what I have to do in order to log actions such as CREATE, UPDATE or DELETE with data that I'm sending

For example I have:

class MySerializer(serializers.HyperlinkedModelSerializer):
    def create(self, validated_data):
        ...some code...
        return object

    def update(self, instance, validated_data):
        ...some code...
        return instance

How can I do this and do you have some references to similar tasks?

like image 979
urDMG Avatar asked Jan 09 '17 20:01

urDMG


1 Answers

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!

like image 77
AdelaN Avatar answered Sep 22 '22 16:09

AdelaN