Flask block specific endpoints from logging

百般思念 提交于 2020-12-13 06:33:40

问题


I have some ajax calls with bokeh in my flask app and to get its data the bokeh plot performs a POST request every second to a certain endpoint, now I am constantly getting a output like this:

127.0.0.1 - - [25/May/2020 12:50:17] "POST /statusdata/ HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2020 12:50:17] "POST /statusdata/ HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2020 12:50:19] "POST /statusdata/ HTTP/1.1" 200 -
127.0.0.1 - - [25/May/2020 12:50:19] "POST /statusdata/ HTTP/1.1" 200 -

How can I exclude the route /statusdata/ from the debugging logging of flask? Thx for the help!


回答1:


You can add a custom filter to the logger to look for the route name. If you're just using the development server, this will be the werkzeug handler. When you move to production, you'll have to find the specific handler. A complete example (which you can monitor in the browser console to confirm that the form was submitted despite no record showing on the server):

from flask import Flask, render_template_string
import logging


class AjaxFilter(logging.Filter):
    def filter(self, record):  
        return "statusdata" not in record.getMessage()

log = logging.getLogger('werkzeug')
log.addFilter(AjaxFilter())


home_template = """
<form method="post" action="{{ url_for('route_a') }}" class="testAjax">
<input type="submit" value="submit A">
</form>

<form method="post" action="{{ url_for('statusdata') }}" class="testAjax">
<input type="submit" value="submit B">
</form>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
   $(".testAjax").submit(function(e) {
       e.preventDefault();
       var form = $(this);
       var url = form.attr('action');

       $.ajax({
           type: "POST",
           url: url,
           data: form.serialize(),
           context: form,
           success: function(resp) {
               console.log(resp);   
           }
       });
   });
</script>
"""

app = Flask('__name__')


@app.route('/')
def home():
    return render_template_string(home_template)

@app.route('/a', methods=['POST'])
def route_a():
    return "1"

@app.route('/statusdata/', methods=['POST'])
def statusdata():
    return "2"

if __name__ == '__main__':
    app.run()


来源:https://stackoverflow.com/questions/62000942/flask-block-specific-endpoints-from-logging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!