How can I log response body in APM in python

I have a Flask API, and I want to log responses body using APM. I used this example code:

from elasticapm.contrib.flask import ElasticAPM
from flask import Flask

app = Flask(__name__)
apm = ElasticAPM(app, server_url='http://localhost:8200', service_name='flask-app-1', logging=True)


@app.route('/')
def hello_world():
    resp = "Hello, World!"
    return resp

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

I have seen set_custom_context in here, but I don't know how to use in above code to send also the resp to APM.

Hi @alza

Have a look at the capture_body setting, it might be exactly what you're looking for :slight_smile:

Thanks @beniwohli. If I understand correctly, capture_body only captures the request body not response body.

Can you show an example of how you're using set_custom_context? As long as it's set during a sampled transaction (i.e., in your hello_world() above), it should be sent automatically with the transaction when the transaction is sent. You shouldn't have to do anything extra.

I didn't set set_custom_context in my hello_world() example above, actually I want to know how to set it? So, then, be able to see the response of requests in Kibana.

I found the solution here! and accordingly changed my example as follow:

import elasticapm
from flask import Flask
from elasticapm.contrib.flask import ElasticAPM

app = Flask(__name__)
app.config['ELASTIC_APM'] = {
    'DEBUG': True,
    'SERVER_URL': 'http://localhost:7200',
    'SERVICE_NAME': 'test-service',
}
apm = ElasticAPM(app)

@app.route('/')
def hello_world():
    resp = {"msg": "Hello world!"}
    elasticapm.set_custom_context({'body': resp})
    return 'OK'

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

Glad you found the solution, and sorry about the confusion with request/response body in my previous answer.

No problem, thanks @beniwohli.

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.