Warm tip: This article is reproduced from serverfault.com, please click

logging-如何显示IIS上运行的Flask的错误日志?

(logging - How can I show error logs from Flask running on IIS?)

发布于 2020-12-03 13:32:37

我已经阅读了几乎所有可以找到的内容,而且碰到了砖墙。在本地主机上运行时,我已设置安装错误日志以使其正常工作,但是在生产服务器(IIS)上运行该应用程序时,未创建任何日志文件,也未发送电子邮件报告。

我使用的基本设置是带有IIS中“ wfastcgi”模块的简单“ app.py”。

从我的(有限的)理解上看,似乎WSGI是开发(本地主机)和生产服务器(我认为吗)之间的关键区别。

这是我一直在尝试的代码(适用于localhost,但不适用于IIS):

[请注意,这是一个原型版本,因此是简单化的'app.py','app.run()'等。...最终版本实现了Flask'Application Factory'的设置。出于安全原因删除了各种值]

app = Flask(__name__)
app.config['SECRET_KEY'] = SECRET

** APP LOGIC HERE **

if __name__ == "__main__":
    if not app.debug:
        if not os.path.exists(os.path.join(app.root_path, 'logs')):
            os.mkdir(os.path.join(app.root_path, 'logs'))

        class ErrorFormatter(logging.Formatter):
            def format(self, record):
                if current_user.is_authenticated:
                    record.email = str(decrypt(current_user.email))
                else:
                    record.email = "GUEST"
                return super().format(record)

        formatter = ErrorFormatter(
            '\n=========================\n\n%(asctime)s %(levelname)s: [User: %(email)s]\n%(message)s [in %(pathname)s:%(lineno)d]\n\n'
        )

        file_handler = RotatingFileHandler(os.path.join(app.root_path, 'logs', 'error_log.log'), maxBytes=102400, backupCount=10)
        file_handler.setFormatter(formatter)
        file_handler.setLevel(logging.ERROR)
        app.logger.addHandler(file_handler)

        auth = (EMAIL, PASSWORD)
        secure = ()
        mail_handler = SMTPHandler(
            mailhost=(SERVER, PORT),
            fromaddr=EMAIL,
            toaddrs=RECIPIENT,
            subject=SUBJECT,
            credentials=auth,
            secure=secure
        )
        mail_handler.setFormatter(formatter)
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)
    app.run(host=HOST, debug=False)

也许我应该对web.config文件做些什么?

任何帮助将不胜感激。谢谢。

Questioner
lc_
Viewed
12
Ding Peng 2020-12-04 11:11:09

这是我的演示:

在此处输入图片说明

这是我的项目在IIS中的目录结构。

from logging.handlers import RotatingFileHandler

from flask import Flask
import logging
import time
import os

app = Flask(__name__)

handler = RotatingFileHandler(os.path.join(app.root_path, 'logs', 'error_log.log'), maxBytes=102400, backupCount=10)
logging_format = logging.Formatter(
    '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')

handler.setFormatter(logging_format)
app.logger.addHandler(handler)


@app.errorhandler(404)
def page_not_found(error):
    app.logger.error(error)

    return 'This page does not exist', 404


@app.errorhandler(500)
def special_exception_handler(error):
    app.logger.error(error)
    return '500 error', 500


def page_not_found(error):
    return 'This page does not exist', 404


app.error_handler_spec[None][404] = page_not_found


@app.route('/')
def testdasdas1():
    no_thing = []
    i = no_thing[0]
    return 'Hello!'


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

这是hello.py。

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="FlaskFastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python27\python.exe|C:\Python27\lib\site-packages\wfastcgi.pyc" resourceType="Unspecified" requireAccess="Script" />
    </handlers>
    <security> 
        <requestFiltering allowDoubleEscaping="true"></requestFiltering> 
    </security> 
  </system.webServer>
 
  <appSettings>
    <add key="WSGI_HANDLER" value="hello.app" />
    <add key="PYTHONPATH" value="~/" />
     <add key="WSGI_RESTART_FILE_REGEX" value=".*((\.py)|(\.config))$" />
  </appSettings>
</configuration>

这是web.config。

在此处输入图片说明

有关“ Windows 10 IIS服务器上的Python Flask托管”的更多信息,你可以参考此链接