关于使用 Flask + Ngnix + uWSGI 进行日志记录的名称错误

Name Error regarding logging with Flask + Ngnix + uWSGI

我已经在 ngnix/uwsgi 后面部署了一个 Flask 应用程序,但我收到一个名称错误,我不确定如何排除故障。

我的代码:

import logging
from logging.handlers import RotatingFileHandler
import json
from time import gmtime, strftime
from flask import Flask, request
from jester import jester

app = Flask(__name__)

# initialize the log handler
logHandler = RotatingFileHandler('/var/log/jester.log', maxBytes=1000, backupCount=1)
# set the log handler level
logHandler.setLevel(logging.ERROR)
# set the app logger level
app.logger.setLevel(logging.ERROR)
app.logger.addHandler(logHandler)

def render_response(response_data, status_code):
    return app.response_class(
            response=json.dumps(response_data),
            status=status_code,
            mimetype='application/json'
        )

# Health check
@app.route('/health-check')
def health_check():
    return render_response("Healthy", 200)

# Main ingestion endpoint
@app.route('/ingest', methods=['POST'])
def ingest():
    # Gather data from the request
    data = request.get_json()

    app.logger.info("Running with data: %s" % str(data))

    #other code...

if __name__ == "__main__":
    app.run(
        host = "0.0.0.0",
        port = int("9999")
    )

我收到的错误是这样的:

[2017-08-30 18:16:26,681] ERROR in app: Exception on /ingest [POST]
Traceback (most recent call last):
  File "/var/www/jester/venv/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/var/www/jester/venv/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/var/www/jester/venv/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/var/www/jester/venv/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/var/www/jester/venv/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/var/www/jester/server.py", line 28, in ingest
    return render_response("Healthy", 200)
NameError: global name 'logger' is not defined

我的 uwsgi.ini 文件:

[uwsgi]
#application's base folder
base = /var/www/jester

#python module to import
app = server
module = %(app)

home = %(base)/venv
pythonpath = %(base)

#socket file's location
socket = /var/www/jester/%n.sock

#permissions for the socket file
chmod-socket = 666

#the variable that holds a flask application inside the module imported at line #6
callable = app

#location of log files
logto = /var/log/uwsgi/%n.log

我不明白为什么我不断收到名称错误,无论我在哪里配置记录器。 uwsgi 是否只是直接调用路由,这样它就不会获取任何日志记录配置?当以这种方式提供应用程序时,我应该如何配置日志以使其可用?

您应该将 logger 变量初始化为记录 class 的对象,然后向其添加 handler

logger = logging.getLoger()

在您的 logHandler = RotatingFileHandler 上方插入这行代码,您应该没问题。

您可以查看 this simple tutorial 日志记录。