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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With