Skip Flask logging for one endpoint?

前端 未结 3 1297
失恋的感觉
失恋的感觉 2021-01-14 12:23

I have a Python Flask application. There is a healthcheck that hits one endpoint (/) a lot, and I\'d like to not see it in logs. How do I disable logging for only one GET en

3条回答
  •  无人及你
    2021-01-14 12:49

    Another option is to monkey patch WSGIRequestHandler suggested by Étienne Bersac

    this way:

    from werkzeug.serving import WSGIRequestHandler
    from werkzeug.urls import uri_to_iri
    
    
    try:
        import click
    except ImportError:
        click = None
    
    
    def log_request(WSGIRequestHandler, code="-", size="-"):
        try:
            path = uri_to_iri(WSGIRequestHandler.path)
    
            if path in black_listed_routes:
                return
    
            msg = "%s %s %s" % (WSGIRequestHandler.command, path, WSGIRequestHandler.request_version)
        except AttributeError:
            # path isn't set if the requestline was bad
            msg = WSGIRequestHandler.requestline
    
        code = str(code)
    
        if click:
            color = click.style
    
            if code[0] == "1":  # 1xx - Informational
                msg = color(msg, bold=True)
            elif code[0] == "2":  # 2xx - Success
                msg = color(msg, fg="white")
            elif code == "304":  # 304 - Resource Not Modified
                msg = color(msg, fg="cyan")
            elif code[0] == "3":  # 3xx - Redirection
                msg = color(msg, fg="green")
            elif code == "404":  # 404 - Resource Not Found
                msg = color(msg, fg="yellow")
            elif code[0] == "4":  # 4xx - Client Error
                msg = color(msg, fg="red", bold=True)
            else:  # 5xx, or any other response
                msg = color(msg, fg="magenta", bold=True)
    
        WSGIRequestHandler.log("info", '"%s" %s %s', msg, code, size)
    
    
    def monkey_patch_logger():
        WSGIRequestHandler.log_request = log_request
    

提交回复
热议问题