From d445b359e9d1b1aee27c116a90a5e1d1a4cfc354 Mon Sep 17 00:00:00 2001 From: Joel Collins Date: Tue, 19 Mar 2019 12:46:16 +0000 Subject: [PATCH] Let gunicorn handle logging --- openflexure_microscope/api/app.py | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/openflexure_microscope/api/app.py b/openflexure_microscope/api/app.py index 8e3462bb..6e67129d 100644 --- a/openflexure_microscope/api/app.py +++ b/openflexure_microscope/api/app.py @@ -6,6 +6,8 @@ TODO: Implement API route to cleanly shut down server from flask import ( Flask, render_template) +from flask.logging import default_handler + from flask_cors import CORS from openflexure_microscope.api.exceptions import JSONExceptionHandler @@ -15,14 +17,30 @@ from openflexure_microscope.camera.pi import StreamingCamera from openflexure_microscope.stage.openflexure import Stage import atexit -import logging, sys +import logging +import sys, os -logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) +# Handle logging +is_gunicorn = "gunicorn" in os.environ.get("SERVER_SOFTWARE", "") + +if (__name__ == "__main__") or (not is_gunicorn): + # If imported, but not by gunicorn + print("Letting sys handle logs") + logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) +else: + print("Letting gunicorn handle logs") + # If running in gunicorn, let gunicorn handle logging + root = logging.getLogger() + + gunicorn_logger = logging.getLogger('gunicorn.error') + for handler in gunicorn_logger.handlers: + root.addHandler(handler) + + root.setLevel(gunicorn_logger.level) # Create a dummy microscope object, with no hardware attachments api_microscope = Microscope(None, None) - # Generate API URI based on version from filename def uri(suffix, api_version, base=None): if not base: @@ -78,7 +96,6 @@ def index(): ##### API ROUTES ###### from openflexure_microscope.api.v1 import blueprints -logging.debug("Registering blueprints...") # Base routes base_blueprint = blueprints.base.construct_blueprint(api_microscope) app.register_blueprint(base_blueprint, url_prefix=uri('', 'v1')) @@ -121,4 +138,4 @@ atexit.register(cleanup) if __name__ == "__main__": - app.run(host='0.0.0.0', port="5000", threaded=True, debug=True, use_reloader=False) + app.run(host='0.0.0.0', port="5000", threaded=True, debug=True, use_reloader=False) \ No newline at end of file