【问题标题】:Log return code of request using flask using python使用python使用flask记录请求的返回码
【发布时间】:2019-07-25 04:48:09
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: python python-2.7 logging flask


    【解决方案1】:

    你应该阅读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 文件,您将看到与状态代码一起记录的消息。

    【讨论】:

      猜你喜欢
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多