4

I have tried both Logging and Traces but haven't found a way to see request headers. Is there a better way than explicitly logging req.headers?

John Otu
  • 208
  • 2
  • 9

2 Answers2

5

Google Cloud logs automatically (and you can increase the log verbosity in the audit logs configuration) the technical information of the service. The standard usage, the request performed on your services (Cloud Function, Cloud Run, App Engine) haven't their content (body and headers) logged. Only the system event: "A post request has been received from this IP, the HTTP response was 200 and the processing duration has taken 500ms".

guillaume blaquiere
  • 66,369
  • 2
  • 47
  • 76
  • Are you essentially saying GCP Cloud Functions do not log request headers? All you described seem to be what I said about Logging and Traces in the question. – John Otu Apr 09 '21 at 01:35
  • 5
    Neither the headers nor the body. It's not an infrastructure relevant metadata, but your service data, you have to log them by yourselves – guillaume blaquiere Apr 09 '21 at 07:11
2

You can parse HTTP request. But make sure your HTTP triggered Functions have public access [1]. Then you can easily handle HTTP Request header [2]. Here an example:

from flask import escape

def hello_content(request):
    """ Responds to an HTTP request using data from the request body parsed
    according to the "content-type" header.
    Args:
        request (flask.Request): The request object.
        <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
    """
    content_type = request.headers['content-type']
    if content_type == 'application/json':
        request_json = request.get_json(silent=True)
        if request_json and 'name' in request_json:
            name = request_json['name']
        else:
            raise ValueError("JSON is invalid, or missing a 'name' property")
    elif content_type == 'application/octet-stream':
        name = request.data
    elif content_type == 'text/plain':
        name = request.data
    elif content_type == 'application/x-www-form-urlencoded':
        name = request.form.get('name')
    else:
        raise ValueError("Unknown content type: {}".format(content_type))
    return 'Hello {}!'.format(escape(name))

Also you can handle HTTP Method such as GET,POST etc [3].

awfullyCold
  • 102
  • 1
  • 10
  • 1
    The question wasn't about how to write a GCP cloud function or handle request header. it was how to find and inspect request headers without explicitly logging them. – John Otu Apr 09 '21 at 01:37