Using highlight.io with Python Flask
Make sure that you followed the fullstack mapping guide.
H.init("<YOUR_PROJECT_ID>", {
tracingOrigins: ['localhost', 'example.myapp.com/backend'],
networkRecording: {
enabled: true,
recordHeadersAndBody: true,
},
});
Download the package from pypi and save it to your requirements. If you use a zip or s3 file upload to publish your function, you will want to make sure highlight-io
is part of the build.
poetry add highlight-io[Flask]
# or with pip
pip install highlight-io[Flask]
Setup the SDK to with the Flask integration.
from flask import Flask
import highlight_io
from highlight_io.integrations.flask import FlaskIntegration
app = Flask(__name__)
# `instrument_logging=True` sets up logging instrumentation.
# if you do not want to send logs or are using `loguru`, pass `instrument_logging=False`
H = highlight_io.H(
"<YOUR_PROJECT_ID>",
integrations=[FlaskIntegration()],
instrument_logging=True,
service_name="my-flask-app",
service_version="git-sha",
environment="production",
)
If you have existing error handlers, you need to instrument them manually to capture errors.
# you may have a custom error handler that formats an error response
# make sure to report the error to highlight to capture it
@app.errorhandler(Exception)
def handle_general_exception(exc: Exception):
highlight_io.H.get_instance().record_exception(exc)
return jsonify(error="internal error", message=str(exc), trace=traceback.format_exc()), 503
Check that your installation is valid by throwing an error. Add the following code to your Flask app and start the Flask server. Visit http://127.0.0.1:5000/hello in your browser. You should see a DivideByZero
error in the Highlight errors page within a few moments.
import logging
import random
import time
from flask import Flask
import highlight_io
from highlight_io.integrations.flask import FlaskIntegration
app = Flask(__name__)
# `instrument_logging=True` sets up logging instrumentation.
# if you do not want to send logs or are using `loguru`, pass `instrument_logging=False`
H = highlight_io.H(
"<YOUR_PROJECT_ID>",
integrations=[FlaskIntegration()],
instrument_logging=True,
service_name="my-flask-app",
service_version="git-sha",
environment="production",
)
@app.route("/hello")
def hello():
return f"<h1>bad idea { 5/0 }</h1>"
if __name__ == "__main__":
app.run()
With the Python SDK, your logs are reported automatically from builtin logging methods. See the Python logging setup guide for more details.