I want to log the stdout & stderr to log files, and this is what I tried.
app = Flask(__name__)
app.logger.setLevel(logging.INFO) # use the native logger of flask
app.logger.disabled = False
handler = logging.handlers.RotatingFileHandler(
SYSTEM_LOG_FILENAME,
'a',
maxBytes=1024 * 1024 * 100,
backupCount=20
)
formatter = logging.Formatter(\
"%(asctime)s - %(levelname)s - %(name)s: \t%(message)s")
handler.setFormatter(formatter)
app.logger.addHandler(handler)
@app.route('/')
def hello():
return 'Hello World'
if __name__ == '__main__':
app.run()
Then I would like to log the console output in files. such as
* Running on http://127.0.0.1:5000/
127.0.0.1 - - [24/May/2013 14:55:14] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [24/May/2013 14:55:14] "GET /favicon.ico HTTP/1.1" 404 -
what can I do?
To start with logging in Flask, first import the logging module from Python. This logger module comes out of the box from the Python installation and does not need configuration. The Python logging module logs events based on pre-defined levels. The recorded log events are known as log records.
There is a parameter for you CustomLog sets log filename and format. If you configure /proc/self/fd/1 as the log filename, Apache2 process will now write to its own stdout.
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.
The logging messages you mention don't come from flask's logger, the come from werkzeug
's logger, that means you also need to add your handler to that logger instance to make it work, e.g:
log = logging.getLogger('werkzeug')
log.setLevel(logging.INFO)
log.addHandler(handler)
If you look at how werkzeug initializes its logger, you'll see that it adds a default handler only if logging wasn't already set up. That means if you set it up before wekzeug does, it won't use the default StreamHandler
but the handler you supply.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With