from opentelemetry import trace
from opentelemetry.trace import StatusCode
def handler(event, context):
http_method = event.get('httpMethod', '')
path = event.get('path', '')
# Set the http request method and route on the parent span.
span = trace.get_current_span()
span.set_attributes({
'http.request.method': http_method,
'http.route': path,
})
try:
result = process_event(event)
# Set the HTTP response code and mark the parent span as failed for 4xx/5xx responses.
status_code = result['statusCode']
span.set_attribute('http.response.status_code', status_code)
span.set_status(StatusCode.OK if status_code < 400 else StatusCode.ERROR)
return result
except Exception as e:
# Set the exception, HTTP error code and status on the parent span.
span.record_exception(e)
span.set_attribute('http.response.status_code', 500)
span.set_status(StatusCode.ERROR)
return {
'statusCode': 500,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'error': 'Internal server error'}),
}