简体   繁体   中英

How can i get request IP address from Google Cloud Logging using Python?

Using the google-cloud-logging module for Python, I can iterate through log messages for my GAE app, and I'd like to list the requesting IP address for each item in Request Log. The official docs don't mention how, and hack through the source code doesn't give me much hope since the log entries are mostly TextEntry with few object properties.

My code is like this:

logging_client = logging.Client()
logger = logging_client.logger('projects/MYPROJECT/logs/appengine.googleapis.com%2Frequest_log')
for entry in logging_client.list_entries():
    timestamp = entry.timestamp.isoformat()
    print("* {}, {}: {}".format(timestamp, type(entry), entry))

When looking at the same logs in the Google Cloud Console, I see a protoPayload.ip field for each log entry - that's exactly the field I hope to extract.

This is not currently possible since the Python client library for Stackdriver Logging doesn't support this feature yet. As you can check in the documentation for theEntry object and its code it is not possible to retrieve the section that contains the Ip of the caller.

However you can do a trick by logging this value yourself with in each call to your App Engine service and therefore you could be able to retrieve it. The value of the caller IP is in the 'X-Appengine-User-Ip' header. You can use this code as an example on how to get it:

from flask import Flask
from flask import request

app = Flask(__name__)


@app.route('/')
def hello_world():
    ip = request.headers['X-Appengine-User-Ip']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM