Include Flask response text payload in cloud logging trace

I would like to be able to include the text payload in a Flask response directly in the trace. I understand I can just log the same payload and then return the response, but it just seems redundant. I've Googled a lot for this and haven't come up with anything yet. Thanks, Mike

1 2 109
2 REPLIES 2

Hi @mikeassel,

Welcome to Google Cloud Community!

Absolutely. You can log Flask response text directly in Cloud Logging without redundant logging. There are two options:

  1. Create a custom decorator: This wrapper function logs the response data before returning it, keeping your route code clean.
  2. Override the jsonify function: Modify the built-in jsonify function to include logging within itself. Be aware this might affect other parts of your code that use jsonify.

Hello, Mike,
To include the Flask response text payload directly in the trace, you need to use the make_response function from the flask module. I am attaching an example:
from flask import Flask, make_response

app = Flask(__name__)

@App.route('/')
def hello():
# Create a text payload
text_payload = "Hey, this is a text payload in response to Flask!"

# Use make_response to create a response with a text payload
response = make_response(text_payload)

# Set the Content-Type header for the message to text
response.headers['Content-Type'] = 'text/plain'

return response

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