如何使用flask日志记录用户在调用接口时所做的更改(之前和之后)

2024-06-17 12:22:24 发布

您现在位置:Python中文网/ 问答频道 /正文

这是经理的业务要求。实际项目与管理系统类似,但他需要详细的日志记录,目前我已经记录了前端调用的后端接口的请求参数,并准备在数据库中设计一个日志表来存储(这样我可以根据前端传递的参数和表中判断前端请求接口是否成功的记录来定位问题)。 但是,我想不出如何将当前登录用户修改的内容(修改前和修改后)添加到维护日志中,以及如何实现这一需求,一个界面中单个表的修改是很困难的,但是如何处理多个表的修改呢? Flask已经工作了一年多了,我希望能寻求各种网友的帮助


Tags: 项目用户数据库flask内容参数界面记录
2条回答

您可以使用Flask中的日志库来实现这一点。 设置配置:

logging.basicConfig(filename='record.log', level=logging.DEBUG, format=f'%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')

然后,无论何时需要记录事件,请使用:

current_app.logger.info("Your message here")

@elephant111cdc是一个“更改数据捕获”功能,您可以can enable on your DB,它会将所有数据修改的历史记录存储在数据库中。审计日志或活动日志是您保存用户在系统中所做工作的某种日志。如果您公开API,格式可能很简单,您只需将每个请求的请求正文和响应正文以及经过身份验证的用户的详细信息保存在某个地方(弹性文件、日志文件甚至数据库)。它可以帮助你追踪一切。例如 审核日志

审核日志/活动日志格式弹性/MongoDB/LogFile

{
"reqUrl" : "/book/13245/",
"reqMethod": "POST",
"reqBody": { 
    "name":"Writing on the Wall",
    "author":"Sam Smith"
},
"respBody":{
    "retCode": 0,
    "retMsg": "Book updated successfully"

},
"username":"elephant111",
"ip_address":"10.10.10.10",
"datetime":"2021-07-30 11:30:00"
}

审计日志/活动日志MySQL格式

| id | reqUrl       | method | reqBody                                             | respBody                                             | username    | ip_address  | date_created        |
|  |       |    |                          -|                           |      -|      -|          -|
| 1  | /book/13245/ | POST   | {"name":"Writing on the Wall","author":"Sam Smith"} | {"retCode": 0,"retMsg": "Book updated successfully"} | elephant111 | 10.10.10.10 | 2021-07-30 11:30:00 |
|    |              |        |                                                     |                                                      |             |             |                     |
|    |              |        |                                                     |                                                      |             |             |                     |

如何在Flask上启用审核日志/活动日志

要在烧瓶上启用审核日志,可以使用以下代码段:

logger_config.py


import os
from logging.config import dictConfig

# Import Log Base Path From Config File
# The output should be something like this 
# log_base_path = "/var/log/"

log_base_path = your_config.LOG_BASE_PATH

logging_dict = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'JSONPERLINE': {
            'format': '%(message)s'
        },
      
    },
    'handlers': {
        'audit_log': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': os.path.join(log_base_path, 'audit_log.log'),
            'formatter': 'JSONPERLINE'
        }
    },
    'loggers': {
        'audit_log': {
            'handlers': ['audit_log'],
            'level': 'INFO'
        }
    }
}

dictConfig(logging_dict)

init.py(或您定义蓝图的任何地方)


@app.after_request
def after_request(response):
    """ Logging all of the requests in JSON Per Line Format. """
    audit_logger = logging.getLogger('inbound_requests')
    
    audit_logger.info({
            "datetime": datetime.datetime.now().isoformat(),
            "user_ip": request.remote_addr,
            "user_name": g.username, // get current authenticated user. you need to customize it based on your code
            "method": request.method,
            "request_url": request.path,
            "response_status": response.status,
            "request_referrer": request.referrer,
            "request_user_agent": request.referrer,
            "request_body": request.json,
            "response_body": response.json
        })
    return response

相关问题 更多 >