uwsgi + flask logging.config not working and also

2019-08-24 12:53发布

问题:

Been looking for an answer for the last 5 hours and found nothing.

I have a flask (python 2.7) application working fine with uwsgi but I have no logs.

/etc/uwsgi/uwsgi.ini config:

[uwsgi]
socket = /tmp/uwsgi.sock
chown-socket = nginx:nginx
chmod-socket = 664
cheaper = 2
processes = 16

/app/uwsgi.ini

[uwsgi]
module = main
callable = app

/app/main.py (works fine without uwsgi)

app = Flask(__name__)
...
...
...
if __name__ == "__main__":
    with open("{0}/logging.config.json".format(CONFIG_PATH), "r") as fd:
        logging.config.dictConfig(json.load(fd))
    app.run()

logging.config.json:

...
"formatters": {
  "simple": {
      "()": "pythonjsonlogger.jsonlogger.JsonFormatter",
      "format": "%(asctime)s %(levelname)s %(module)s %(message)s"
    }
...
"handlers": {
"console":{
      "level": "DEBUG",
      "class": "logging.StreamHandler",
      "formatter": "simple",
      "stream" : "ext://sys.stdout"
  },
  "loggers": { },
  "root": {
      "handlers": ["console"],
      "level": "DEBUG"
  }
}

I've also tried to move the logger outside of main (one post suggested it) as follows:

app = Flask(__name__)

with open("{0}/logging.config.json".format(CONFIG_PATH), "r") as fd:
    logging.config.dictConfig(json.load(fd))
...
...
...
if __name__ == "__main__":
    app.run()

and it just breaks uwsgi:

--- no python application found, check your startup logs for errors ---

same with logging declaration before app declaration (but without an error - the app just doesn't work)

Any suggestions?

回答1:

Well I found the problem:

"formatters": {
"simple": {
  "()": "pythonjsonlogger.jsonlogger.JsonFormatter",
  "format": "%(asctime)s %(levelname)s %(module)s %(message)s"
}

pythonjsonlogger is a library i installed manually decades ago and forgot about. It wasn't loading correctly when declaring logging.config.dictConfig().

Also, to whomever sees this, uWSGI calls only app.run() and if you want to see any logs you should declare logging before you declare app. eg:

with open("{0}/logging.config.json".format(CONFIG_PATH), "r") as fd:
    logging.config.dictConfig(json.load(fd))

app = Flask(__name__)
...
...
...
if __name__ == "__main__":
    app.run()