|
| 1 | +# Copyright 2019 Google, LLC. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from flask import Flask, request |
| 16 | +import json |
| 17 | +import os |
| 18 | +import sys |
| 19 | + |
| 20 | +app = Flask(__name__) |
| 21 | + |
| 22 | + |
| 23 | +@app.route('/', methods=['GET']) |
| 24 | +def index(): |
| 25 | + PROJECT = os.environ['GOOGLE_CLOUD_PROJECT'] |
| 26 | + |
| 27 | + # [START run_manual_logging] |
| 28 | + # Uncomment and populate this variable in your code: |
| 29 | + # PROJECT = 'The project ID of your Cloud Run service'; |
| 30 | + |
| 31 | + # Build structured log messages as an object. |
| 32 | + global_log_fields = {} |
| 33 | + |
| 34 | + # Add log correlation to nest all log messages |
| 35 | + # beneath request log in Log Viewer. |
| 36 | + trace_header = request.headers.get('X-Cloud-Trace-Context') |
| 37 | + |
| 38 | + if trace_header and PROJECT: |
| 39 | + trace = trace_header.split('/') |
| 40 | + global_log_fields['logging.googleapis.com/trace'] = ( |
| 41 | + f"projects/{PROJECT}/traces/{trace[0]}") |
| 42 | + |
| 43 | + # Complete a structured log entry. |
| 44 | + entry = dict(severity='NOTICE', |
| 45 | + message='This is the default display field.', |
| 46 | + # Log viewer accesses 'component' as jsonPayload.component'. |
| 47 | + component='arbitrary-property', |
| 48 | + **global_log_fields) |
| 49 | + |
| 50 | + print(json.dumps(entry)) |
| 51 | + # [END run_manual_logging] |
| 52 | + |
| 53 | + # Flush the stdout to avoid log buffering. |
| 54 | + sys.stdout.flush() |
| 55 | + |
| 56 | + return 'Hello Logger!' |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == '__main__': |
| 60 | + PORT = int(os.getenv('PORT')) if os.getenv('PORT') else 8080 |
| 61 | + |
| 62 | + # This is used when running locally. Gunicorn is used to run the |
| 63 | + # application on Cloud Run. See entrypoint in Dockerfile. |
| 64 | + app.run(host='127.0.0.1', port=PORT, debug=True) |
0 commit comments