这是经理的业务需求。实际项目类似于管理系统,但他需要详细的logging.At存在,我已经记录了前端调用的后端接口的请求参数,并准备在数据库中设计一个日志表进行存储(以便根据前端传入的参数和表中判断前端请求接口是否成功的记录来定位问题)。但是,我想不到如何将当前登录用户修改的内容(修改前和修改后)添加到维护日志中,如何实现这个requirement.It很难在一个界面中修改单个表,但是如何处理多个表的修改?Flask已经工作一年多了,希望能寻求各路网友的帮助。
发布于 2021-07-29 19:23:00
您可以使用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")发布于 2021-07-30 09:30:05
@Eviant111CDC是一个"Change Data Capture"功能,你可以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上启用审核日志/活动日志
要在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 responsehttps://stackoverflow.com/questions/68568949
复制相似问题