Search code examples
pythonflaskflask-sqlalchemywerkzeug

How to remove the "- -" from flask's logging?


When I run flask 0.9, I got the logging:

127.0.0.1 - - [30/Mar/2016 10:08:38] "GET / HTTP/1.1" 200 -
  1. What should I do to remove - - between 127.0.0.1 and [30/Mar/2006 10:08:38]?

  2. If I want to remove the response code 200 from the log message what should I do?

Any advice will be appreciated!

As @alecxe proposed, I list my snippet code relative logging:

logging.basicConfig(filename='werkzeug.log', level=logging.INFO)
logger = logging.getLogger('werkzeug')
logger.setLevel(logging.INFO)

Solution

  • You can subclass werkzeug.serving.WSGIRequestHandler to override the behavior you don't like:

    import logging
    from flask import Flask
    from werkzeug.serving import WSGIRequestHandler, _log
    
    app = Flask(__name__)
    
    @app.route('/hello')
    def hello():
        return '<html><body><p>Hello, World.</p></body></html>'
    
    class MyRequestHandler(WSGIRequestHandler):
        # Just like WSGIRequestHandler, but without "- -"
        def log(self, type, message, *args):
            _log(type, '%s [%s] %s\n' % (self.address_string(),
                                             self.log_date_time_string(),
                                             message % args))
    
        # Just like WSGIRequestHandler, but without "code"
        def log_request(self, code='-', size='-'):
            self.log('info', '"%s" %s', self.requestline, size)
    
    if __name__=="__main__":
        logging.basicConfig(filename='werkzeug.log', level=logging.INFO)
        logger = logging.getLogger('werkzeug')
        logger.setLevel(logging.INFO)
        app.run(debug=True, request_handler=MyRequestHandler)
    

    The resulting log file:

    INFO:werkzeug: * Running on http://127.0.0.1:5000/
    INFO:werkzeug: * Restarting with reloader
    INFO:werkzeug:127.0.0.1 [30/Mar/2016 02:28:24] "GET /?foo HTTP/1.1" -
    INFO:werkzeug:127.0.0.1 [30/Mar/2016 02:28:28] "GET /hello HTTP/1.1" -