跳过Flask记录一个端点?

时间:2019-07-09 19:44:31

标签: flask

我有一个python flask应用程序。有一个运行状况检查会频繁地影响一个端点(/),我希望在日志中看不到它。如何仅禁用一个GET端点的日志记录,而保留其他所有日志记录?

5 个答案:

答案 0 :(得分:2)

我建议您实施专用的日志记录过滤器。将该过滤器插入内部werkzeug记录器中。

您还可以在https://github.com/pallets/werkzeug/blob/71cf9902012338f8ee98338fa7bba50572606637/src/werkzeug/serving.py#L378处调查WSGI请求处理程序function my_func() { return new Promise(resolve => resolve('hello')); } $(document).ready(function() { document.querySelector('#btn').addEventListener('click', function(e) { async function arr() { arr = await my_func(); $.ajax({ url: "/some_url", type: "GET", dataType: "json", data: { coord: JSON.stringify({ "l1": arr[0], "l2": arr[1] }), csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(json) { window.location.href = "data/"; }, error: function(xhr, errmsg, err) { alert("Error: " + xhr.status + ": " + xhr.responseText); } }); }); } arr(); }); 方法的子类

答案 1 :(得分:2)

ÉtienneBersac向我指出了正确的方向。

这是我的实现方式:

push()

答案 2 :(得分:1)

这是基于 mpaepperanswer 略微修改的实现。

它允许使用正则表达式指定禁用日志的端点。当您想忽略端点(例如 "/v1/recipes/<int:recipe_id>":

)的日志时,这会很有用
def disable_endpoint_logs():
    """Disable logs for requests to specific endpoints."""

    disabled_endpoints = ('/', '/healthz', '/v1/recipes/[0-9]+')

    parent_log_request = serving.WSGIRequestHandler.log_request

    def log_request(self, *args, **kwargs):
        if not any(re.match(f"{de}$", self.path) for de in disabled_endpoints):
            parent_log_request(self, *args, **kwargs)

    serving.WSGIRequestHandler.log_request = log_request

使用上面的代码,端点 "/v1/recipes/23992341" 的日志将被忽略,但 "/v1/recipes" 的日志不会被忽略。

只需在代码中调用一次此函数即可。

答案 3 :(得分:0)

另一个选择是猴子补丁ÉtienneBersac

建议的WSGIRequestHandler

这种方式:

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

答案 4 :(得分:0)

提供的其他解决方案是正确的,它们适用于 Werkzeug 在默认 Flask 设置上。同样的方法也适用于将 Flask 与 gevent 结合使用,但决定将其发布在这里以防其他人偶然发现它并立即需要代码:

from gevent.pywsgi import WSGIHandler

class CustomWSGIHandler(WSGIHandler):
    def log_request(self):
        requests_to_ignore = ["/health", "/"]
    if self.path in requests_to_ignore:
        return
    super(CustomWSGIHandler, self).log_request()