使用python使用Flask记录请求的返回码

时间:2019-03-03 20:56:29

标签: python python-2.7 logging flask

我想记录每个请求的返回码。 例如:-    流日志:127.0.0.1--[04 / Mar / 2019 05:41:40]“ GET / HTTP / 1.1” 200-

文件日志:[2019-03-03 20:41:40,284]调试[src.get:12]成功送达               请求,响应信息:{}

我也想添加响应代码(在上述情况下为“ 200”),也要添加到文件日志中。

OR

我可以将流日志附加到我的文件日志中吗?如果是,怎么办?

1 个答案:

答案 0 :(得分:0)

您应该阅读有关logging模块的信息:

https://docs.python.org/2.7/tutorial/errors.html

下面是有关如何在文件中记录响应代码的最简单的示例。

import requests
import logging

logger = logging.getLogger()

# create a file on the desktop and store logs
file = logging.FileHandler('C:/users/User/Desktop/test.log')

formatter = logging.Formatter()
file.setFormatter(formatter)
logger.addHandler(file) 


# set level of debugging
logger.setLevel(logging.DEBUG)


def visit_google():
    # Connect to google
    r = requests.get("https://www.google.com")

    # Check status_code
    status_code = r.status_code

    if status_code == 200:
        # Save status code along with the message
        logger.debug("Able to connect to google successfully. " + str(status_code))
    else:
        logger.debug("Unable to connect to google. " + str(status_code))

visit_google()

如果在桌面上打开test.log文件,您将看到记录的消息以及状态代码。