简体   繁体   中英

how to get request of flask in decorator logger?

I want writing log about query strings and form data of request object in flask.

I use decorator function for logging.

customlog.py

import logging

def webLog(func):
    @wraps(func)
    def newFunc(*args, **kwargs):
        logging.debug(request.url + " : " + str(request.remote_addr))
        return func(*args, **kwargs)
    return newFunc

main.py

@app.route('/')
@customlog.webLog
def hello_world():
    return 'Hello World!'

but, request in main.py, another source file.

How to get request object for logging?
Using parameters of decorator function?

I think you can just add the following import from flask import request to customlog.py . Here's the test code I used that worked. I just replaced logging.debug with a simple print statement for testing.

from functools import wraps
from flask import request

def webLog(func):
    @wraps(func)
    def newFunc(*args, **kwargs):
        print request.url + " : " + str(request.remote_addr)
        return func(*args, **kwargs)
    return newFunc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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