Skip to content

Commit 4cbf107

Browse files
authored
feat(logging): update write_entry snippet to use Python logging framework (#14361)
* feat(logging): update write_entry snippet to use Python logging framework - Update `write_entry` in `snippets.py` to use `google.cloud.logging.setup_logging()` instead of calling the client logger methods directly. - Demonstrate writing a structured JSON log using the standard `logging` library's `extra` parameter. - Update `test_write` in `snippets_test.py` to verify logs written via the default python logging handler. - Remove python version constraint for pytest in `requirements-test.txt`. * linting import orders * Fix gemini suggestions and lint more import order. * Overhaul comments by request. * more comment overhaul
1 parent e72ad32 commit 4cbf107

3 files changed

Lines changed: 43 additions & 26 deletions

File tree

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
backoff==2.2.1
2-
pytest==9.0.3; python_version >= "3.10"
2+
pytest==9.0.3

logging/samples/snippets/snippets.py

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -22,35 +22,39 @@
2222
"""
2323

2424
import argparse
25+
import time
2526

26-
from google.cloud import logging
27+
import google.cloud.logging
28+
29+
import logging
2730

2831

2932
# [START logging_write_log_entry]
30-
def write_entry(logger_name):
31-
"""Writes log entries to the given logger."""
32-
logging_client = logging.Client()
33+
def write_entry():
34+
"""Demonstrates how to write log entries to Google Cloud using Python's standard logging library."""
35+
logging_client = google.cloud.logging.Client()
3336

34-
# This log can be found in the Cloud Logging console under 'Custom Logs'.
35-
logger = logging_client.logger(logger_name)
37+
# By default, logs route to projects/[PROJECT_ID]/logs/python
38+
# unless overridden by GCP or custom handlers.
39+
logging_client.setup_logging(log_level=logging.INFO)
3640

3741
# Make a simple text log
38-
logger.log_text("Hello, world!")
42+
logging.info("Hello, world!")
3943

4044
# Simple text log with severity.
41-
logger.log_text("Goodbye, world!", severity="WARNING")
42-
43-
# Struct log. The struct can be any JSON-serializable dictionary.
44-
logger.log_struct(
45-
{
46-
"name": "King Arthur",
47-
"quest": "Find the Holy Grail",
48-
"favorite_color": "Blue",
49-
},
50-
severity="INFO",
51-
)
45+
logging.warning("Goodbye, world!")
46+
47+
# Prepare your structured data as a dictionary.
48+
json_log = {
49+
"name": "King Arthur",
50+
"quest": "Find the Holy Grail",
51+
"favorite_color": "Blue",
52+
}
53+
54+
logging.info("This is a JSON log.", extra={"json_fields": json_log})
5255

53-
print("Wrote logs to {}.".format(logger.name))
56+
# wait for threads to finish working on the background.
57+
time.sleep(5)
5458

5559

5660
# [END logging_write_log_entry]
@@ -105,6 +109,6 @@ def delete_logger(logger_name):
105109
if args.command == "list":
106110
list_entries(args.logger_name)
107111
elif args.command == "write":
108-
write_entry(args.logger_name)
112+
write_entry()
109113
elif args.command == "delete":
110114
delete_logger(args.logger_name)

logging/samples/snippets/snippets_test.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
import os
1516
import uuid
1617

1718
import backoff
@@ -21,9 +22,10 @@
2122

2223
import snippets
2324

24-
2525
TEST_LOGGER_NAME = "example_log_{}".format(uuid.uuid4().hex)
2626
TEST_TEXT = "Hello, world."
27+
GOOGLE_CLOUD_PROJECT = os.getenv("GOOGLE_CLOUD_PROJECT")
28+
DEFAULT_LOGGER = f"projects/{GOOGLE_CLOUD_PROJECT}/logs/python"
2729

2830

2931
@pytest.fixture
@@ -47,13 +49,24 @@ def eventually_consistent_test():
4749

4850
def test_write(capsys):
4951

50-
snippets.write_entry(TEST_LOGGER_NAME)
52+
snippets.write_entry()
5153

5254
@backoff.on_exception(backoff.expo, AssertionError, max_time=120)
5355
def eventually_consistent_test():
54-
snippets.list_entries(TEST_LOGGER_NAME)
55-
out, _ = capsys.readouterr()
56-
assert TEST_TEXT in out
56+
# retrieve logs
57+
client = logging.Client()
58+
59+
log_filter = DEFAULT_LOGGER
60+
61+
entries = client.list_entries(
62+
filter_=log_filter, order_by=logging.DESCENDING, max_results=3
63+
)
64+
65+
retrieved_entries = list(entries)
66+
67+
assert retrieved_entries[0].payload["message"] == "This is a JSON log."
68+
assert retrieved_entries[1].payload == "Goodbye, world!"
69+
assert retrieved_entries[2].payload == "Hello, world!"
5770

5871
eventually_consistent_test()
5972

0 commit comments

Comments
 (0)