From c5217f9439b4af5614732e71547059332c2b461b Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Thu, 4 Aug 2016 10:39:35 -0700 Subject: [PATCH 01/52] Update logging samples to fit new style guide and match Node.js samples. [(#435)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/435) --- samples/snippets/README.md | 36 ++++++++ samples/snippets/export.py | 144 ++++++++++++++++++++++++++++++ samples/snippets/export_test.py | 71 +++++++++++++++ samples/snippets/requirements.txt | 1 + samples/snippets/snippets.py | 106 ++++++++++++++++++++++ samples/snippets/snippets_test.py | 45 ++++++++++ 6 files changed, 403 insertions(+) create mode 100644 samples/snippets/README.md create mode 100644 samples/snippets/export.py create mode 100644 samples/snippets/export_test.py create mode 100644 samples/snippets/requirements.txt create mode 100644 samples/snippets/snippets.py create mode 100644 samples/snippets/snippets_test.py diff --git a/samples/snippets/README.md b/samples/snippets/README.md new file mode 100644 index 000000000..c9042db88 --- /dev/null +++ b/samples/snippets/README.md @@ -0,0 +1,36 @@ +# Stackdriver Logging v2 API Samples + +`snippets.py` is a simple command-line program to demonstrate writing to a log, +listing its entries, and deleting it. + +`export.py` demonstrates how to interact with sinks which are used to export +logs to Google Cloud Storage, Cloud Pub/Sub, or BigQuery. The sample uses +Google Cloud Storage, but can be easily adapted for other outputs. + + + + +## Prerequisites + +All samples require a [Google Cloud Project](https://console.cloud.google.com). + +To run `export.py`, you will also need a Google Cloud Storage Bucket. + + gsutil mb gs://[YOUR_PROJECT_ID] + +You must add Cloud Logging as an owner to the bucket. To do so, add +`cloud-logs@google.com` as an owner to the bucket. See the +[exportings logs](https://cloud.google.com/logging/docs/export/configure_export#configuring_log_sinks) +docs for complete details. + +# Running locally + +Use the [Cloud SDK](https://cloud.google.com/sdk) to provide authentication: + + gcloud beta auth application-default login + +Run the samples: + + python snippets.py -h + python export.py -h + diff --git a/samples/snippets/export.py b/samples/snippets/export.py new file mode 100644 index 000000000..b24dd9878 --- /dev/null +++ b/samples/snippets/export.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python + +# Copyright 2016 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse + +from gcloud import logging + + +def list_sinks(): + """Lists all sinks.""" + logging_client = logging.Client() + + sinks = [] + token = None + while True: + new_sinks, token = logging_client.list_sinks(page_token=token) + sinks.extend(new_sinks) + if token is None: + break + + if not sinks: + print('No sinks.') + + for sink in sinks: + print('{}: {} -> {}'.format(sink.name, sink.filter_, sink.destination)) + + +def create_sink(sink_name, destination_bucket, filter_): + """Creates a sink to export logs to the given Cloud Storage bucket. + + The filter determines which logs this sink matches and will be exported + to the destination. For example a filter of 'severity>=INFO' will send + all logs that have a severity of INFO or greater to the destination. + See https://cloud.google.com/logging/docs/view/advanced_filters for more + filter information. + """ + logging_client = logging.Client() + + # The destination can be a Cloud Storage bucket, a Cloud Pub/Sub topic, + # or a BigQuery dataset. In this case, it is a Cloud Storage Bucket. + # See https://cloud.google.com/logging/docs/api/tasks/exporting-logs for + # information on the destination format. + destination = 'storage.googleapis.com/{bucket}'.format( + bucket=destination_bucket) + + sink = logging_client.sink( + sink_name, + filter_, + destination) + + if sink.exists(): + print('Sink {} already exists.'.format(sink.name)) + return + + sink.create() + print('Created sink {}'.format(sink.name)) + + +def update_sink(sink_name, filter_): + """Changes a sink's filter. + + The filter determines which logs this sink matches and will be exported + to the destination. For example a filter of 'severity>=INFO' will send + all logs that have a severity of INFO or greater to the destination. + See https://cloud.google.com/logging/docs/view/advanced_filters for more + filter information. + """ + logging_client = logging.Client() + sink = logging_client.sink(sink_name) + + sink.reload() + + sink.filter_ = filter_ + print('Updated sink {}'.format(sink.name)) + sink.update() + # [END update] + + +def delete_sink(sink_name): + """Deletes a sink.""" + logging_client = logging.Client() + sink = logging_client.sink(sink_name) + + sink.delete() + + print('Deleted sink {}'.format(sink.name)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter + ) + + subparsers = parser.add_subparsers(dest='command') + subparsers.add_parser('list', help=list_sinks.__doc__) + + create_parser = subparsers.add_parser('create', help=list_sinks.__doc__) + create_parser.add_argument( + 'sink_name', + help='Name of the log export sink.') + create_parser.add_argument( + 'destination_bucket', + help='Cloud Storage bucket where logs will be exported.') + create_parser.add_argument( + 'filter', + help='The filter used to match logs.') + + update_parser = subparsers.add_parser('update', help=update_sink.__doc__) + update_parser.add_argument( + 'sink_name', + help='Name of the log export sink.') + update_parser.add_argument( + 'filter', + help='The filter used to match logs.') + + delete_parser = subparsers.add_parser('delete', help=delete_sink.__doc__) + delete_parser.add_argument( + 'sink_name', + help='Name of the log export sink.') + + args = parser.parse_args() + + if args.command == 'list': + list_sinks() + elif args.command == 'create': + create_sink(args.sink_name, args.destination_bucket, args.filter) + elif args.command == 'update': + update_sink(args.sink_name, args.filter) + elif args.command == 'delete': + delete_sink(args.sink_name) diff --git a/samples/snippets/export_test.py b/samples/snippets/export_test.py new file mode 100644 index 000000000..b59c717ac --- /dev/null +++ b/samples/snippets/export_test.py @@ -0,0 +1,71 @@ +# Copyright 2016 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import export +from gcloud import logging +from gcp.testing import eventually_consistent +import pytest + +TEST_SINK_NAME = 'example_sink' +TEST_SINK_FILTER = 'severity>=CRITICAL' + + +@pytest.fixture +def example_sink(cloud_config): + client = logging.Client() + + sink = client.sink( + TEST_SINK_NAME, + TEST_SINK_FILTER, + 'storage.googleapis.com/{bucket}'.format( + bucket=cloud_config.storage_bucket)) + + if sink.exists(): + sink.delete() + + sink.create() + + return sink + + +def test_list(example_sink, capsys): + @eventually_consistent.call + def _(): + export.list_sinks() + out, _ = capsys.readouterr() + assert example_sink.name in out + + +def test_create(cloud_config, capsys): + export.create_sink( + TEST_SINK_NAME, + TEST_SINK_FILTER, + 'storage.googleapis.com/{bucket}'.format( + bucket=cloud_config.storage_bucket)) + + out, _ = capsys.readouterr() + assert TEST_SINK_NAME in out + + +def test_update(example_sink, capsys): + updated_filter = 'severity>=INFO' + export.update_sink(TEST_SINK_NAME, updated_filter) + + example_sink.reload() + assert example_sink.filter_ == updated_filter + + +def test_delete(example_sink, capsys): + export.delete_sink(TEST_SINK_NAME) + assert not example_sink.exists() diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt new file mode 100644 index 000000000..868847aeb --- /dev/null +++ b/samples/snippets/requirements.txt @@ -0,0 +1 @@ +gcloud==0.17.0 diff --git a/samples/snippets/snippets.py b/samples/snippets/snippets.py new file mode 100644 index 000000000..f73143ec8 --- /dev/null +++ b/samples/snippets/snippets.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python + +# Copyright 2016 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""This application demonstrates how to perform basic operations on logs and +log entries with Stackdriver Logging. + +For more information, see the README.md under /logging and the +documentation at https://cloud.google.com/logging/docs. +""" + +import argparse + +from gcloud import logging + + +def write_entry(logger_name): + """Writes log entries to the given logger.""" + logging_client = logging.Client() + + # This log can be found in the Cloud Logging console under 'Custom Logs'. + logger = logging_client.logger(logger_name) + + # Make a simple text log + logger.log_text('Hello, world!') + + # Simple text log with severity. + logger.log_text('Goodbye, world!', severity='ERROR') + + # Struct log. The struct can be any JSON-serializable dictionary. + logger.log_struct({ + 'name': 'King Arthur', + 'quest': 'Find the Holy Grail', + 'favorite_color': 'Blue' + }) + + print('Wrote logs to {}.'.format(logger.name)) + + +def list_entries(logger_name): + """Lists the most recent entries for a given logger.""" + logging_client = logging.Client() + logger = logging_client.logger(logger_name) + + print('Listing entries for logger {}:'.format(logger.name)) + + entries = [] + page_token = None + + while True: + new_entries, page_token = logger.list_entries(page_token=page_token) + entries.extend(new_entries) + if not page_token: + break + + for entry in entries: + timestamp = entry.timestamp.isoformat() + print('* {}: {}'.format + (timestamp, entry.payload)) + + +def delete_logger(logger_name): + """Deletes a logger and all its entries. + + Note that a deletion can take several minutes to take effect. + """ + logging_client = logging.Client() + logger = logging_client.logger(logger_name) + + logger.delete() + + print('Deleted all logging entries for {}'.format(logger.name)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument( + 'logger_name', help='Logger name', default='example_log') + subparsers = parser.add_subparsers(dest='command') + subparsers.add_parser('list', help=list_entries.__doc__) + subparsers.add_parser('write', help=write_entry.__doc__) + subparsers.add_parser('delete', help=delete_logger.__doc__) + + args = parser.parse_args() + + if args.command == 'list': + list_entries(args.logger_name) + elif args.command == 'write': + write_entry(args.logger_name) + elif args.command == 'delete': + delete_logger(args.logger_name) diff --git a/samples/snippets/snippets_test.py b/samples/snippets/snippets_test.py new file mode 100644 index 000000000..6a1004d46 --- /dev/null +++ b/samples/snippets/snippets_test.py @@ -0,0 +1,45 @@ +# Copyright 2016 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from gcloud import logging +from gcp.testing import eventually_consistent +import pytest +import snippets + +TEST_LOGGER_NAME = 'example_log' + + +@pytest.fixture +def example_log(): + client = logging.Client() + logger = client.logger(TEST_LOGGER_NAME) + text = 'Hello, world.' + logger.log_text(text) + return text + + +def test_list(example_log, capsys): + @eventually_consistent.call + def _(): + snippets.list_entries(TEST_LOGGER_NAME) + out, _ = capsys.readouterr() + assert example_log in out + + +def test_write(): + snippets.write_entry(TEST_LOGGER_NAME) + + +def test_delete(): + snippets.delete_logger(TEST_LOGGER_NAME) From 9401475d2974475e0b9feef92907af55e0e6f7fe Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Thu, 4 Aug 2016 11:23:52 -0700 Subject: [PATCH 02/52] Fix test conflict. Change-Id: I67e149dc43ebdb11144ac3839e062aa4668ebb2e --- samples/snippets/export_test.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/samples/snippets/export_test.py b/samples/snippets/export_test.py index b59c717ac..6b7a5461e 100644 --- a/samples/snippets/export_test.py +++ b/samples/snippets/export_test.py @@ -48,6 +48,12 @@ def _(): def test_create(cloud_config, capsys): + # Delete the sink if it exists, otherwise the test will fail in conflit. + client = logging.Client() + sink = client.sink(TEST_SINK_NAME) + if sink.exists(): + sink.delete() + export.create_sink( TEST_SINK_NAME, TEST_SINK_FILTER, @@ -56,6 +62,7 @@ def test_create(cloud_config, capsys): out, _ = capsys.readouterr() assert TEST_SINK_NAME in out + assert sink.exists() def test_update(example_sink, capsys): From c94e662c73ed1a632ca7a01cc20034229e325036 Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Thu, 4 Aug 2016 13:31:20 -0700 Subject: [PATCH 03/52] Fix logging test. Change-Id: I866edcc956fda2265dd7af7b774336930ec6a151 --- samples/snippets/export_test.py | 56 ++++++++++++++++++++------------- 1 file changed, 34 insertions(+), 22 deletions(-) diff --git a/samples/snippets/export_test.py b/samples/snippets/export_test.py index 6b7a5461e..5a0218aaa 100644 --- a/samples/snippets/export_test.py +++ b/samples/snippets/export_test.py @@ -12,31 +12,42 @@ # See the License for the specific language governing permissions and # limitations under the License. +import random +import string + import export from gcloud import logging from gcp.testing import eventually_consistent import pytest -TEST_SINK_NAME = 'example_sink' +TEST_SINK_NAME_TMPL = 'example_sink_{}' TEST_SINK_FILTER = 'severity>=CRITICAL' -@pytest.fixture +def _random_id(): + return ''.join( + random.choice(string.ascii_uppercase + string.digits) + for _ in range(6)) + + +@pytest.yield_fixture def example_sink(cloud_config): client = logging.Client() sink = client.sink( - TEST_SINK_NAME, + TEST_SINK_NAME_TMPL.format(_random_id()), TEST_SINK_FILTER, 'storage.googleapis.com/{bucket}'.format( bucket=cloud_config.storage_bucket)) - if sink.exists(): - sink.delete() - sink.create() - return sink + yield sink + + try: + sink.delete() + except: + pass def test_list(example_sink, capsys): @@ -48,31 +59,32 @@ def _(): def test_create(cloud_config, capsys): - # Delete the sink if it exists, otherwise the test will fail in conflit. - client = logging.Client() - sink = client.sink(TEST_SINK_NAME) - if sink.exists(): - sink.delete() - - export.create_sink( - TEST_SINK_NAME, - TEST_SINK_FILTER, - 'storage.googleapis.com/{bucket}'.format( - bucket=cloud_config.storage_bucket)) + sink_name = TEST_SINK_NAME_TMPL.format(_random_id()) + + try: + export.create_sink( + sink_name, + cloud_config.storage_bucket, + TEST_SINK_FILTER) + # Clean-up the temporary sink. + finally: + try: + logging.Client().sink(sink_name).delete() + except: + pass out, _ = capsys.readouterr() - assert TEST_SINK_NAME in out - assert sink.exists() + assert sink_name in out def test_update(example_sink, capsys): updated_filter = 'severity>=INFO' - export.update_sink(TEST_SINK_NAME, updated_filter) + export.update_sink(example_sink.name, updated_filter) example_sink.reload() assert example_sink.filter_ == updated_filter def test_delete(example_sink, capsys): - export.delete_sink(TEST_SINK_NAME) + export.delete_sink(example_sink.name) assert not example_sink.exists() From 22afe695f4edb1df14774b0f9707eb4994546fdd Mon Sep 17 00:00:00 2001 From: DPE bot Date: Tue, 16 Aug 2016 13:32:42 -0700 Subject: [PATCH 04/52] Auto-update dependencies. [(#456)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/456) --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 868847aeb..2beeafe63 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -gcloud==0.17.0 +gcloud==0.18.1 From 8ae5f1089505d27117f80019719b9ac8fcb75487 Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Fri, 19 Aug 2016 13:56:28 -0700 Subject: [PATCH 05/52] Fix import order lint errors Change-Id: Ieaf7237fc6f925daec46a07d2e81a452b841198a --- samples/snippets/export_test.py | 3 ++- samples/snippets/snippets_test.py | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/samples/snippets/export_test.py b/samples/snippets/export_test.py index 5a0218aaa..d4dfd681e 100644 --- a/samples/snippets/export_test.py +++ b/samples/snippets/export_test.py @@ -15,11 +15,12 @@ import random import string -import export from gcloud import logging from gcp.testing import eventually_consistent import pytest +import export + TEST_SINK_NAME_TMPL = 'example_sink_{}' TEST_SINK_FILTER = 'severity>=CRITICAL' diff --git a/samples/snippets/snippets_test.py b/samples/snippets/snippets_test.py index 6a1004d46..f41f52fb5 100644 --- a/samples/snippets/snippets_test.py +++ b/samples/snippets/snippets_test.py @@ -15,6 +15,7 @@ from gcloud import logging from gcp.testing import eventually_consistent import pytest + import snippets TEST_LOGGER_NAME = 'example_log' From 052f3e5f308f930d09e0a6c44d644a26e54528ff Mon Sep 17 00:00:00 2001 From: DPE bot Date: Fri, 23 Sep 2016 09:48:46 -0700 Subject: [PATCH 06/52] Auto-update dependencies. [(#540)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/540) --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 2beeafe63..dfb42aaaa 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -gcloud==0.18.1 +gcloud==0.18.2 From f53c654b0e0e6f6b2651eb22542b44bc590af517 Mon Sep 17 00:00:00 2001 From: DPE bot Date: Mon, 26 Sep 2016 11:34:45 -0700 Subject: [PATCH 07/52] Auto-update dependencies. [(#542)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/542) --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index dfb42aaaa..97a207d3a 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -gcloud==0.18.2 +gcloud==0.18.3 From 49cf3185ada9f428aea03eec6f7ef9f6ace2e401 Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Thu, 29 Sep 2016 20:51:47 -0700 Subject: [PATCH 08/52] Move to google-cloud [(#544)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/544) --- samples/snippets/export.py | 2 +- samples/snippets/export_test.py | 2 +- samples/snippets/requirements.txt | 2 +- samples/snippets/snippets.py | 2 +- samples/snippets/snippets_test.py | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/snippets/export.py b/samples/snippets/export.py index b24dd9878..20367c274 100644 --- a/samples/snippets/export.py +++ b/samples/snippets/export.py @@ -16,7 +16,7 @@ import argparse -from gcloud import logging +from google.cloud import logging def list_sinks(): diff --git a/samples/snippets/export_test.py b/samples/snippets/export_test.py index d4dfd681e..8f1c299d7 100644 --- a/samples/snippets/export_test.py +++ b/samples/snippets/export_test.py @@ -15,8 +15,8 @@ import random import string -from gcloud import logging from gcp.testing import eventually_consistent +from google.cloud import logging import pytest import export diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 97a207d3a..303f67c09 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -gcloud==0.18.3 +google-cloud-logging==0.20.0 diff --git a/samples/snippets/snippets.py b/samples/snippets/snippets.py index f73143ec8..0280cfbe4 100644 --- a/samples/snippets/snippets.py +++ b/samples/snippets/snippets.py @@ -23,7 +23,7 @@ import argparse -from gcloud import logging +from google.cloud import logging def write_entry(logger_name): diff --git a/samples/snippets/snippets_test.py b/samples/snippets/snippets_test.py index f41f52fb5..86eac1180 100644 --- a/samples/snippets/snippets_test.py +++ b/samples/snippets/snippets_test.py @@ -12,8 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -from gcloud import logging from gcp.testing import eventually_consistent +from google.cloud import logging import pytest import snippets From 4271a026bb4f73d368b83d8971b49d40b900488b Mon Sep 17 00:00:00 2001 From: Jason Dobry Date: Wed, 5 Oct 2016 09:56:04 -0700 Subject: [PATCH 09/52] Add new "quickstart" samples [(#547)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/547) --- samples/snippets/quickstart.py | 42 ++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 samples/snippets/quickstart.py diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py new file mode 100644 index 000000000..19409c776 --- /dev/null +++ b/samples/snippets/quickstart.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python + +# Copyright 2016 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +def run_quickstart(): + # [START logging_quickstart] + # Imports the Google Cloud client library + from google.cloud import logging + + # Instantiates a client + logging_client = logging.Client() + + # The name of the log to write to + log_name = 'my-log' + # Selects the log to write to + logger = logging_client.logger(log_name) + + # The data to log + text = 'Hello, world!' + + # Writes the log entry + logger.log_text(text) + + print('Logged: {}'.format(text)) + # [END logging_quickstart] + + +if __name__ == '__main__': + run_quickstart() From 7024024076f7b5fb803ed45950f8d45eb66b5bf7 Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Wed, 12 Oct 2016 10:48:57 -0700 Subject: [PATCH 10/52] Quickstart tests [(#569)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/569) * Add tests for quickstarts * Update secrets --- samples/snippets/quickstart_test.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 samples/snippets/quickstart_test.py diff --git a/samples/snippets/quickstart_test.py b/samples/snippets/quickstart_test.py new file mode 100644 index 000000000..1b49cd126 --- /dev/null +++ b/samples/snippets/quickstart_test.py @@ -0,0 +1,22 @@ +# Copyright 2016 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import quickstart + + +def test_quickstart(capsys): + quickstart.run_quickstart() + out, _ = capsys.readouterr() + assert 'Logged' in out From 9aecaa287e5e58843d7ab9ff040d2f06540a7ad4 Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Mon, 24 Oct 2016 11:03:17 -0700 Subject: [PATCH 11/52] Generate readmes for most service samples [(#599)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/599) --- samples/snippets/README.md | 36 -------- samples/snippets/README.rst | 163 +++++++++++++++++++++++++++++++++ samples/snippets/README.rst.in | 26 ++++++ 3 files changed, 189 insertions(+), 36 deletions(-) delete mode 100644 samples/snippets/README.md create mode 100644 samples/snippets/README.rst create mode 100644 samples/snippets/README.rst.in diff --git a/samples/snippets/README.md b/samples/snippets/README.md deleted file mode 100644 index c9042db88..000000000 --- a/samples/snippets/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# Stackdriver Logging v2 API Samples - -`snippets.py` is a simple command-line program to demonstrate writing to a log, -listing its entries, and deleting it. - -`export.py` demonstrates how to interact with sinks which are used to export -logs to Google Cloud Storage, Cloud Pub/Sub, or BigQuery. The sample uses -Google Cloud Storage, but can be easily adapted for other outputs. - - - - -## Prerequisites - -All samples require a [Google Cloud Project](https://console.cloud.google.com). - -To run `export.py`, you will also need a Google Cloud Storage Bucket. - - gsutil mb gs://[YOUR_PROJECT_ID] - -You must add Cloud Logging as an owner to the bucket. To do so, add -`cloud-logs@google.com` as an owner to the bucket. See the -[exportings logs](https://cloud.google.com/logging/docs/export/configure_export#configuring_log_sinks) -docs for complete details. - -# Running locally - -Use the [Cloud SDK](https://cloud.google.com/sdk) to provide authentication: - - gcloud beta auth application-default login - -Run the samples: - - python snippets.py -h - python export.py -h - diff --git a/samples/snippets/README.rst b/samples/snippets/README.rst new file mode 100644 index 000000000..2647c799c --- /dev/null +++ b/samples/snippets/README.rst @@ -0,0 +1,163 @@ +.. This file is automatically generated. Do not edit this file directly. + +Stackdriver Logging Python Samples +=============================================================================== + +This directory contains samples for Stackdriver Logging. `Stackdriver Logging`_ allows you to store, search, analyze, monitor, and alert on log data and events from Google Cloud Platform and Amazon Web Services. + + + + +.. _Stackdriver Logging: https://cloud.google.com/logging/docs + +Setup +------------------------------------------------------------------------------- + + +Authentication +++++++++++++++ + +Authentication is typically done through `Application Default Credentials`_, +which means you do not have to change the code to authenticate as long as +your environment has credentials. You have a few options for setting up +authentication: + +#. When running locally, use the `Google Cloud SDK`_ + + .. code-block:: bash + + gcloud beta auth application-default login + + +#. When running on App Engine or Compute Engine, credentials are already + set-up. However, you may need to configure your Compute Engine instance + with `additional scopes`_. + +#. You can create a `Service Account key file`_. This file can be used to + authenticate to Google Cloud Platform services from any environment. To use + the file, set the ``GOOGLE_APPLICATION_CREDENTIALS`` environment variable to + the path to the key file, for example: + + .. code-block:: bash + + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service_account.json + +.. _Application Default Credentials: https://cloud.google.com/docs/authentication#getting_credentials_for_server-centric_flow +.. _additional scopes: https://cloud.google.com/compute/docs/authentication#using +.. _Service Account key file: https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount + +Install Dependencies +++++++++++++++++++++ + +#. Install `pip`_ and `virtualenv`_ if you do not already have them. + +#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. + + .. code-block:: bash + + $ virtualenv env + $ source env/bin/activate + +#. Install the dependencies needed to run the samples. + + .. code-block:: bash + + $ pip install -r requirements.txt + +.. _pip: https://pip.pypa.io/ +.. _virtualenv: https://virtualenv.pypa.io/ + +Samples +------------------------------------------------------------------------------- + +Quickstart ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + + + +To run this sample: + +.. code-block:: bash + + $ python quickstart.py + + +Snippets ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + + + +To run this sample: + +.. code-block:: bash + + $ python snippets.py + + usage: snippets.py [-h] logger_name {list,write,delete} ... + + This application demonstrates how to perform basic operations on logs and + log entries with Stackdriver Logging. + + For more information, see the README.md under /logging and the + documentation at https://cloud.google.com/logging/docs. + + positional arguments: + logger_name Logger name + {list,write,delete} + list Lists the most recent entries for a given logger. + write Writes log entries to the given logger. + delete Deletes a logger and all its entries. Note that a + deletion can take several minutes to take effect. + + optional arguments: + -h, --help show this help message and exit + + +Export ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + + + +To run this sample: + +.. code-block:: bash + + $ python export.py + + usage: export.py [-h] {list,create,update,delete} ... + + positional arguments: + {list,create,update,delete} + list Lists all sinks. + create Lists all sinks. + update Changes a sink's filter. The filter determines which + logs this sink matches and will be exported to the + destination. For example a filter of 'severity>=INFO' + will send all logs that have a severity of INFO or + greater to the destination. See https://cloud.google.c + om/logging/docs/view/advanced_filters for more filter + information. + delete Deletes a sink. + + optional arguments: + -h, --help show this help message and exit + + + + +The client library +------------------------------------------------------------------------------- + +This sample uses the `Google Cloud Client Library for Python`_. +You can read the documentation for more details on API usage and use GitHub +to `browse the source`_ and `report issues`_. + +.. Google Cloud Client Library for Python: + https://googlecloudplatform.github.io/google-cloud-python/ +.. browse the source: + https://github.com/GoogleCloudPlatform/google-cloud-python +.. report issues: + https://github.com/GoogleCloudPlatform/google-cloud-python/issues + + +.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/samples/snippets/README.rst.in b/samples/snippets/README.rst.in new file mode 100644 index 000000000..50862fa1d --- /dev/null +++ b/samples/snippets/README.rst.in @@ -0,0 +1,26 @@ +# This file is used to generate README.rst + +product: + name: Stackdriver Logging + short_name: Stackdriver Logging + url: https://cloud.google.com/logging/docs + description: > + `Stackdriver Logging`_ allows you to store, search, analyze, monitor, + and alert on log data and events from Google Cloud Platform and Amazon + Web Services. + +setup: +- auth +- install_deps + +samples: +- name: Quickstart + file: quickstart.py +- name: Snippets + file: snippets.py + show_help: true +- name: Export + file: export.py + show_help: true + +cloud_client_library: true From 957eb575ebb65b34a3d06b1919b1574fd24f7cc8 Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Tue, 15 Nov 2016 14:58:27 -0800 Subject: [PATCH 12/52] Update samples to support latest Google Cloud Python [(#656)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/656) --- samples/snippets/export.py | 8 +------- samples/snippets/requirements.txt | 2 +- samples/snippets/snippets.py | 11 +---------- 3 files changed, 3 insertions(+), 18 deletions(-) diff --git a/samples/snippets/export.py b/samples/snippets/export.py index 20367c274..f8c1f0c5f 100644 --- a/samples/snippets/export.py +++ b/samples/snippets/export.py @@ -23,13 +23,7 @@ def list_sinks(): """Lists all sinks.""" logging_client = logging.Client() - sinks = [] - token = None - while True: - new_sinks, token = logging_client.list_sinks(page_token=token) - sinks.extend(new_sinks) - if token is None: - break + sinks = list(logging_client.list_sinks()) if not sinks: print('No sinks.') diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 303f67c09..ce5d85c60 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==0.20.0 +google-cloud-logging==0.21.0 diff --git a/samples/snippets/snippets.py b/samples/snippets/snippets.py index 0280cfbe4..8a31066fa 100644 --- a/samples/snippets/snippets.py +++ b/samples/snippets/snippets.py @@ -56,16 +56,7 @@ def list_entries(logger_name): print('Listing entries for logger {}:'.format(logger.name)) - entries = [] - page_token = None - - while True: - new_entries, page_token = logger.list_entries(page_token=page_token) - entries.extend(new_entries) - if not page_token: - break - - for entry in entries: + for entry in logger.list_entries(): timestamp = entry.timestamp.isoformat() print('* {}: {}'.format (timestamp, entry.payload)) From d270cbf50d16812e43a6e330733b4c6963d025ff Mon Sep 17 00:00:00 2001 From: DPE bot Date: Tue, 13 Dec 2016 09:54:02 -0800 Subject: [PATCH 13/52] Auto-update dependencies. [(#715)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/715) --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index ce5d85c60..4b9f9fcb7 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==0.21.0 +google-cloud-logging==0.22.0 From ec152a2da740ae322cc53fd2cdc33c19db55ab25 Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Tue, 4 Apr 2017 16:08:30 -0700 Subject: [PATCH 14/52] Remove cloud config fixture [(#887)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/887) * Remove cloud config fixture * Fix client secrets * Fix bigtable instance --- samples/snippets/export_test.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/samples/snippets/export_test.py b/samples/snippets/export_test.py index 8f1c299d7..99b78f8e4 100644 --- a/samples/snippets/export_test.py +++ b/samples/snippets/export_test.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import os import random import string @@ -21,6 +22,7 @@ import export +BUCKET = os.environ['CLOUD_STORAGE_BUCKET'] TEST_SINK_NAME_TMPL = 'example_sink_{}' TEST_SINK_FILTER = 'severity>=CRITICAL' @@ -32,14 +34,13 @@ def _random_id(): @pytest.yield_fixture -def example_sink(cloud_config): +def example_sink(): client = logging.Client() sink = client.sink( TEST_SINK_NAME_TMPL.format(_random_id()), TEST_SINK_FILTER, - 'storage.googleapis.com/{bucket}'.format( - bucket=cloud_config.storage_bucket)) + 'storage.googleapis.com/{bucket}'.format(bucket=BUCKET)) sink.create() @@ -59,13 +60,13 @@ def _(): assert example_sink.name in out -def test_create(cloud_config, capsys): +def test_create(capsys): sink_name = TEST_SINK_NAME_TMPL.format(_random_id()) try: export.create_sink( sink_name, - cloud_config.storage_bucket, + BUCKET, TEST_SINK_FILTER) # Clean-up the temporary sink. finally: From 68078a35c4ce085a431d366db2973df622d9a1ab Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Wed, 12 Apr 2017 15:14:35 -0700 Subject: [PATCH 15/52] Fix reference to our testing tools --- samples/snippets/export_test.py | 2 +- samples/snippets/snippets_test.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/snippets/export_test.py b/samples/snippets/export_test.py index 99b78f8e4..b53b8978f 100644 --- a/samples/snippets/export_test.py +++ b/samples/snippets/export_test.py @@ -16,7 +16,7 @@ import random import string -from gcp.testing import eventually_consistent +from gcp_devrel.testing import eventually_consistent from google.cloud import logging import pytest diff --git a/samples/snippets/snippets_test.py b/samples/snippets/snippets_test.py index 86eac1180..f22fbc8f1 100644 --- a/samples/snippets/snippets_test.py +++ b/samples/snippets/snippets_test.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from gcp.testing import eventually_consistent +from gcp_devrel.testing import eventually_consistent from google.cloud import logging import pytest From 006a15dd52e46a8c179353c574c8533509db8c8a Mon Sep 17 00:00:00 2001 From: DPE bot Date: Mon, 24 Apr 2017 13:12:09 -0700 Subject: [PATCH 16/52] Auto-update dependencies. [(#914)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/914) * Auto-update dependencies. * xfail the error reporting test * Fix lint --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 4b9f9fcb7..4942b24ad 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==0.22.0 +google-cloud-logging==1.0.0 From e387e6533169937eec089dc77b6bdecc0c056bf1 Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Thu, 27 Apr 2017 09:54:41 -0700 Subject: [PATCH 17/52] Re-generate all readmes --- samples/snippets/README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/README.rst b/samples/snippets/README.rst index 2647c799c..767abc103 100644 --- a/samples/snippets/README.rst +++ b/samples/snippets/README.rst @@ -26,7 +26,7 @@ authentication: .. code-block:: bash - gcloud beta auth application-default login + gcloud auth application-default login #. When running on App Engine or Compute Engine, credentials are already From aa308d638abb93eda636c7ad26fe178282e17438 Mon Sep 17 00:00:00 2001 From: Bill Prin Date: Tue, 23 May 2017 17:01:25 -0700 Subject: [PATCH 18/52] Fix README rst links [(#962)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/962) * Fix README rst links * Update all READMEs --- samples/snippets/README.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/samples/snippets/README.rst b/samples/snippets/README.rst index 767abc103..a9ff67afc 100644 --- a/samples/snippets/README.rst +++ b/samples/snippets/README.rst @@ -152,11 +152,11 @@ This sample uses the `Google Cloud Client Library for Python`_. You can read the documentation for more details on API usage and use GitHub to `browse the source`_ and `report issues`_. -.. Google Cloud Client Library for Python: +.. _Google Cloud Client Library for Python: https://googlecloudplatform.github.io/google-cloud-python/ -.. browse the source: +.. _browse the source: https://github.com/GoogleCloudPlatform/google-cloud-python -.. report issues: +.. _report issues: https://github.com/GoogleCloudPlatform/google-cloud-python/issues From 148d61e4449b355520bb99f082cce742bb7dd73b Mon Sep 17 00:00:00 2001 From: DPE bot Date: Tue, 27 Jun 2017 12:41:15 -0700 Subject: [PATCH 19/52] Auto-update dependencies. [(#1004)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1004) * Auto-update dependencies. * Fix natural language samples * Fix pubsub iam samples * Fix language samples * Fix bigquery samples --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 4942b24ad..8b01c04cb 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==1.0.0 +google-cloud-logging==1.1.0 From 14786d6e83bfda24b7a70ebdf156713811cb156b Mon Sep 17 00:00:00 2001 From: DPE bot Date: Mon, 7 Aug 2017 10:04:55 -0700 Subject: [PATCH 20/52] Auto-update dependencies. [(#1055)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1055) * Auto-update dependencies. * Explicitly use latest bigtable client Change-Id: Id71e9e768f020730e4ca9514a0d7ebaa794e7d9e * Revert language update for now Change-Id: I8867f154e9a5aae00d0047c9caf880e5e8f50c53 * Remove pdb. smh Change-Id: I5ff905fadc026eebbcd45512d4e76e003e3b2b43 --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 8b01c04cb..0cf479d75 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==1.1.0 +google-cloud-logging==1.2.0 From 9dcd1e7533b41a1d8c826a8c210d1baf6b4e9b5a Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Tue, 29 Aug 2017 13:35:20 -0700 Subject: [PATCH 21/52] Fix logging tests Change-Id: I6691c70912b1e1b5993e962a4827a846642feac3 --- samples/snippets/snippets_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/snippets_test.py b/samples/snippets/snippets_test.py index f22fbc8f1..78093781c 100644 --- a/samples/snippets/snippets_test.py +++ b/samples/snippets/snippets_test.py @@ -42,5 +42,5 @@ def test_write(): snippets.write_entry(TEST_LOGGER_NAME) -def test_delete(): +def test_delete(example_log): snippets.delete_logger(TEST_LOGGER_NAME) From 9c986cb56a8b05584518142cfc2747179f49e503 Mon Sep 17 00:00:00 2001 From: DPE bot Date: Tue, 29 Aug 2017 16:53:02 -0700 Subject: [PATCH 22/52] Auto-update dependencies. [(#1093)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1093) * Auto-update dependencies. * Fix storage notification poll sample Change-Id: I6afbc79d15e050531555e4c8e51066996717a0f3 * Fix spanner samples Change-Id: I40069222c60d57e8f3d3878167591af9130895cb * Drop coverage because it's not useful Change-Id: Iae399a7083d7866c3c7b9162d0de244fbff8b522 * Try again to fix flaky logging test Change-Id: I6225c074701970c17c426677ef1935bb6d7e36b4 --- samples/snippets/requirements.txt | 2 +- samples/snippets/snippets_test.py | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 0cf479d75..4a4968528 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==1.2.0 +google-cloud-logging==1.3.0 diff --git a/samples/snippets/snippets_test.py b/samples/snippets/snippets_test.py index 78093781c..480763cdb 100644 --- a/samples/snippets/snippets_test.py +++ b/samples/snippets/snippets_test.py @@ -43,4 +43,6 @@ def test_write(): def test_delete(example_log): - snippets.delete_logger(TEST_LOGGER_NAME) + @eventually_consistent.call + def _(): + snippets.delete_logger(TEST_LOGGER_NAME) From 5e1b0efeeac1bc3b1e6f60482130d0fdfbedb4b4 Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Mon, 18 Sep 2017 11:04:05 -0700 Subject: [PATCH 23/52] Update all generated readme auth instructions [(#1121)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1121) Change-Id: I03b5eaef8b17ac3dc3c0339fd2c7447bd3e11bd2 --- samples/snippets/README.rst | 32 +++++--------------------------- 1 file changed, 5 insertions(+), 27 deletions(-) diff --git a/samples/snippets/README.rst b/samples/snippets/README.rst index a9ff67afc..349787427 100644 --- a/samples/snippets/README.rst +++ b/samples/snippets/README.rst @@ -17,34 +17,12 @@ Setup Authentication ++++++++++++++ -Authentication is typically done through `Application Default Credentials`_, -which means you do not have to change the code to authenticate as long as -your environment has credentials. You have a few options for setting up -authentication: +This sample requires you to have authentication setup. Refer to the +`Authentication Getting Started Guide`_ for instructions on setting up +credentials for applications. -#. When running locally, use the `Google Cloud SDK`_ - - .. code-block:: bash - - gcloud auth application-default login - - -#. When running on App Engine or Compute Engine, credentials are already - set-up. However, you may need to configure your Compute Engine instance - with `additional scopes`_. - -#. You can create a `Service Account key file`_. This file can be used to - authenticate to Google Cloud Platform services from any environment. To use - the file, set the ``GOOGLE_APPLICATION_CREDENTIALS`` environment variable to - the path to the key file, for example: - - .. code-block:: bash - - export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service_account.json - -.. _Application Default Credentials: https://cloud.google.com/docs/authentication#getting_credentials_for_server-centric_flow -.. _additional scopes: https://cloud.google.com/compute/docs/authentication#using -.. _Service Account key file: https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount +.. _Authentication Getting Started Guide: + https://cloud.google.com/docs/authentication/getting-started Install Dependencies ++++++++++++++++++++ From cc7133139b979e77e0f33a423296fede39424ef2 Mon Sep 17 00:00:00 2001 From: michaelawyu Date: Thu, 12 Oct 2017 10:16:11 -0700 Subject: [PATCH 24/52] Added Link to Python Setup Guide [(#1158)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1158) * Update Readme.rst to add Python setup guide As requested in b/64770713. This sample is linked in documentation https://cloud.google.com/bigtable/docs/scaling, and it would make more sense to update the guide here than in the documentation. * Update README.rst * Update README.rst * Update README.rst * Update README.rst * Update README.rst * Update install_deps.tmpl.rst * Updated readmegen scripts and re-generated related README files * Fixed the lint error --- samples/snippets/README.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/samples/snippets/README.rst b/samples/snippets/README.rst index 349787427..74f8dae99 100644 --- a/samples/snippets/README.rst +++ b/samples/snippets/README.rst @@ -27,7 +27,10 @@ credentials for applications. Install Dependencies ++++++++++++++++++++ -#. Install `pip`_ and `virtualenv`_ if you do not already have them. +#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. + + .. _Python Development Environment Setup Guide: + https://cloud.google.com/python/setup #. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. From de4dbfafd435ded7c3903fa4a9b543aea98f87b8 Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Tue, 24 Oct 2017 12:14:35 -0700 Subject: [PATCH 25/52] Fix a few more lint issues Change-Id: I0d420f3053f391fa225e4b8179e45fd1138f5c65 --- samples/snippets/export_test.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/snippets/export_test.py b/samples/snippets/export_test.py index b53b8978f..ea0903905 100644 --- a/samples/snippets/export_test.py +++ b/samples/snippets/export_test.py @@ -48,7 +48,7 @@ def example_sink(): try: sink.delete() - except: + except Exception: pass @@ -72,7 +72,7 @@ def test_create(capsys): finally: try: logging.Client().sink(sink_name).delete() - except: + except Exception: pass out, _ = capsys.readouterr() From 049f1fdc3c61c7518809fa89c52a5f45bbb46661 Mon Sep 17 00:00:00 2001 From: DPE bot Date: Wed, 1 Nov 2017 12:30:10 -0700 Subject: [PATCH 26/52] Auto-update dependencies. [(#1186)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1186) --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 4a4968528..78aa79015 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==1.3.0 +google-cloud-logging==1.4.0 From b1c379a3a74f07d3bf2be298fd87d986cda78b22 Mon Sep 17 00:00:00 2001 From: Andrew Gorcester Date: Tue, 28 Nov 2017 10:21:53 -0800 Subject: [PATCH 27/52] Add sample for standard library logging handler configuration [(#1233)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1233) * Add sample for standard library logging handler configuration * Add handler.py to readme --- samples/snippets/README.rst | 12 +++++++++ samples/snippets/handler.py | 46 ++++++++++++++++++++++++++++++++ samples/snippets/handler_test.py | 22 +++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 samples/snippets/handler.py create mode 100644 samples/snippets/handler_test.py diff --git a/samples/snippets/README.rst b/samples/snippets/README.rst index 74f8dae99..4612fdd05 100644 --- a/samples/snippets/README.rst +++ b/samples/snippets/README.rst @@ -63,6 +63,18 @@ To run this sample: $ python quickstart.py +Handler ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + + + +To run this sample: + +.. code-block:: bash + + $ python handler.py + + Snippets +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ diff --git a/samples/snippets/handler.py b/samples/snippets/handler.py new file mode 100644 index 000000000..9986eab85 --- /dev/null +++ b/samples/snippets/handler.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python + +# Copyright 2016 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +def use_logging_handler(): + # [START logging_handler_setup] + # Imports the Google Cloud client library + import google.cloud.logging + + # Instantiates a client + client = google.cloud.logging.Client() + + # Connects the logger to the root logging handler; by default this captures + # all logs at INFO level and higher + client.setup_logging() + # [END logging_handler_setup] + + # [START logging_handler_usage] + # Imports Python standard library logging + import logging + + # The data to log + text = 'Hello, world!' + + # Emits the data using the standard logging module + logging.warn(text) + # [END logging_handler_usage] + + print('Logged: {}'.format(text)) + + +if __name__ == '__main__': + use_logging_handler() diff --git a/samples/snippets/handler_test.py b/samples/snippets/handler_test.py new file mode 100644 index 000000000..d48ee2e20 --- /dev/null +++ b/samples/snippets/handler_test.py @@ -0,0 +1,22 @@ +# Copyright 2016 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import handler + + +def test_handler(capsys): + handler.use_logging_handler() + out, _ = capsys.readouterr() + assert 'Logged' in out From 51a20c033913b8d5c28c56d21484599d3681df25 Mon Sep 17 00:00:00 2001 From: michaelawyu Date: Thu, 7 Dec 2017 10:34:29 -0800 Subject: [PATCH 28/52] Added "Open in Cloud Shell" buttons to README files [(#1254)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1254) --- samples/snippets/README.rst | 40 +++++++++++++++++++--------------- samples/snippets/README.rst.in | 2 ++ 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/samples/snippets/README.rst b/samples/snippets/README.rst index 4612fdd05..00b7fa91a 100644 --- a/samples/snippets/README.rst +++ b/samples/snippets/README.rst @@ -3,6 +3,10 @@ Stackdriver Logging Python Samples =============================================================================== +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=logging/cloud-client/README.rst + + This directory contains samples for Stackdriver Logging. `Stackdriver Logging`_ allows you to store, search, analyze, monitor, and alert on log data and events from Google Cloud Platform and Amazon Web Services. @@ -54,30 +58,26 @@ Samples Quickstart +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=logging/cloud-client/quickstart.py;logging/cloud-client/README.rst -To run this sample: - -.. code-block:: bash - - $ python quickstart.py - - -Handler -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - To run this sample: .. code-block:: bash - $ python handler.py + $ python quickstart.py Snippets +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=logging/cloud-client/snippets.py;logging/cloud-client/README.rst + + To run this sample: @@ -87,13 +87,13 @@ To run this sample: $ python snippets.py usage: snippets.py [-h] logger_name {list,write,delete} ... - + This application demonstrates how to perform basic operations on logs and log entries with Stackdriver Logging. - + For more information, see the README.md under /logging and the documentation at https://cloud.google.com/logging/docs. - + positional arguments: logger_name Logger name {list,write,delete} @@ -101,14 +101,19 @@ To run this sample: write Writes log entries to the given logger. delete Deletes a logger and all its entries. Note that a deletion can take several minutes to take effect. - + optional arguments: -h, --help show this help message and exit + Export +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=logging/cloud-client/export.py;logging/cloud-client/README.rst + + To run this sample: @@ -118,7 +123,7 @@ To run this sample: $ python export.py usage: export.py [-h] {list,create,update,delete} ... - + positional arguments: {list,create,update,delete} list Lists all sinks. @@ -131,13 +136,14 @@ To run this sample: om/logging/docs/view/advanced_filters for more filter information. delete Deletes a sink. - + optional arguments: -h, --help show this help message and exit + The client library ------------------------------------------------------------------------------- diff --git a/samples/snippets/README.rst.in b/samples/snippets/README.rst.in index 50862fa1d..00fa4b6b8 100644 --- a/samples/snippets/README.rst.in +++ b/samples/snippets/README.rst.in @@ -24,3 +24,5 @@ samples: show_help: true cloud_client_library: true + +folder: logging/cloud-client \ No newline at end of file From ef1fd810fcd4ec0ddc671f102768529908f20150 Mon Sep 17 00:00:00 2001 From: DPE bot Date: Mon, 26 Feb 2018 09:03:37 -0800 Subject: [PATCH 29/52] Auto-update dependencies. [(#1359)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1359) --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 78aa79015..fd8ba2ec4 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==1.4.0 +google-cloud-logging==1.5.0 From 908af21114d53f600a7bc82e20a5161e87013b7b Mon Sep 17 00:00:00 2001 From: DPE bot Date: Mon, 5 Mar 2018 12:28:55 -0800 Subject: [PATCH 30/52] Auto-update dependencies. [(#1377)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1377) * Auto-update dependencies. * Update requirements.txt --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index fd8ba2ec4..b4a1672d3 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==1.5.0 +google-cloud-logging==1.6.0 From afa6c2e4e46c3cf6a55f3221b01027dc9cc9d64e Mon Sep 17 00:00:00 2001 From: chenyumic Date: Fri, 6 Apr 2018 22:57:36 -0700 Subject: [PATCH 31/52] Regenerate the README files and fix the Open in Cloud Shell link for some samples [(#1441)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1441) --- samples/snippets/README.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/snippets/README.rst b/samples/snippets/README.rst index 00b7fa91a..829cf041d 100644 --- a/samples/snippets/README.rst +++ b/samples/snippets/README.rst @@ -12,7 +12,7 @@ This directory contains samples for Stackdriver Logging. `Stackdriver Logging`_ -.. _Stackdriver Logging: https://cloud.google.com/logging/docs +.. _Stackdriver Logging: https://cloud.google.com/logging/docs Setup ------------------------------------------------------------------------------- @@ -59,7 +59,7 @@ Quickstart +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=logging/cloud-client/quickstart.py;logging/cloud-client/README.rst + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=logging/cloud-client/quickstart.py,logging/cloud-client/README.rst @@ -75,7 +75,7 @@ Snippets +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=logging/cloud-client/snippets.py;logging/cloud-client/README.rst + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=logging/cloud-client/snippets.py,logging/cloud-client/README.rst @@ -111,7 +111,7 @@ Export +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=logging/cloud-client/export.py;logging/cloud-client/README.rst + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=logging/cloud-client/export.py,logging/cloud-client/README.rst From cd2b1289aaccdd3a9fb17b4babcdb5312321fdfd Mon Sep 17 00:00:00 2001 From: Frank Natividad Date: Thu, 26 Apr 2018 10:26:41 -0700 Subject: [PATCH 32/52] Update READMEs to fix numbering and add git clone [(#1464)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1464) --- samples/snippets/README.rst | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/samples/snippets/README.rst b/samples/snippets/README.rst index 829cf041d..1ae5e6d66 100644 --- a/samples/snippets/README.rst +++ b/samples/snippets/README.rst @@ -31,10 +31,16 @@ credentials for applications. Install Dependencies ++++++++++++++++++++ +#. Clone python-docs-samples and change directory to the sample directory you want to use. + + .. code-block:: bash + + $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git + #. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. - .. _Python Development Environment Setup Guide: - https://cloud.google.com/python/setup + .. _Python Development Environment Setup Guide: + https://cloud.google.com/python/setup #. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. From 12bf3dad04475f7f75ca75dd1c2c6315d5b62fab Mon Sep 17 00:00:00 2001 From: Jeffrey Rennie Date: Wed, 15 Aug 2018 13:12:16 -0700 Subject: [PATCH 33/52] Update logging doc tags. [(#1634)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1634) --- samples/snippets/export.py | 9 ++++++++- samples/snippets/snippets.py | 6 ++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/samples/snippets/export.py b/samples/snippets/export.py index f8c1f0c5f..f7606ba6c 100644 --- a/samples/snippets/export.py +++ b/samples/snippets/export.py @@ -19,6 +19,7 @@ from google.cloud import logging +# [START logging_list_sinks] def list_sinks(): """Lists all sinks.""" logging_client = logging.Client() @@ -30,8 +31,10 @@ def list_sinks(): for sink in sinks: print('{}: {} -> {}'.format(sink.name, sink.filter_, sink.destination)) +# [END logging_list_sinks] +# [START logging_create_sink] def create_sink(sink_name, destination_bucket, filter_): """Creates a sink to export logs to the given Cloud Storage bucket. @@ -61,8 +64,10 @@ def create_sink(sink_name, destination_bucket, filter_): sink.create() print('Created sink {}'.format(sink.name)) +# [END logging_create_sink] +# [START logging_update_sink] def update_sink(sink_name, filter_): """Changes a sink's filter. @@ -80,9 +85,10 @@ def update_sink(sink_name, filter_): sink.filter_ = filter_ print('Updated sink {}'.format(sink.name)) sink.update() - # [END update] +# [END logging_update_sink] +# [START logging_delete_sink] def delete_sink(sink_name): """Deletes a sink.""" logging_client = logging.Client() @@ -91,6 +97,7 @@ def delete_sink(sink_name): sink.delete() print('Deleted sink {}'.format(sink.name)) +# [END logging_delete_sink] if __name__ == '__main__': diff --git a/samples/snippets/snippets.py b/samples/snippets/snippets.py index 8a31066fa..78f67e8a9 100644 --- a/samples/snippets/snippets.py +++ b/samples/snippets/snippets.py @@ -26,6 +26,7 @@ from google.cloud import logging +# [START logging_write_log_entry] def write_entry(logger_name): """Writes log entries to the given logger.""" logging_client = logging.Client() @@ -47,8 +48,10 @@ def write_entry(logger_name): }) print('Wrote logs to {}.'.format(logger.name)) +# [END logging_write_log_entry] +# [START logging_list_log_entries] def list_entries(logger_name): """Lists the most recent entries for a given logger.""" logging_client = logging.Client() @@ -60,8 +63,10 @@ def list_entries(logger_name): timestamp = entry.timestamp.isoformat() print('* {}: {}'.format (timestamp, entry.payload)) +# [END logging_list_log_entries] +# [START logging_delete_log] def delete_logger(logger_name): """Deletes a logger and all its entries. @@ -73,6 +78,7 @@ def delete_logger(logger_name): logger.delete() print('Deleted all logging entries for {}'.format(logger.name)) +# [END logging_delete_log] if __name__ == '__main__': From 5262931dcfbff0d78bc044bda0de9469abe438b9 Mon Sep 17 00:00:00 2001 From: Andrew Gorcester Date: Tue, 20 Nov 2018 12:57:25 -0800 Subject: [PATCH 34/52] Fix deprecation warning [(#1801)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1801) logging.warn -> logging.warning to fix "DeprecationWarning: The 'warn' function is deprecated, use 'warning' instead" --- samples/snippets/handler.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/handler.py b/samples/snippets/handler.py index 9986eab85..7b4e50f21 100644 --- a/samples/snippets/handler.py +++ b/samples/snippets/handler.py @@ -36,7 +36,7 @@ def use_logging_handler(): text = 'Hello, world!' # Emits the data using the standard logging module - logging.warn(text) + logging.warning(text) # [END logging_handler_usage] print('Logged: {}'.format(text)) From 8afd09dbdf4fba5fcb3330de0b41545298bfd956 Mon Sep 17 00:00:00 2001 From: DPE bot Date: Tue, 20 Nov 2018 15:40:29 -0800 Subject: [PATCH 35/52] Auto-update dependencies. [(#1846)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1846) ACK, merging. --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index b4a1672d3..22b650de9 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==1.6.0 +google-cloud-logging==1.8.0 From c0fa69f97e5b05d4bdb6d70cb10e1b97cadf7e69 Mon Sep 17 00:00:00 2001 From: DPEBot Date: Wed, 6 Feb 2019 12:06:35 -0800 Subject: [PATCH 36/52] Auto-update dependencies. [(#1980)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1980) * Auto-update dependencies. * Update requirements.txt * Update requirements.txt --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 22b650de9..986c14569 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==1.8.0 +google-cloud-logging==1.10.0 From 3958331ce154112902bd7992d5d04ad921fe1bfa Mon Sep 17 00:00:00 2001 From: Gus Class Date: Tue, 8 Oct 2019 09:53:32 -0700 Subject: [PATCH 37/52] Adds split updates for Firebase ... opencensus [(#2438)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2438) --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 986c14569..8048908a2 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==1.10.0 +google-cloud-logging==1.12.1 From 609284c871ad67e218bed7b96c28a38a21475d2a Mon Sep 17 00:00:00 2001 From: DPEBot Date: Fri, 20 Dec 2019 17:41:38 -0800 Subject: [PATCH 38/52] Auto-update dependencies. [(#2005)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2005) * Auto-update dependencies. * Revert update of appengine/flexible/datastore. * revert update of appengine/flexible/scipy * revert update of bigquery/bqml * revert update of bigquery/cloud-client * revert update of bigquery/datalab-migration * revert update of bigtable/quickstart * revert update of compute/api * revert update of container_registry/container_analysis * revert update of dataflow/run_template * revert update of datastore/cloud-ndb * revert update of dialogflow/cloud-client * revert update of dlp * revert update of functions/imagemagick * revert update of functions/ocr/app * revert update of healthcare/api-client/fhir * revert update of iam/api-client * revert update of iot/api-client/gcs_file_to_device * revert update of iot/api-client/mqtt_example * revert update of language/automl * revert update of run/image-processing * revert update of vision/automl * revert update testing/requirements.txt * revert update of vision/cloud-client/detect * revert update of vision/cloud-client/product_search * revert update of jobs/v2/api_client * revert update of jobs/v3/api_client * revert update of opencensus * revert update of translate/cloud-client * revert update to speech/cloud-client Co-authored-by: Kurtis Van Gent <31518063+kurtisvg@users.noreply.github.com> Co-authored-by: Doug Mahugh --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 8048908a2..03f959145 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==1.12.1 +google-cloud-logging==1.14.0 From 10dab41e668cfdf9c6e69f01506934abebe73de4 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Fri, 27 Mar 2020 19:40:24 +0100 Subject: [PATCH 39/52] chore(deps): update dependency google-cloud-logging to v1.15.0 [(#3161)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3161) This PR contains the following updates: | Package | Update | Change | |---|---|---| | [google-cloud-logging](https://togithub.com/googleapis/python-logging) | minor | `==1.14.0` -> `==1.15.0` | --- ### Release Notes
googleapis/python-logging ### [`v1.15.0`](https://togithub.com/googleapis/python-logging/blob/master/CHANGELOG.md#​1150httpswwwgithubcomgoogleapispython-loggingcomparev1140v1150-2020-02-26) [Compare Source](https://togithub.com/googleapis/python-logging/compare/v1.14.0...v1.15.0) ##### Features - add support for cmek settings; undeprecate resource name helper methods; bump copyright year to 2020 ([#​22](https://www.github.com/googleapis/python-logging/issues/22)) ([1c687c1](https://www.github.com/googleapis/python-logging/commit/1c687c168cdc1f5ebc74d2380ad87335a42209a2)) ##### Bug Fixes - **logging:** deprecate resource name helper methods (via synth) ([#​9837](https://www.github.com/googleapis/python-logging/issues/9837)) ([335af9e](https://www.github.com/googleapis/python-logging/commit/335af9e909eb7fb4696ba906a82176611653531d)) - **logging:** update test assertion and core version pins ([#​10087](https://www.github.com/googleapis/python-logging/issues/10087)) ([4aedea8](https://www.github.com/googleapis/python-logging/commit/4aedea80e2bccb5ba3c41fae7a0ee46cc07eefa9)) - replace unsafe six.PY3 with PY2 for better future compatibility with Python 4 ([#​10081](https://www.github.com/googleapis/python-logging/issues/10081)) ([c6eb601](https://www.github.com/googleapis/python-logging/commit/c6eb60179d674dfd5137d90d209094c9369b3581))
--- ### Renovate configuration :date: **Schedule**: At any time (no schedule defined). :vertical_traffic_light: **Automerge**: Disabled by config. Please merge this manually once you are satisfied. :recycle: **Rebasing**: Never, or you tick the rebase/retry checkbox. :no_bell: **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#GoogleCloudPlatform/python-docs-samples). --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 03f959145..9bd776d79 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==1.14.0 +google-cloud-logging==1.15.0 From 6a53a8425334a9684c4287377e4e08f4e7ddacd6 Mon Sep 17 00:00:00 2001 From: Kurtis Van Gent <31518063+kurtisvg@users.noreply.github.com> Date: Wed, 1 Apr 2020 19:11:50 -0700 Subject: [PATCH 40/52] Simplify noxfile setup. [(#2806)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/2806) * chore(deps): update dependency requests to v2.23.0 * Simplify noxfile and add version control. * Configure appengine/standard to only test Python 2.7. * Update Kokokro configs to match noxfile. * Add requirements-test to each folder. * Remove Py2 versions from everything execept appengine/standard. * Remove conftest.py. * Remove appengine/standard/conftest.py * Remove 'no-sucess-flaky-report' from pytest.ini. * Add GAE SDK back to appengine/standard tests. * Fix typo. * Roll pytest to python 2 version. * Add a bunch of testing requirements. * Remove typo. * Add appengine lib directory back in. * Add some additional requirements. * Fix issue with flake8 args. * Even more requirements. * Readd appengine conftest.py. * Add a few more requirements. * Even more Appengine requirements. * Add webtest for appengine/standard/mailgun. * Add some additional requirements. * Add workaround for issue with mailjet-rest. * Add responses for appengine/standard/mailjet. Co-authored-by: Renovate Bot --- samples/snippets/requirements-test.txt | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 samples/snippets/requirements-test.txt diff --git a/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt new file mode 100644 index 000000000..1cfcb6852 --- /dev/null +++ b/samples/snippets/requirements-test.txt @@ -0,0 +1,2 @@ +pytest==5.3.2 +gcp-devrel-py-tools==0.0.15 From 5999d8ef6abb93931fa7da021ac5ad6d23f26f5a Mon Sep 17 00:00:00 2001 From: Takashi Matsuo Date: Wed, 22 Apr 2020 18:38:58 -0700 Subject: [PATCH 41/52] [logging] chore: remove gcp-devrel-py-tools [(#3477)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3477) --- samples/snippets/export_test.py | 9 ++++++--- samples/snippets/requirements-test.txt | 2 +- samples/snippets/snippets_test.py | 17 ++++++++++------- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/samples/snippets/export_test.py b/samples/snippets/export_test.py index ea0903905..b787c066a 100644 --- a/samples/snippets/export_test.py +++ b/samples/snippets/export_test.py @@ -16,12 +16,13 @@ import random import string -from gcp_devrel.testing import eventually_consistent +import backoff from google.cloud import logging import pytest import export + BUCKET = os.environ['CLOUD_STORAGE_BUCKET'] TEST_SINK_NAME_TMPL = 'example_sink_{}' TEST_SINK_FILTER = 'severity>=CRITICAL' @@ -53,12 +54,14 @@ def example_sink(): def test_list(example_sink, capsys): - @eventually_consistent.call - def _(): + @backoff.on_exception(backoff.expo, AssertionError, max_time=60) + def eventually_consistent_test(): export.list_sinks() out, _ = capsys.readouterr() assert example_sink.name in out + eventually_consistent_test() + def test_create(capsys): sink_name = TEST_SINK_NAME_TMPL.format(_random_id()) diff --git a/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt index 1cfcb6852..8855f3cf1 100644 --- a/samples/snippets/requirements-test.txt +++ b/samples/snippets/requirements-test.txt @@ -1,2 +1,2 @@ +backoff==1.10.0 pytest==5.3.2 -gcp-devrel-py-tools==0.0.15 diff --git a/samples/snippets/snippets_test.py b/samples/snippets/snippets_test.py index 480763cdb..075c88a51 100644 --- a/samples/snippets/snippets_test.py +++ b/samples/snippets/snippets_test.py @@ -12,12 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -from gcp_devrel.testing import eventually_consistent +import backoff from google.cloud import logging import pytest import snippets + TEST_LOGGER_NAME = 'example_log' @@ -31,18 +32,20 @@ def example_log(): def test_list(example_log, capsys): - @eventually_consistent.call - def _(): + @backoff.on_exception(backoff.expo, AssertionError, max_time=120) + def eventually_consistent_test(): snippets.list_entries(TEST_LOGGER_NAME) out, _ = capsys.readouterr() assert example_log in out + eventually_consistent_test() + def test_write(): snippets.write_entry(TEST_LOGGER_NAME) -def test_delete(example_log): - @eventually_consistent.call - def _(): - snippets.delete_logger(TEST_LOGGER_NAME) +def test_delete(example_log, capsys): + snippets.delete_logger(TEST_LOGGER_NAME) + out, _ = capsys.readouterr() + assert TEST_LOGGER_NAME in out From ff2cea80192aa791178196c747d90b47c4014bbc Mon Sep 17 00:00:00 2001 From: Darren Carlton Date: Wed, 6 May 2020 17:21:13 -0400 Subject: [PATCH 42/52] Update logging example to retrieve the default handler [(#3691)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3691) * Update handler.py * Update README.rst * Update handler.py Co-authored-by: Kurtis Van Gent <31518063+kurtisvg@users.noreply.github.com> --- samples/snippets/README.rst | 6 +++--- samples/snippets/handler.py | 9 ++++++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/samples/snippets/README.rst b/samples/snippets/README.rst index 1ae5e6d66..f8cb576a9 100644 --- a/samples/snippets/README.rst +++ b/samples/snippets/README.rst @@ -7,12 +7,12 @@ Stackdriver Logging Python Samples :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=logging/cloud-client/README.rst -This directory contains samples for Stackdriver Logging. `Stackdriver Logging`_ allows you to store, search, analyze, monitor, and alert on log data and events from Google Cloud Platform and Amazon Web Services. +This directory contains samples for `Cloud Logging`_, which you can use to store, search, analyze, monitor, and alert on log data and events from Google Cloud Platform and Amazon Web Services. -.. _Stackdriver Logging: https://cloud.google.com/logging/docs +.. _Cloud Logging: https://cloud.google.com/logging/docs Setup ------------------------------------------------------------------------------- @@ -165,4 +165,4 @@ to `browse the source`_ and `report issues`_. https://github.com/GoogleCloudPlatform/google-cloud-python/issues -.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file +.. _Google Cloud SDK: https://cloud.google.com/sdk/ diff --git a/samples/snippets/handler.py b/samples/snippets/handler.py index 7b4e50f21..d59458425 100644 --- a/samples/snippets/handler.py +++ b/samples/snippets/handler.py @@ -17,14 +17,17 @@ def use_logging_handler(): # [START logging_handler_setup] - # Imports the Google Cloud client library + # Imports the Cloud Logging client library import google.cloud.logging # Instantiates a client client = google.cloud.logging.Client() - # Connects the logger to the root logging handler; by default this captures - # all logs at INFO level and higher + # Retrieves a Cloud Logging handler based on the environment + # you're running in and integrates the handler with the + # Python logging module. By default this captures all logs + # at INFO level and higher + client.get_default_handler() client.setup_logging() # [END logging_handler_setup] From d6789bd37c1da4af4a1dc27bcd5846daa003f464 Mon Sep 17 00:00:00 2001 From: Takashi Matsuo Date: Tue, 26 May 2020 10:41:50 -0700 Subject: [PATCH 43/52] testing: various cleanups [(#3877)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/3877) * testing: various cleanups * [iap]: only run iap tests on Kokoro * [vision/automl]: use temporary directory for temporary files * [appengine/flexible/scipy]: use temporary directory * [bigtable/snippets/reads]: update pytest snapshot * [texttospeech/cloud-client]: added output.mp3 to .gitignore * [iot/api-client/gcs_file_to_device]: use temporary directory * [iot/api-client/mqtt_example]: use temporary directory * [logging/cloud-client]: use uuid and add backoff * use project directory with Trampoline V1 --- samples/snippets/snippets_test.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/samples/snippets/snippets_test.py b/samples/snippets/snippets_test.py index 075c88a51..1d1d01972 100644 --- a/samples/snippets/snippets_test.py +++ b/samples/snippets/snippets_test.py @@ -12,14 +12,17 @@ # See the License for the specific language governing permissions and # limitations under the License. +import uuid + import backoff +from google.api_core.exceptions import NotFound from google.cloud import logging import pytest import snippets -TEST_LOGGER_NAME = 'example_log' +TEST_LOGGER_NAME = 'example_log_{}'.format(uuid.uuid4().hex) @pytest.fixture @@ -46,6 +49,8 @@ def test_write(): def test_delete(example_log, capsys): - snippets.delete_logger(TEST_LOGGER_NAME) - out, _ = capsys.readouterr() - assert TEST_LOGGER_NAME in out + @backoff.on_exception(backoff.expo, NotFound, max_time=120) + def eventually_consistent_test(): + snippets.delete_logger(TEST_LOGGER_NAME) + out, _ = capsys.readouterr() + assert TEST_LOGGER_NAME in out From 121d6df36d771d3b6a7677e232b54ceab08c4949 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Mon, 13 Jul 2020 00:46:30 +0200 Subject: [PATCH 44/52] chore(deps): update dependency pytest to v5.4.3 [(#4279)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/4279) * chore(deps): update dependency pytest to v5.4.3 * specify pytest for python 2 in appengine Co-authored-by: Leah Cole --- samples/snippets/requirements-test.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt index 8855f3cf1..678aa129f 100644 --- a/samples/snippets/requirements-test.txt +++ b/samples/snippets/requirements-test.txt @@ -1,2 +1,2 @@ backoff==1.10.0 -pytest==5.3.2 +pytest==5.4.3 From d28afc95313a41bc7489ebbe8e6f8b594d480da5 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Sat, 1 Aug 2020 21:51:00 +0200 Subject: [PATCH 45/52] Update dependency pytest to v6 [(#4390)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/4390) --- samples/snippets/requirements-test.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt index 678aa129f..d0029c6de 100644 --- a/samples/snippets/requirements-test.txt +++ b/samples/snippets/requirements-test.txt @@ -1,2 +1,2 @@ backoff==1.10.0 -pytest==5.4.3 +pytest==6.0.1 From be25bb000c1079d449d4e53869bef0ed0baad85d Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Mon, 10 Aug 2020 22:11:59 +0200 Subject: [PATCH 46/52] chore(deps): update dependency google-cloud-logging to v1.15.1 [(#4458)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/4458) --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 9bd776d79..dbb4176a1 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-logging==1.15.0 +google-cloud-logging==1.15.1 From a44921fdd7c5bb2cf44872131d16fe2664d2e945 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim Date: Mon, 12 Oct 2020 16:17:20 +0000 Subject: [PATCH 47/52] chore: update templates --- .coveragerc | 5 +- .flake8 | 2 + .github/snippet-bot.yml | 0 .gitignore | 5 +- .kokoro/populate-secrets.sh | 43 ++++ CONTRIBUTING.rst | 19 -- MANIFEST.in | 3 + docs/multiprocessing.rst | 7 + samples/AUTHORING_GUIDE.md | 1 + samples/CONTRIBUTING.md | 1 + samples/snippets/README.rst | 29 ++- samples/snippets/noxfile.py | 229 ++++++++++++++++++ scripts/readme-gen/readme_gen.py | 66 +++++ scripts/readme-gen/templates/README.tmpl.rst | 87 +++++++ scripts/readme-gen/templates/auth.tmpl.rst | 9 + .../templates/auth_api_key.tmpl.rst | 14 ++ .../templates/install_deps.tmpl.rst | 29 +++ .../templates/install_portaudio.tmpl.rst | 35 +++ synth.metadata | 27 +-- synth.py | 10 +- 20 files changed, 582 insertions(+), 39 deletions(-) create mode 100644 .github/snippet-bot.yml create mode 100755 .kokoro/populate-secrets.sh create mode 100644 docs/multiprocessing.rst create mode 100644 samples/AUTHORING_GUIDE.md create mode 100644 samples/CONTRIBUTING.md create mode 100644 samples/snippets/noxfile.py create mode 100644 scripts/readme-gen/readme_gen.py create mode 100644 scripts/readme-gen/templates/README.tmpl.rst create mode 100644 scripts/readme-gen/templates/auth.tmpl.rst create mode 100644 scripts/readme-gen/templates/auth_api_key.tmpl.rst create mode 100644 scripts/readme-gen/templates/install_deps.tmpl.rst create mode 100644 scripts/readme-gen/templates/install_portaudio.tmpl.rst diff --git a/.coveragerc b/.coveragerc index dd39c8546..0d8e6297d 100644 --- a/.coveragerc +++ b/.coveragerc @@ -17,6 +17,8 @@ # Generated by synthtool. DO NOT EDIT! [run] branch = True +omit = + google/cloud/__init__.py [report] fail_under = 100 @@ -32,4 +34,5 @@ omit = */gapic/*.py */proto/*.py */core/*.py - */site-packages/*.py \ No newline at end of file + */site-packages/*.py + google/cloud/__init__.py diff --git a/.flake8 b/.flake8 index 20fe9bda2..ed9316381 100644 --- a/.flake8 +++ b/.flake8 @@ -21,6 +21,8 @@ exclude = # Exclude generated code. **/proto/** **/gapic/** + **/services/** + **/types/** *_pb2.py # Standard linting exemptions. diff --git a/.github/snippet-bot.yml b/.github/snippet-bot.yml new file mode 100644 index 000000000..e69de29bb diff --git a/.gitignore b/.gitignore index 3fb06e09c..b9daa52f1 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ dist build eggs +.eggs parts bin var @@ -45,14 +46,16 @@ pip-log.txt # Built documentation docs/_build bigquery/docs/generated +docs.metadata # Virtual environment env/ coverage.xml +sponge_log.xml # System test environment variables. system_tests/local_test_setup # Make sure a generated file isn't accidentally committed. pylintrc -pylintrc.test \ No newline at end of file +pylintrc.test diff --git a/.kokoro/populate-secrets.sh b/.kokoro/populate-secrets.sh new file mode 100755 index 000000000..f52514257 --- /dev/null +++ b/.kokoro/populate-secrets.sh @@ -0,0 +1,43 @@ +#!/bin/bash +# Copyright 2020 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eo pipefail + +function now { date +"%Y-%m-%d %H:%M:%S" | tr -d '\n' ;} +function msg { println "$*" >&2 ;} +function println { printf '%s\n' "$(now) $*" ;} + + +# Populates requested secrets set in SECRET_MANAGER_KEYS from service account: +# kokoro-trampoline@cloud-devrel-kokoro-resources.iam.gserviceaccount.com +SECRET_LOCATION="${KOKORO_GFILE_DIR}/secret_manager" +msg "Creating folder on disk for secrets: ${SECRET_LOCATION}" +mkdir -p ${SECRET_LOCATION} +for key in $(echo ${SECRET_MANAGER_KEYS} | sed "s/,/ /g") +do + msg "Retrieving secret ${key}" + docker run --entrypoint=gcloud \ + --volume=${KOKORO_GFILE_DIR}:${KOKORO_GFILE_DIR} \ + gcr.io/google.com/cloudsdktool/cloud-sdk \ + secrets versions access latest \ + --project cloud-devrel-kokoro-resources \ + --secret ${key} > \ + "${SECRET_LOCATION}/${key}" + if [[ $? == 0 ]]; then + msg "Secret written to ${SECRET_LOCATION}/${key}" + else + msg "Error retrieving secret ${key}" + fi +done diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 64c917ca8..ef2706b77 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -80,25 +80,6 @@ We use `nox `__ to instrument our tests. .. nox: https://pypi.org/project/nox/ -Note on Editable Installs / Develop Mode -======================================== - -- As mentioned previously, using ``setuptools`` in `develop mode`_ - or a ``pip`` `editable install`_ is not possible with this - library. This is because this library uses `namespace packages`_. - For context see `Issue #2316`_ and the relevant `PyPA issue`_. - - Since ``editable`` / ``develop`` mode can't be used, packages - need to be installed directly. Hence your changes to the source - tree don't get incorporated into the **already installed** - package. - -.. _namespace packages: https://www.python.org/dev/peps/pep-0420/ -.. _Issue #2316: https://github.com/GoogleCloudPlatform/google-cloud-python/issues/2316 -.. _PyPA issue: https://github.com/pypa/packaging-problems/issues/12 -.. _develop mode: https://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode -.. _editable install: https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs - ***************************************** I'm getting weird errors... Can you help? ***************************************** diff --git a/MANIFEST.in b/MANIFEST.in index 68855abc3..e9e29d120 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -20,3 +20,6 @@ recursive-include google *.json *.proto recursive-include tests * global-exclude *.py[co] global-exclude __pycache__ + +# Exclude scripts for samples readmegen +prune scripts/readme-gen \ No newline at end of file diff --git a/docs/multiprocessing.rst b/docs/multiprocessing.rst new file mode 100644 index 000000000..1cb29d4ca --- /dev/null +++ b/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpcio` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.Pool` or + :class:`multiprocessing.Process`. diff --git a/samples/AUTHORING_GUIDE.md b/samples/AUTHORING_GUIDE.md new file mode 100644 index 000000000..55c97b32f --- /dev/null +++ b/samples/AUTHORING_GUIDE.md @@ -0,0 +1 @@ +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/AUTHORING_GUIDE.md \ No newline at end of file diff --git a/samples/CONTRIBUTING.md b/samples/CONTRIBUTING.md new file mode 100644 index 000000000..34c882b6f --- /dev/null +++ b/samples/CONTRIBUTING.md @@ -0,0 +1 @@ +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/CONTRIBUTING.md \ No newline at end of file diff --git a/samples/snippets/README.rst b/samples/snippets/README.rst index f8cb576a9..d60cd0a3b 100644 --- a/samples/snippets/README.rst +++ b/samples/snippets/README.rst @@ -1,3 +1,4 @@ + .. This file is automatically generated. Do not edit this file directly. Stackdriver Logging Python Samples @@ -7,17 +8,19 @@ Stackdriver Logging Python Samples :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=logging/cloud-client/README.rst -This directory contains samples for `Cloud Logging`_, which you can use to store, search, analyze, monitor, and alert on log data and events from Google Cloud Platform and Amazon Web Services. +This directory contains samples for Stackdriver Logging. `Stackdriver Logging`_ allows you to store, search, analyze, monitor, and alert on log data and events from Google Cloud Platform and Amazon Web Services. + +.. _Stackdriver Logging: https://cloud.google.com/logging/docs -.. _Cloud Logging: https://cloud.google.com/logging/docs Setup ------------------------------------------------------------------------------- + Authentication ++++++++++++++ @@ -28,6 +31,9 @@ credentials for applications. .. _Authentication Getting Started Guide: https://cloud.google.com/docs/authentication/getting-started + + + Install Dependencies ++++++++++++++++++++ @@ -42,7 +48,7 @@ Install Dependencies .. _Python Development Environment Setup Guide: https://cloud.google.com/python/setup -#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. +#. Create a virtualenv. Samples are compatible with Python 3.6+. .. code-block:: bash @@ -58,9 +64,15 @@ Install Dependencies .. _pip: https://pip.pypa.io/ .. _virtualenv: https://virtualenv.pypa.io/ + + + + + Samples ------------------------------------------------------------------------------- + Quickstart +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ @@ -77,6 +89,8 @@ To run this sample: $ python quickstart.py + + Snippets +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ @@ -92,6 +106,7 @@ To run this sample: $ python snippets.py + usage: snippets.py [-h] logger_name {list,write,delete} ... This application demonstrates how to perform basic operations on logs and @@ -113,6 +128,8 @@ To run this sample: + + Export +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ @@ -128,6 +145,7 @@ To run this sample: $ python export.py + usage: export.py [-h] {list,create,update,delete} ... positional arguments: @@ -150,6 +168,10 @@ To run this sample: + + + + The client library ------------------------------------------------------------------------------- @@ -165,4 +187,5 @@ to `browse the source`_ and `report issues`_. https://github.com/GoogleCloudPlatform/google-cloud-python/issues + .. _Google Cloud SDK: https://cloud.google.com/sdk/ diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py new file mode 100644 index 000000000..01686e4a0 --- /dev/null +++ b/samples/snippets/noxfile.py @@ -0,0 +1,229 @@ +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import print_function + +import os +from pathlib import Path +import sys + +import nox + + +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING +# DO NOT EDIT THIS FILE EVER! +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING + +# Copy `noxfile_config.py` to your directory and modify it instead. + + +# `TEST_CONFIG` dict is a configuration hook that allows users to +# modify the test configurations. The values here should be in sync +# with `noxfile_config.py`. Users will copy `noxfile_config.py` into +# their directory and modify it. + +TEST_CONFIG = { + # You can opt out from the test for specific Python versions. + 'ignored_versions': ["2.7"], + + # An envvar key for determining the project id to use. Change it + # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a + # build specific Cloud project. You can also use your own string + # to use your own Cloud project. + 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', + # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + + # A dictionary you want to inject into your test. Don't put any + # secrets here. These values will override predefined values. + 'envs': {}, +} + + +try: + # Ensure we can import noxfile_config in the project's directory. + sys.path.append('.') + from noxfile_config import TEST_CONFIG_OVERRIDE +except ImportError as e: + print("No user noxfile_config found: detail: {}".format(e)) + TEST_CONFIG_OVERRIDE = {} + +# Update the TEST_CONFIG with the user supplied values. +TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) + + +def get_pytest_env_vars(): + """Returns a dict for pytest invocation.""" + ret = {} + + # Override the GCLOUD_PROJECT and the alias. + env_key = TEST_CONFIG['gcloud_project_env'] + # This should error out if not set. + ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key] + + # Apply user supplied envs. + ret.update(TEST_CONFIG['envs']) + return ret + + +# DO NOT EDIT - automatically generated. +# All versions used to tested samples. +ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"] + +# Any default versions that should be ignored. +IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] + +TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) + +INSTALL_LIBRARY_FROM_SOURCE = bool(os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False)) +# +# Style Checks +# + + +def _determine_local_import_names(start_dir): + """Determines all import names that should be considered "local". + + This is used when running the linter to insure that import order is + properly checked. + """ + file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] + return [ + basename + for basename, extension in file_ext_pairs + if extension == ".py" + or os.path.isdir(os.path.join(start_dir, basename)) + and basename not in ("__pycache__") + ] + + +# Linting with flake8. +# +# We ignore the following rules: +# E203: whitespace before ‘:’ +# E266: too many leading ‘#’ for block comment +# E501: line too long +# I202: Additional newline in a section of imports +# +# We also need to specify the rules which are ignored by default: +# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] +FLAKE8_COMMON_ARGS = [ + "--show-source", + "--builtin=gettext", + "--max-complexity=20", + "--import-order-style=google", + "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", + "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", + "--max-line-length=88", +] + + +@nox.session +def lint(session): + session.install("flake8", "flake8-import-order") + + local_names = _determine_local_import_names(".") + args = FLAKE8_COMMON_ARGS + [ + "--application-import-names", + ",".join(local_names), + "." + ] + session.run("flake8", *args) + + +# +# Sample Tests +# + + +PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] + + +def _session_tests(session, post_install=None): + """Runs py.test for a particular project.""" + if os.path.exists("requirements.txt"): + session.install("-r", "requirements.txt") + + if os.path.exists("requirements-test.txt"): + session.install("-r", "requirements-test.txt") + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars() + ) + + +@nox.session(python=ALL_VERSIONS) +def py(session): + """Runs py.test for a sample using the specified version of Python.""" + if session.python in TESTED_VERSIONS: + _session_tests(session) + else: + session.skip("SKIPPED: {} tests are disabled for this sample.".format( + session.python + )) + + +# +# Readmegen +# + + +def _get_repo_root(): + """ Returns the root folder of the project. """ + # Get root of this repository. Assume we don't have directories nested deeper than 10 items. + p = Path(os.getcwd()) + for i in range(10): + if p is None: + break + if Path(p / ".git").exists(): + return str(p) + # .git is not available in repos cloned via Cloud Build + # setup.py is always in the library's root, so use that instead + # https://github.com/googleapis/synthtool/issues/792 + if Path(p / "setup.py").exists(): + return str(p) + p = p.parent + raise Exception("Unable to detect repository root.") + + +GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) + + +@nox.session +@nox.parametrize("path", GENERATED_READMES) +def readmegen(session, path): + """(Re-)generates the readme for a sample.""" + session.install("jinja2", "pyyaml") + dir_ = os.path.dirname(path) + + if os.path.exists(os.path.join(dir_, "requirements.txt")): + session.install("-r", os.path.join(dir_, "requirements.txt")) + + in_file = os.path.join(dir_, "README.rst.in") + session.run( + "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file + ) diff --git a/scripts/readme-gen/readme_gen.py b/scripts/readme-gen/readme_gen.py new file mode 100644 index 000000000..d309d6e97 --- /dev/null +++ b/scripts/readme-gen/readme_gen.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python + +# Copyright 2016 Google Inc +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Generates READMEs using configuration defined in yaml.""" + +import argparse +import io +import os +import subprocess + +import jinja2 +import yaml + + +jinja_env = jinja2.Environment( + trim_blocks=True, + loader=jinja2.FileSystemLoader( + os.path.abspath(os.path.join(os.path.dirname(__file__), 'templates')))) + +README_TMPL = jinja_env.get_template('README.tmpl.rst') + + +def get_help(file): + return subprocess.check_output(['python', file, '--help']).decode() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('source') + parser.add_argument('--destination', default='README.rst') + + args = parser.parse_args() + + source = os.path.abspath(args.source) + root = os.path.dirname(source) + destination = os.path.join(root, args.destination) + + jinja_env.globals['get_help'] = get_help + + with io.open(source, 'r') as f: + config = yaml.load(f) + + # This allows get_help to execute in the right directory. + os.chdir(root) + + output = README_TMPL.render(config) + + with io.open(destination, 'w') as f: + f.write(output) + + +if __name__ == '__main__': + main() diff --git a/scripts/readme-gen/templates/README.tmpl.rst b/scripts/readme-gen/templates/README.tmpl.rst new file mode 100644 index 000000000..4fd239765 --- /dev/null +++ b/scripts/readme-gen/templates/README.tmpl.rst @@ -0,0 +1,87 @@ +{# The following line is a lie. BUT! Once jinja2 is done with it, it will + become truth! #} +.. This file is automatically generated. Do not edit this file directly. + +{{product.name}} Python Samples +=============================================================================== + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor={{folder}}/README.rst + + +This directory contains samples for {{product.name}}. {{product.description}} + +{{description}} + +.. _{{product.name}}: {{product.url}} + +{% if required_api_url %} +To run the sample, you need to enable the API at: {{required_api_url}} +{% endif %} + +{% if required_role %} +To run the sample, you need to have `{{required_role}}` role. +{% endif %} + +{{other_required_steps}} + +{% if setup %} +Setup +------------------------------------------------------------------------------- + +{% for section in setup %} + +{% include section + '.tmpl.rst' %} + +{% endfor %} +{% endif %} + +{% if samples %} +Samples +------------------------------------------------------------------------------- + +{% for sample in samples %} +{{sample.name}} ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +{% if not sample.hide_cloudshell_button %} +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor={{folder}}/{{sample.file}},{{folder}}/README.rst +{% endif %} + + +{{sample.description}} + +To run this sample: + +.. code-block:: bash + + $ python {{sample.file}} +{% if sample.show_help %} + + {{get_help(sample.file)|indent}} +{% endif %} + + +{% endfor %} +{% endif %} + +{% if cloud_client_library %} + +The client library +------------------------------------------------------------------------------- + +This sample uses the `Google Cloud Client Library for Python`_. +You can read the documentation for more details on API usage and use GitHub +to `browse the source`_ and `report issues`_. + +.. _Google Cloud Client Library for Python: + https://googlecloudplatform.github.io/google-cloud-python/ +.. _browse the source: + https://github.com/GoogleCloudPlatform/google-cloud-python +.. _report issues: + https://github.com/GoogleCloudPlatform/google-cloud-python/issues + +{% endif %} + +.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/scripts/readme-gen/templates/auth.tmpl.rst b/scripts/readme-gen/templates/auth.tmpl.rst new file mode 100644 index 000000000..1446b94a5 --- /dev/null +++ b/scripts/readme-gen/templates/auth.tmpl.rst @@ -0,0 +1,9 @@ +Authentication +++++++++++++++ + +This sample requires you to have authentication setup. Refer to the +`Authentication Getting Started Guide`_ for instructions on setting up +credentials for applications. + +.. _Authentication Getting Started Guide: + https://cloud.google.com/docs/authentication/getting-started diff --git a/scripts/readme-gen/templates/auth_api_key.tmpl.rst b/scripts/readme-gen/templates/auth_api_key.tmpl.rst new file mode 100644 index 000000000..11957ce27 --- /dev/null +++ b/scripts/readme-gen/templates/auth_api_key.tmpl.rst @@ -0,0 +1,14 @@ +Authentication +++++++++++++++ + +Authentication for this service is done via an `API Key`_. To obtain an API +Key: + +1. Open the `Cloud Platform Console`_ +2. Make sure that billing is enabled for your project. +3. From the **Credentials** page, create a new **API Key** or use an existing + one for your project. + +.. _API Key: + https://developers.google.com/api-client-library/python/guide/aaa_apikeys +.. _Cloud Console: https://console.cloud.google.com/project?_ diff --git a/scripts/readme-gen/templates/install_deps.tmpl.rst b/scripts/readme-gen/templates/install_deps.tmpl.rst new file mode 100644 index 000000000..a0406dba8 --- /dev/null +++ b/scripts/readme-gen/templates/install_deps.tmpl.rst @@ -0,0 +1,29 @@ +Install Dependencies +++++++++++++++++++++ + +#. Clone python-docs-samples and change directory to the sample directory you want to use. + + .. code-block:: bash + + $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git + +#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. + + .. _Python Development Environment Setup Guide: + https://cloud.google.com/python/setup + +#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. + + .. code-block:: bash + + $ virtualenv env + $ source env/bin/activate + +#. Install the dependencies needed to run the samples. + + .. code-block:: bash + + $ pip install -r requirements.txt + +.. _pip: https://pip.pypa.io/ +.. _virtualenv: https://virtualenv.pypa.io/ diff --git a/scripts/readme-gen/templates/install_portaudio.tmpl.rst b/scripts/readme-gen/templates/install_portaudio.tmpl.rst new file mode 100644 index 000000000..5ea33d18c --- /dev/null +++ b/scripts/readme-gen/templates/install_portaudio.tmpl.rst @@ -0,0 +1,35 @@ +Install PortAudio ++++++++++++++++++ + +Install `PortAudio`_. This is required by the `PyAudio`_ library to stream +audio from your computer's microphone. PyAudio depends on PortAudio for cross-platform compatibility, and is installed differently depending on the +platform. + +* For Mac OS X, you can use `Homebrew`_:: + + brew install portaudio + + **Note**: if you encounter an error when running `pip install` that indicates + it can't find `portaudio.h`, try running `pip install` with the following + flags:: + + pip install --global-option='build_ext' \ + --global-option='-I/usr/local/include' \ + --global-option='-L/usr/local/lib' \ + pyaudio + +* For Debian / Ubuntu Linux:: + + apt-get install portaudio19-dev python-all-dev + +* Windows may work without having to install PortAudio explicitly (it will get + installed with PyAudio). + +For more details, see the `PyAudio installation`_ page. + + +.. _PyAudio: https://people.csail.mit.edu/hubert/pyaudio/ +.. _PortAudio: http://www.portaudio.com/ +.. _PyAudio installation: + https://people.csail.mit.edu/hubert/pyaudio/#downloads +.. _Homebrew: http://brew.sh diff --git a/synth.metadata b/synth.metadata index a5616d3e5..70f91ca29 100644 --- a/synth.metadata +++ b/synth.metadata @@ -1,32 +1,32 @@ { "sources": [ - { - "generator": { - "name": "artman", - "version": "2.0.0", - "dockerImage": "googleapis/artman@sha256:b3b47805231a305d0f40c4bf069df20f6a2635574e6d4259fac651d3f9f6e098" - } - }, { "git": { "name": ".", - "remote": "git@github.com:googleapis/python-logging", - "sha": "a22a3bfdd4c8a4d6e9cc0c7d7504322ff31ad7ea" + "remote": "git@github.com:googleapis/python-logging.git", + "sha": "98029b5a0d997963a7a30758933e0cc8ee8f5127" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "aaff764c185e18a6c73227357c3df5fa60fec85a", - "internalRef": "309426927" + "sha": "fd31b1600fc496d6127665d29f095371d985c637", + "internalRef": "336344634" + } + }, + { + "git": { + "name": "synthtool", + "remote": "https://github.com/googleapis/synthtool.git", + "sha": "befc24dcdeb8e57ec1259826fd33120b05137e8f" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "cdddf139b36000b3a7c65fd2a7781e253262359a" + "sha": "befc24dcdeb8e57ec1259826fd33120b05137e8f" } } ], @@ -37,8 +37,7 @@ "apiName": "logging", "apiVersion": "v2", "language": "python", - "generator": "gapic", - "config": "google/logging/artman_logging.yaml" + "generator": "bazel" } } ] diff --git a/synth.py b/synth.py index 45a49f131..9965d9b69 100644 --- a/synth.py +++ b/synth.py @@ -15,6 +15,7 @@ """This script is used to synthesize generated parts of this library.""" import synthtool as s from synthtool import gcp +from synthtool.languages import python gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() @@ -56,7 +57,14 @@ 'webob', 'django' ], + samples=True, ) s.move(templated_files, excludes=[".coveragerc"]) -s.shell.run(["nox", "-s", "blacken"], hide_output=False) +# -------------------------------------------------------------------------- +# Samples templates +# -------------------------------------------------------------------------- + +python.py_samples() + +s.shell.run(["nox", "-s", "blacken"], hide_output=False) \ No newline at end of file From 2b57b0e7fc31ad804a4fbc68d6d5cfbdd78d9459 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim Date: Fri, 30 Oct 2020 23:05:13 +0000 Subject: [PATCH 48/52] chore: remove multiprocessing note --- docs/multiprocessing.rst | 7 ------- noxfile.py | 33 --------------------------------- 2 files changed, 40 deletions(-) delete mode 100644 docs/multiprocessing.rst diff --git a/docs/multiprocessing.rst b/docs/multiprocessing.rst deleted file mode 100644 index 1cb29d4ca..000000000 --- a/docs/multiprocessing.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. note:: - - Because this client uses :mod:`grpcio` library, it is safe to - share instances across threads. In multiprocessing scenarios, the best - practice is to create client instances *after* the invocation of - :func:`os.fork` by :class:`multiprocessing.Pool` or - :class:`multiprocessing.Process`. diff --git a/noxfile.py b/noxfile.py index 11fc0bf28..9cc3ab77f 100644 --- a/noxfile.py +++ b/noxfile.py @@ -172,39 +172,6 @@ def docs(session): ) -@nox.session(python="3.7") -def docfx(session): - """Build the docfx yaml files for this library.""" - - session.install("-e", ".") - session.install("sphinx", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-T", # show full traceback on exception - "-N", # no colors - "-D", - ( - "extensions=sphinx.ext.autodoc," - "sphinx.ext.autosummary," - "docfx_yaml.extension," - "sphinx.ext.intersphinx," - "sphinx.ext.coverage," - "sphinx.ext.napoleon," - "sphinx.ext.todo," - "sphinx.ext.viewcode," - "recommonmark" - ), - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - @nox.session(python=DEFAULT_PYTHON_VERSION) def docfx(session): """Build the docfx yaml files for this library.""" From ca80508ac71b68a27149be2f3858ff3aaba59517 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim Date: Wed, 11 Nov 2020 22:54:51 +0000 Subject: [PATCH 49/52] docs: fix samples README --- samples/snippets/README.rst | 37 +++++++++------------------------- samples/snippets/README.rst.in | 6 +++--- 2 files changed, 12 insertions(+), 31 deletions(-) diff --git a/samples/snippets/README.rst b/samples/snippets/README.rst index d60cd0a3b..110ad776e 100644 --- a/samples/snippets/README.rst +++ b/samples/snippets/README.rst @@ -1,26 +1,27 @@ - .. This file is automatically generated. Do not edit this file directly. -Stackdriver Logging Python Samples +Cloud Logging Python Samples =============================================================================== .. image:: https://gstatic.com/cloudssh/images/open-btn.png :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=logging/cloud-client/README.rst -This directory contains samples for Stackdriver Logging. `Stackdriver Logging`_ allows you to store, search, analyze, monitor, and alert on log data and events from Google Cloud Platform and Amazon Web Services. +This directory contains samples for Cloud Logging. `Cloud Logging`_ allows you to store, search, analyze, monitor, and alert on log data and events from Google Cloud Platform and Amazon Web Services. + + + +.. _Cloud Logging: https://cloud.google.com/logging/docs -.. _Stackdriver Logging: https://cloud.google.com/logging/docs Setup ------------------------------------------------------------------------------- - Authentication ++++++++++++++ @@ -31,17 +32,14 @@ credentials for applications. .. _Authentication Getting Started Guide: https://cloud.google.com/docs/authentication/getting-started - - - Install Dependencies ++++++++++++++++++++ -#. Clone python-docs-samples and change directory to the sample directory you want to use. +#. Clone python-logging and change directory to the sample directory you want to use. .. code-block:: bash - $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git + $ git clone https://github.com/googleapis/python-logging.git #. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. @@ -64,15 +62,9 @@ Install Dependencies .. _pip: https://pip.pypa.io/ .. _virtualenv: https://virtualenv.pypa.io/ - - - - - Samples ------------------------------------------------------------------------------- - Quickstart +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ @@ -89,8 +81,6 @@ To run this sample: $ python quickstart.py - - Snippets +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ @@ -106,7 +96,6 @@ To run this sample: $ python snippets.py - usage: snippets.py [-h] logger_name {list,write,delete} ... This application demonstrates how to perform basic operations on logs and @@ -128,8 +117,6 @@ To run this sample: - - Export +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ @@ -145,7 +132,6 @@ To run this sample: $ python export.py - usage: export.py [-h] {list,create,update,delete} ... positional arguments: @@ -168,10 +154,6 @@ To run this sample: - - - - The client library ------------------------------------------------------------------------------- @@ -187,5 +169,4 @@ to `browse the source`_ and `report issues`_. https://github.com/GoogleCloudPlatform/google-cloud-python/issues - -.. _Google Cloud SDK: https://cloud.google.com/sdk/ +.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/samples/snippets/README.rst.in b/samples/snippets/README.rst.in index 00fa4b6b8..ff243c1ce 100644 --- a/samples/snippets/README.rst.in +++ b/samples/snippets/README.rst.in @@ -1,11 +1,11 @@ # This file is used to generate README.rst product: - name: Stackdriver Logging - short_name: Stackdriver Logging + name: Cloud Logging + short_name: Cloud Logging url: https://cloud.google.com/logging/docs description: > - `Stackdriver Logging`_ allows you to store, search, analyze, monitor, + `Cloud Logging`_ allows you to store, search, analyze, monitor, and alert on log data and events from Google Cloud Platform and Amazon Web Services. From d8ff32f2f7285d17d849e38be3ccba3692d8cde5 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim Date: Wed, 11 Nov 2020 23:07:30 +0000 Subject: [PATCH 50/52] chore: regen samples noxfile --- samples/snippets/noxfile.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index 01686e4a0..17300976a 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -39,6 +39,10 @@ # You can opt out from the test for specific Python versions. 'ignored_versions': ["2.7"], + # Old samples are opted out of enforcing Python type hints + # All new samples should feature them + 'enforce_type_hints': False, + # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string @@ -132,7 +136,10 @@ def _determine_local_import_names(start_dir): @nox.session def lint(session): - session.install("flake8", "flake8-import-order") + if not TEST_CONFIG['enforce_type_hints']: + session.install("flake8", "flake8-import-order") + else: + session.install("flake8", "flake8-import-order", "flake8-annotations") local_names = _determine_local_import_names(".") args = FLAKE8_COMMON_ARGS + [ @@ -141,7 +148,16 @@ def lint(session): "." ] session.run("flake8", *args) +# +# Black +# + +@nox.session +def blacken(session): + session.install("black") + python_files = [path for path in os.listdir(".") if path.endswith(".py")] + session.run("black", *python_files) # # Sample Tests From 0d8437a31beaa53dfebd733dc62e6af3251a5a0b Mon Sep 17 00:00:00 2001 From: Bu Sun Kim Date: Wed, 11 Nov 2020 23:09:15 +0000 Subject: [PATCH 51/52] docs: remove stackdriver logging --- samples/snippets/README.rst | 2 +- samples/snippets/snippets.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/snippets/README.rst b/samples/snippets/README.rst index 110ad776e..b3383727d 100644 --- a/samples/snippets/README.rst +++ b/samples/snippets/README.rst @@ -99,7 +99,7 @@ To run this sample: usage: snippets.py [-h] logger_name {list,write,delete} ... This application demonstrates how to perform basic operations on logs and - log entries with Stackdriver Logging. + log entries with Cloud Logging. For more information, see the README.md under /logging and the documentation at https://cloud.google.com/logging/docs. diff --git a/samples/snippets/snippets.py b/samples/snippets/snippets.py index 78f67e8a9..16a7e847b 100644 --- a/samples/snippets/snippets.py +++ b/samples/snippets/snippets.py @@ -15,7 +15,7 @@ # limitations under the License. """This application demonstrates how to perform basic operations on logs and -log entries with Stackdriver Logging. +log entries with Cloud Logging. For more information, see the README.md under /logging and the documentation at https://cloud.google.com/logging/docs. From eab2f268aeb513fe615cb49ab963546ef2b317a9 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim Date: Wed, 11 Nov 2020 23:19:26 +0000 Subject: [PATCH 52/52] chore: run formatter --- samples/snippets/export.py | 79 +++++++++++++---------------- samples/snippets/export_test.py | 22 ++++---- samples/snippets/handler.py | 6 +-- samples/snippets/handler_test.py | 2 +- samples/snippets/noxfile.py | 35 ++++++------- samples/snippets/quickstart.py | 8 +-- samples/snippets/quickstart_test.py | 2 +- samples/snippets/snippets.py | 53 ++++++++++--------- samples/snippets/snippets_test.py | 4 +- 9 files changed, 104 insertions(+), 107 deletions(-) diff --git a/samples/snippets/export.py b/samples/snippets/export.py index f7606ba6c..aa65deeaa 100644 --- a/samples/snippets/export.py +++ b/samples/snippets/export.py @@ -27,10 +27,12 @@ def list_sinks(): sinks = list(logging_client.list_sinks()) if not sinks: - print('No sinks.') + print("No sinks.") for sink in sinks: - print('{}: {} -> {}'.format(sink.name, sink.filter_, sink.destination)) + print("{}: {} -> {}".format(sink.name, sink.filter_, sink.destination)) + + # [END logging_list_sinks] @@ -50,20 +52,18 @@ def create_sink(sink_name, destination_bucket, filter_): # or a BigQuery dataset. In this case, it is a Cloud Storage Bucket. # See https://cloud.google.com/logging/docs/api/tasks/exporting-logs for # information on the destination format. - destination = 'storage.googleapis.com/{bucket}'.format( - bucket=destination_bucket) + destination = "storage.googleapis.com/{bucket}".format(bucket=destination_bucket) - sink = logging_client.sink( - sink_name, - filter_, - destination) + sink = logging_client.sink(sink_name, filter_, destination) if sink.exists(): - print('Sink {} already exists.'.format(sink.name)) + print("Sink {} already exists.".format(sink.name)) return sink.create() - print('Created sink {}'.format(sink.name)) + print("Created sink {}".format(sink.name)) + + # [END logging_create_sink] @@ -83,8 +83,10 @@ def update_sink(sink_name, filter_): sink.reload() sink.filter_ = filter_ - print('Updated sink {}'.format(sink.name)) + print("Updated sink {}".format(sink.name)) sink.update() + + # [END logging_update_sink] @@ -96,50 +98,41 @@ def delete_sink(sink_name): sink.delete() - print('Deleted sink {}'.format(sink.name)) + print("Deleted sink {}".format(sink.name)) + + # [END logging_delete_sink] -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) - subparsers = parser.add_subparsers(dest='command') - subparsers.add_parser('list', help=list_sinks.__doc__) + subparsers = parser.add_subparsers(dest="command") + subparsers.add_parser("list", help=list_sinks.__doc__) - create_parser = subparsers.add_parser('create', help=list_sinks.__doc__) - create_parser.add_argument( - 'sink_name', - help='Name of the log export sink.') - create_parser.add_argument( - 'destination_bucket', - help='Cloud Storage bucket where logs will be exported.') + create_parser = subparsers.add_parser("create", help=list_sinks.__doc__) + create_parser.add_argument("sink_name", help="Name of the log export sink.") create_parser.add_argument( - 'filter', - help='The filter used to match logs.') - - update_parser = subparsers.add_parser('update', help=update_sink.__doc__) - update_parser.add_argument( - 'sink_name', - help='Name of the log export sink.') - update_parser.add_argument( - 'filter', - help='The filter used to match logs.') - - delete_parser = subparsers.add_parser('delete', help=delete_sink.__doc__) - delete_parser.add_argument( - 'sink_name', - help='Name of the log export sink.') + "destination_bucket", help="Cloud Storage bucket where logs will be exported." + ) + create_parser.add_argument("filter", help="The filter used to match logs.") + + update_parser = subparsers.add_parser("update", help=update_sink.__doc__) + update_parser.add_argument("sink_name", help="Name of the log export sink.") + update_parser.add_argument("filter", help="The filter used to match logs.") + + delete_parser = subparsers.add_parser("delete", help=delete_sink.__doc__) + delete_parser.add_argument("sink_name", help="Name of the log export sink.") args = parser.parse_args() - if args.command == 'list': + if args.command == "list": list_sinks() - elif args.command == 'create': + elif args.command == "create": create_sink(args.sink_name, args.destination_bucket, args.filter) - elif args.command == 'update': + elif args.command == "update": update_sink(args.sink_name, args.filter) - elif args.command == 'delete': + elif args.command == "delete": delete_sink(args.sink_name) diff --git a/samples/snippets/export_test.py b/samples/snippets/export_test.py index b787c066a..09dbf9c83 100644 --- a/samples/snippets/export_test.py +++ b/samples/snippets/export_test.py @@ -23,15 +23,15 @@ import export -BUCKET = os.environ['CLOUD_STORAGE_BUCKET'] -TEST_SINK_NAME_TMPL = 'example_sink_{}' -TEST_SINK_FILTER = 'severity>=CRITICAL' +BUCKET = os.environ["CLOUD_STORAGE_BUCKET"] +TEST_SINK_NAME_TMPL = "example_sink_{}" +TEST_SINK_FILTER = "severity>=CRITICAL" def _random_id(): - return ''.join( - random.choice(string.ascii_uppercase + string.digits) - for _ in range(6)) + return "".join( + random.choice(string.ascii_uppercase + string.digits) for _ in range(6) + ) @pytest.yield_fixture @@ -41,7 +41,8 @@ def example_sink(): sink = client.sink( TEST_SINK_NAME_TMPL.format(_random_id()), TEST_SINK_FILTER, - 'storage.googleapis.com/{bucket}'.format(bucket=BUCKET)) + "storage.googleapis.com/{bucket}".format(bucket=BUCKET), + ) sink.create() @@ -67,10 +68,7 @@ def test_create(capsys): sink_name = TEST_SINK_NAME_TMPL.format(_random_id()) try: - export.create_sink( - sink_name, - BUCKET, - TEST_SINK_FILTER) + export.create_sink(sink_name, BUCKET, TEST_SINK_FILTER) # Clean-up the temporary sink. finally: try: @@ -83,7 +81,7 @@ def test_create(capsys): def test_update(example_sink, capsys): - updated_filter = 'severity>=INFO' + updated_filter = "severity>=INFO" export.update_sink(example_sink.name, updated_filter) example_sink.reload() diff --git a/samples/snippets/handler.py b/samples/snippets/handler.py index d59458425..9a63d022f 100644 --- a/samples/snippets/handler.py +++ b/samples/snippets/handler.py @@ -36,14 +36,14 @@ def use_logging_handler(): import logging # The data to log - text = 'Hello, world!' + text = "Hello, world!" # Emits the data using the standard logging module logging.warning(text) # [END logging_handler_usage] - print('Logged: {}'.format(text)) + print("Logged: {}".format(text)) -if __name__ == '__main__': +if __name__ == "__main__": use_logging_handler() diff --git a/samples/snippets/handler_test.py b/samples/snippets/handler_test.py index d48ee2e20..9d635806a 100644 --- a/samples/snippets/handler_test.py +++ b/samples/snippets/handler_test.py @@ -19,4 +19,4 @@ def test_handler(capsys): handler.use_logging_handler() out, _ = capsys.readouterr() - assert 'Logged' in out + assert "Logged" in out diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index 17300976a..ab2c49227 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -37,28 +37,25 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - 'ignored_versions': ["2.7"], - + "ignored_versions": ["2.7"], # Old samples are opted out of enforcing Python type hints # All new samples should feature them - 'enforce_type_hints': False, - + "enforce_type_hints": False, # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string # to use your own Cloud project. - 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. - 'envs': {}, + "envs": {}, } try: # Ensure we can import noxfile_config in the project's directory. - sys.path.append('.') + sys.path.append(".") from noxfile_config import TEST_CONFIG_OVERRIDE except ImportError as e: print("No user noxfile_config found: detail: {}".format(e)) @@ -73,12 +70,12 @@ def get_pytest_env_vars(): ret = {} # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG['gcloud_project_env'] + env_key = TEST_CONFIG["gcloud_project_env"] # This should error out if not set. - ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key] + ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] # Apply user supplied envs. - ret.update(TEST_CONFIG['envs']) + ret.update(TEST_CONFIG["envs"]) return ret @@ -87,7 +84,7 @@ def get_pytest_env_vars(): ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"] # Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] +IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) @@ -136,7 +133,7 @@ def _determine_local_import_names(start_dir): @nox.session def lint(session): - if not TEST_CONFIG['enforce_type_hints']: + if not TEST_CONFIG["enforce_type_hints"]: session.install("flake8", "flake8-import-order") else: session.install("flake8", "flake8-import-order", "flake8-annotations") @@ -145,13 +142,16 @@ def lint(session): args = FLAKE8_COMMON_ARGS + [ "--application-import-names", ",".join(local_names), - "." + ".", ] session.run("flake8", *args) + + # # Black # + @nox.session def blacken(session): session.install("black") @@ -159,6 +159,7 @@ def blacken(session): session.run("black", *python_files) + # # Sample Tests # @@ -198,9 +199,9 @@ def py(session): if session.python in TESTED_VERSIONS: _session_tests(session) else: - session.skip("SKIPPED: {} tests are disabled for this sample.".format( - session.python - )) + session.skip( + "SKIPPED: {} tests are disabled for this sample.".format(session.python) + ) # diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py index 19409c776..7c38ea6fa 100644 --- a/samples/snippets/quickstart.py +++ b/samples/snippets/quickstart.py @@ -24,19 +24,19 @@ def run_quickstart(): logging_client = logging.Client() # The name of the log to write to - log_name = 'my-log' + log_name = "my-log" # Selects the log to write to logger = logging_client.logger(log_name) # The data to log - text = 'Hello, world!' + text = "Hello, world!" # Writes the log entry logger.log_text(text) - print('Logged: {}'.format(text)) + print("Logged: {}".format(text)) # [END logging_quickstart] -if __name__ == '__main__': +if __name__ == "__main__": run_quickstart() diff --git a/samples/snippets/quickstart_test.py b/samples/snippets/quickstart_test.py index 1b49cd126..d8ace2cbc 100644 --- a/samples/snippets/quickstart_test.py +++ b/samples/snippets/quickstart_test.py @@ -19,4 +19,4 @@ def test_quickstart(capsys): quickstart.run_quickstart() out, _ = capsys.readouterr() - assert 'Logged' in out + assert "Logged" in out diff --git a/samples/snippets/snippets.py b/samples/snippets/snippets.py index 16a7e847b..39399dcf7 100644 --- a/samples/snippets/snippets.py +++ b/samples/snippets/snippets.py @@ -35,19 +35,23 @@ def write_entry(logger_name): logger = logging_client.logger(logger_name) # Make a simple text log - logger.log_text('Hello, world!') + logger.log_text("Hello, world!") # Simple text log with severity. - logger.log_text('Goodbye, world!', severity='ERROR') + logger.log_text("Goodbye, world!", severity="ERROR") # Struct log. The struct can be any JSON-serializable dictionary. - logger.log_struct({ - 'name': 'King Arthur', - 'quest': 'Find the Holy Grail', - 'favorite_color': 'Blue' - }) + logger.log_struct( + { + "name": "King Arthur", + "quest": "Find the Holy Grail", + "favorite_color": "Blue", + } + ) + + print("Wrote logs to {}.".format(logger.name)) + - print('Wrote logs to {}.'.format(logger.name)) # [END logging_write_log_entry] @@ -57,12 +61,13 @@ def list_entries(logger_name): logging_client = logging.Client() logger = logging_client.logger(logger_name) - print('Listing entries for logger {}:'.format(logger.name)) + print("Listing entries for logger {}:".format(logger.name)) for entry in logger.list_entries(): timestamp = entry.timestamp.isoformat() - print('* {}: {}'.format - (timestamp, entry.payload)) + print("* {}: {}".format(timestamp, entry.payload)) + + # [END logging_list_log_entries] @@ -77,27 +82,27 @@ def delete_logger(logger_name): logger.delete() - print('Deleted all logging entries for {}'.format(logger.name)) + print("Deleted all logging entries for {}".format(logger.name)) + + # [END logging_delete_log] -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) - parser.add_argument( - 'logger_name', help='Logger name', default='example_log') - subparsers = parser.add_subparsers(dest='command') - subparsers.add_parser('list', help=list_entries.__doc__) - subparsers.add_parser('write', help=write_entry.__doc__) - subparsers.add_parser('delete', help=delete_logger.__doc__) + parser.add_argument("logger_name", help="Logger name", default="example_log") + subparsers = parser.add_subparsers(dest="command") + subparsers.add_parser("list", help=list_entries.__doc__) + subparsers.add_parser("write", help=write_entry.__doc__) + subparsers.add_parser("delete", help=delete_logger.__doc__) args = parser.parse_args() - if args.command == 'list': + if args.command == "list": list_entries(args.logger_name) - elif args.command == 'write': + elif args.command == "write": write_entry(args.logger_name) - elif args.command == 'delete': + elif args.command == "delete": delete_logger(args.logger_name) diff --git a/samples/snippets/snippets_test.py b/samples/snippets/snippets_test.py index 1d1d01972..479f742ae 100644 --- a/samples/snippets/snippets_test.py +++ b/samples/snippets/snippets_test.py @@ -22,14 +22,14 @@ import snippets -TEST_LOGGER_NAME = 'example_log_{}'.format(uuid.uuid4().hex) +TEST_LOGGER_NAME = "example_log_{}".format(uuid.uuid4().hex) @pytest.fixture def example_log(): client = logging.Client() logger = client.logger(TEST_LOGGER_NAME) - text = 'Hello, world.' + text = "Hello, world." logger.log_text(text) return text