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

How can I show error logs from Flask running on IIS?

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

I've read just about everything I can find on this and I've hit a brick wall. I've setup error logging to work when running on localhost, but when I run it on a production server (IIS), no log file is created, nor is the email report sent.

The basic setup I'm using is a simple 'app.py' with the 'wfastcgi' module in IIS.

From my (limited) understanding, having read up on it, it seems that WSGI is the key difference between the development (localhost) and production servers (I think?).

Here's the code I've been trying (works on localhost, but not on IIS):

[note that this is a prototype version, hence the simplistic 'app.py', 'app.run()', etc. ...the final version implements the Flask 'Application Factory' setup. Various values removed for security reasons]

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)

Should I be doing something with the web.config file, perhaps?

Any help would be greatly appreciated. Thanks.

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

Here is my demo:

enter image description here

This is the directory structure of my project in 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()

This is 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>

This is web.config.

enter image description here

For more information about "Python Flask Hosting on Windows 10 IIS server", you can refer to this link.