如何为Django创建该记录器?

时间:2018-02-08 21:38:15

标签: python django logging django-rest-framework

URL: / client /[client_id]/ log / operator
Method: POST
Data:
{
"access_token": "TOKEN",
"limit": 100,
"sort": "asc",
"start_date": "2018-01-01T00: 00: 00Z"
}
OR
{
"access_token": "TOKEN",
"limit": 100,
"sort": "asc",
"offset": "500"
}

Success Response:
{
"result": "ok",
"logs": [
{
"date": "2018-01-01T00: 00: 00Z",
"text": "Log entry"
},
...
]
}

日志条目的格式为:“message.User:命名运营商的名称。”

我需要创建一个接收运营商活动日志的请求。这将返回所有用户操作的格式化日志。

我有一个活动应用程序,其中有一个OperatorLog模型。

from django.db import models

from users.models import User
from .constants import ACTIVITY_ACTIONS


class OperatorLogManager(models.Manager):
    """Manager for operator logs"""

    def active(self):
        """Mark object as active"""
        return self.filter(is_delete=False)

    def get_by_user_id(self, id):
        return self.active().filter(pk=id)

    def get_by_client_id(self, client_uid):
        return self.active().filter(client_uid=client_uid)



    class OperatorLog(models.Model):
        """Model for logs"""

        user        = models.ForeignKey(User, on_delete=models.CASCADE)
        created     = models.DateTimeField(auto_now_add=True)
        is_deleted  = models.BooleanField(default=False)
        action_type = models.CharField(max_length=32,
             сhoices=ACTIVITY_ACTIONS)
        message     = models.TextField(max_length=2048)
        client_uid  = models.CharField(max_length=50)
        bitrix_id   = models.PositiveIntegerField()

        # Operator Manager
        objects = OperatorLogManager()

        def delete(self, **kwargs):
            self.is_deleted = True
            self.save()

您需要公共API(activity / api.py)才能在其他应用程序中注册事件, 还有一个包含活动类型列表(constants.py)的文件,它应该可以通过导入api.py在其他应用程序中使用,您需要使用序列化程序(DRF)输出日志。

constants.py(样本版本)

from model_utils import Choices

ACTIVITY_ACTIONS = Choices (
   ('ACTION_REQ_PHONE_VERIFY', 'Request phone verification'),
   ('VALIDATE_PHONE', 'Request phone validation'),
   ('VALIDATE_EMAIL', 'Email validation'),
   ('SET_INTERNAL_VERIFY', 'Set result of Internal verification'),
   ('SET_BANK_VERIFY', 'Set result of Bank verification'),
   ('GET_CLIENT_DATA', 'Request client data'),
   ('GET_SENSITIVE_INFO', 'Request sensitive info'),
   )

1 个答案:

答案 0 :(得分:0)

尝试使用日志记录库,您可以在其中访问各种类型的日志消息
喜欢 - 错误,调试,警告或只是信息。

您可以在此处详细了解:
https://docs.python.org/3/library/logging.html