首页 > 解决方案 > 如何从 uswgi + flask 应用程序记录错误?

问题描述

我是 wsgi 和烧瓶的新手,想检查日志。但是我无法将日志打印到文件中。我使用本教程来设置我的项目。我想记录诸如 python 中的打印语句和发生的错误之类的内容。

这是我对 usgwi server.ini 的配置:

[uwsgi]
module = wsgi:app

master = false
processes = 1

socket = myproject.sock
socket = stats.sock
chmod-socket = 660
vacuum = true

die-on-term = true

plugins-dir = /usr/lib/uwsgi/plugins
plugins = logfile


logger = file:logs.log
logger-req = file:requests.log
stats = myproject.sock

logs.log 和 requests.log 永远不会被填满(master=false 和 process=1,因为我在应用程序中使用 tensorflow)

然后我有 wsgi.py

from main import app

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

然后烧瓶应用程序 main.py

app = Flask(__name__, static_url_path='/www')

@app.route('/')
def send_index():
    print("I want to print this to logs")
    x = 1 / 0 # I would like this to throw a ZeroDivisionError and send it to logs
    return send_from_directory('www', 'index.html')

if __name__ == '__main__':
     app.run(host='0.0.0.0')

标签: flaskuwsgiwsgi

解决方案


一种方法是使用“日志记录”包在应用程序中使用日志记录。一些快速提示:

logging.basicConfig(filename='record.log', level=logging.DEBUG, format=f'%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')

应在声明您的应用后在 main.py 中调用。您还可以使用:

current_app.logger.info("Your message here")

记录特定事件。


推荐阅读