Skip to content

Commit ffdb12e

Browse files
authored
docs: Refactor logging to use standard library integration
Per b/234303347
1 parent d2ce99a commit ffdb12e

1 file changed

Lines changed: 30 additions & 23 deletions

File tree

logging/samples/snippets/snippets.py

Lines changed: 30 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -27,30 +27,37 @@
2727

2828

2929
# [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-
34-
# This log can be found in the Cloud Logging console under 'Custom Logs'.
35-
logger = logging_client.logger(logger_name)
36-
37-
# Make a simple text log
38-
logger.log_text("Hello, world!")
30+
import logging
31+
import google.cloud.logging
3932

40-
# 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-
)
52-
53-
print("Wrote logs to {}.".format(logger.name))
33+
def write_entry(logger_name):
34+
"""Writes log entries using the Python standard library integration."""
35+
# Instantiate Cloud Logging client
36+
client = google.cloud.logging.Client()
37+
38+
# Set up standard library integration
39+
# Attaches the CloudLoggingHandler to the root logger.
40+
# The 'name' parameter sets the destination log ID in Cloud Logging.
41+
client.setup_logging(name=logger_name)
42+
43+
# Simple text log
44+
logging.info("Hello, world!")
45+
46+
# Simple text log with severity
47+
# Standard Python logging levels map to Cloud Logging severities.
48+
logging.warning("Goodbye, world!")
49+
50+
# Structured log (JSON payload)
51+
# Use the 'json_fields' key in the 'extra' argument to log a dictionary.
52+
# Data will appear as the jsonPayload in the Cloud Logging entry.
53+
data_dict = {
54+
"name": "King Arthur",
55+
"quest": "Find the Holy Grail",
56+
"favorite_color": "Blue",
57+
}
58+
logging.info("Quest details", extra={"json_fields": data_dict})
59+
60+
print(f"Wrote logs to {logger_name}.")
5461

5562

5663
# [END logging_write_log_entry]

0 commit comments

Comments
 (0)