11

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)
abelard2008
  • 1,984
  • 1
  • 20
  • 35
  • Have you set up the logging in your app? What do you have in your `main.py` app entry file? – alecxe Mar 30 '16 at 04:09
  • Related thread: http://stackoverflow.com/questions/17743019/flask-logging-cannot-get-it-to-write-to-a-file. – alecxe Mar 30 '16 at 04:13
  • @alecxe I updated my question. Seemly, the thread you provided can not resolve my question, such as there is no `remote_addr` and I don't know which variable I should use for `remote_addr`? – abelard2008 Mar 30 '16 at 04:17

1 Answers1

16

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" -
Robᵩ
  • 163,533
  • 20
  • 239
  • 308