简体   繁体   English

如何使用Django Rest Framework在Django中进行动作记录

[英]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. 我需要使用Django Rest Framework记录Django 1.10.4中的动作并将其保存在文件中。

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 我已经阅读过文档,但对要发送的数据记录诸如CREATE,UPDATE或DELETE之类的操作却不太了解

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 ! 大家好,Stackoverflower同学们!

Let's take this step by step. 让我们逐步进行此操作。

First, you need to declare a Django logger . 首先,您需要声明一个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 ): 最简单的记录器可以是(在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! 祝好运!

大多数动作列在mixins.py中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM