Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of flask.logger over the more generic python logging module?

I'm building a website using Flask and I'm now in the process of adding some logging to it for which I found these docs. The basic example is as follows:

if not app.debug:
    import logging
    from themodule import TheHandlerYouWant
    file_handler = TheHandlerYouWant(...)
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

after which you can log using app.logger.error('An error occurred'). This works fine, but apart from the fact that I do not see any advantage over the regular python logging module I also see a major downside: if I want to log outside of a request context (when for example running some code with a cron job) I get errors because I'm using app outside of the request context.

So my main question; why would I use the Flask logger at all? What is the reason that it was ever built?

like image 653
kramer65 Avatar asked Oct 29 '15 13:10

kramer65


1 Answers

The Flask logger uses the "generic" Python logging, it's a logging.getLogger(name) like any other.

The logger exists so that Flask app and views can log things that happen during execution. For example, it will log tracebacks on 500 errors during debug mode. The configuration example is there to show how to enable these logs, which are still useful in production, when you are not in debug mode.

Having an internal logger is not unique to Flask, it's the standard way to use logging in Python. Every module defines it's own logger, but the configuration of the logging is only handled by the last link in the chain: your project.

You can also use app.logger for your own messages, although it's not required. You could also create a separate logger for your own messages. In the end, it's all Python logging.

like image 118
davidism Avatar answered Oct 20 '22 03:10

davidism