title: How do I write Flask's excellent debug log message to a file in production?
body: <p>I have a Flask application that works well and produces an occasional error, which is visible when it is running with <code>debug=True</code>: </p>
  
  <pre><code>if __name__ == '__main__':
      app.run(debug=True)
  </code></pre>
  
  <p>I get useful error messages such as:</p>
  
  <pre><code>Traceback (most recent call last):
    File "./main.py", line 871, in index_route
  
  KeyError: 'stateIIIII'
  </code></pre>
  
  <p>I would like to get error messages like these saved to a file when I run the application in production (using Lighttpd + fastcgi).</p>
  
  <p>After looking at various StackOverflow questions (<a href="http://flask.pocoo.org/docs/errorhandling/" rel="noreferrer">http://flask.pocoo.org/docs/errorhandling/</a>, <a href="http://docs.python.org/2/library/logging.html" rel="noreferrer">http://docs.python.org/2/library/logging.html</a>, etc.); the Flask mailing list; and a few blogs, it seems there is no easy way just to send all the great error messages to a file - I need to use the Python logging module to customise things. So I came up with the following code.</p>
  
  <p>At the top of my application file I have various imports followed by:</p>
  
  <pre><code>app = Flask(__name__)
  
  if app.debug is not True:   
      import logging
      from logging.handlers import RotatingFileHandler
      file_handler = RotatingFileHandler('python.log', maxBytes=1024 * 1024 * 100, backupCount=20)
      file_handler.setLevel(logging.ERROR)
      app.logger.setLevel(logging.ERROR)
      app.logger.addHandler(file_handler)
  </code></pre>
  
  <p>I have then put the code for each route in a try/except statement and use traceback to work out which line the error came from and print a nice error message:</p>
  
  <pre><code>def some_route():
      try:
          # code for route in here (including a return statement)
  
      except:
          exc_type, exc_value, exc_traceback = sys.exc_info()
          app.logger.error(traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2))
          return render_template('error.html')
  </code></pre>
  
  <p>And then right at the end of the file I remove the <code>debug=True</code> statement. Though I don't think I need to do that as the application is being run by a fastcgi server(?) when it is run in production. The last two lines of my application code look like this:</p>
  
  <pre><code>if __name__ == '__main__':
      app.run()
  </code></pre>
  
  <p>I am struggling to get this working. I think the best I have managed is to get a single error log message to be saved in the file using (<code>app.logger.error('test message')</code> ), but it only prints that one message. An attempt to log another error directly after that one is simply ignored.</p>