Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 699
abelard2008 Avatar asked Mar 30 '16 04:03

abelard2008


People also ask

What is G in Flask?

Flask provides the g object for this purpose. It is a simple namespace object that has the same lifetime as an application context. Note. The g name stands for “global”, but that is referring to the data being global within a context.

How do I add screen logging to my Flask application?

We first initialize a Flask application class and define the static and template folders. Then we define a route ('/') and tell the application that it should render index. html. The last line tells the application to expose itself on port 5000.


Video Answer


1 Answers

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" -
like image 196
Robᵩ Avatar answered Sep 21 '22 20:09

Robᵩ