1

This is a business requirement from the manager. The actual project is similar to the management system, but he requires detailed logging.At present, I have recorded the request parameters of the back-end interface that the front-end calls, and prepare to design a log table in the database to store it (so that I can locate the problem according to the parameters passed by the front-end and the records that judge whether the front-end request interface succeeds or not in the table). However, I can't think of how to add the content (before and after modification) modified by the current login user to the maintenance log, and how to realize this requirement.It is difficult to modify a single table in an interface, but how to handle the modification of multiple tables? Flask has been working for more than a year, and I hope to seek the help of various netizens.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
  • Are you looking for Audit log or CDC? – Soroosh Khodami Jul 29 '21 at 11:53
  • Is it possible that your manager means "Event Sourcing"? ("design a log table in the database" -> this kinda sounds like a history of actions) – c8999c 3f964f64 Jul 29 '21 at 15:21
  • @c899c 3f964f64 I have designed the log table, but the key is how to design a solution to the user before and after changes – elephant111 Jul 30 '21 at 02:45
  • @Soroosh khodami. I don't understand the CDC concept and Audit log, and that's probably not what i excepted. – elephant111 Jul 30 '21 at 02:47
  • https://blog.csdn.net/qq_32793985/article/details/109122289?utm_term=java%E8%AE%B0%E5%BD%95%E4%BF%AE%E6%94%B9%E5%89%8D%E5%90%8E%E6%95%B0%E6%8D%AE&utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~sobaiduweb~default-0-109122289&spm=3001.4430 This is a Java article can achieve the effect I want.But how do you do this with Flask? – elephant111 Jul 30 '21 at 02:51

2 Answers2

0

You may use the logging library in Flask to achieve this. Setting the config:

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

And then whereever you need to log the event, use:

current_app.logger.info("Your message here")
rajat yadav
  • 374
  • 2
  • 7
  • Thank you for your answer sincerely.I think the key is how to record the content before modification and the content after modification, which I have no idea.I have used the method you mentioned, but it does not address the needs – elephant111 Jul 30 '21 at 02:39
0

@elephant111 CDC is "Change Data Capture" feature that you can enable on your DB and it would store all of the histories of data modification on DB. An audit log or Activity log, is some sort of log that you keep what your user has been done in the system. the format could be easy if you are exposing APIs, you can just keep the request body and response body of each request and the detail of authenticated user in somewhere ( Elastic, Log file or even your Database ). And it helps you track everything. for example audit log

Audit Log/Activity Log Format Elastic / 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"
}

Audit Log / Activity Log MySQL Format

| 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 |
|    |              |        |                                                     |                                                      |             |             |                     |
|    |              |        |                                                     |                                                      |             |             |                     |

How To Enable Audit Log / Activity Log on Flask

To Enable Audit Log on the Flask you can use the following snippet code:

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 ( or wherever you define your blueprints )


@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
Soroosh Khodami
  • 1,185
  • 9
  • 17
  • 1
    Thank you for your detailed design, we think of the same, I have achieved your effect, but it still can not visually show the difference between the content before and after modification. – elephant111 Jul 30 '21 at 09:52
  • 1
    If I can't meet the manager's requirements at last, some of your code will be helpful to me. Thank you very much – elephant111 Jul 30 '21 at 10:04
  • actually, I think you can. because every time before you do the modification, you are viewing the current values of the entity in UI. so the previous log, in this case, is showing what was the data before the update ( also you can correlate them via some request generated Id). – Soroosh Khodami Jul 30 '21 at 10:25
  • But, if you want to have them exactly in the same place. it should be done via your service implementation, at first , query what it is and then update, in this case, you can keep both before and after in your logs. But if you have some sort of data that needs to have versioning ( like blog posts ) you can implement your own customized flow something like WordPress Revisions. Link https://wordpress.org/support/article/revisions/ and https://developer.wordpress.org/rest-api/reference/post-revisions/ – Soroosh Khodami Jul 30 '21 at 10:26
  • @elephant111 also check this link out https://stackoverflow.com/a/58189641/9856857 – Soroosh Khodami Jul 30 '21 at 10:46
  • I'll look into it. It'll take some time – elephant111 Aug 02 '21 at 09:55