1

I'm using Flask to develop an API. Now I want to have a log to record what is happening in the API. But there are some things I don't understand, and I don't know why they work.

I have the following configuration.

from logging.config import dictConfig

dictConfig({
    'version': 1,
    'formatters': {
        'default': {
            'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
        }
    },
    'handlers': {
        'wsgi': {
            'class': 'logging.StreamHandler',
            'stream': 'ext://flask.logging.wsgi_errors_stream',
            'formatter': 'default'
        },
        'info_file_handler': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': 'logs/info.log',
            'formatter': 'default',
            'maxBytes': 485760,
            'backupCount': 5,
            'encoding': 'utf8'
        },
        'error_file_handler': {
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': 'logs/errors.log',
            'formatter': 'default',
            'maxBytes': 485760,
            'backupCount': 5,
            'encoding': 'utf8'
        },
    },
    'root': {
        'level': 'ERROR',
        'handlers': ['wsgi', 'info_file_handler', 'error_file_handler']
    }
})

According to the official documentation, to use the logger I have to use:

app.logger.error('message')

But when I import app to use the logger in my different modules, I get an error of python circular import dependencies. So it doesn't work. All the examples I see, just use one file and they put everything in there (which is something I don't want).

Testing things, I used Python's logging module, without using the Flask logger variable. I import the module and use it.

import logging
logging.error('message')

And it is done correctly, it takes well the handlers of the above configuration and throw the logs in the respective files.

What I'm wondering is why it works well. I am not using the Flask variable (logger) and works. And I don't have any python circular import dependencies. I hope I've made myself clear.

RodriKing
  • 822
  • 2
  • 10
  • 20

0 Answers0