### Install google-cloud-logging Source: https://context7.com/googleapis/python-logging/llms.txt Install the library using pip. Ensure you are in a virtual environment. ```bash python -m venv venv source venv/bin/activate # Mac / Linux # venv\Scripts\activate # Windows pip install google-cloud-logging ``` -------------------------------- ### Install google-cloud-logging on Windows Source: https://github.com/googleapis/python-logging/blob/main/README.rst Use these commands to install the library in a virtual environment on Windows systems. ```console python -m venv \Scripts\activate \Scripts\pip.exe install google-cloud-logging ``` -------------------------------- ### Install google-cloud-logging on Mac/Linux Source: https://github.com/googleapis/python-logging/blob/main/README.rst Use this command to install the library in a virtual environment on Mac or Linux systems. ```console python -m venv source /bin/activate /bin/pip install google-cloud-logging ``` -------------------------------- ### Setup Standard Logging Integration Source: https://context7.com/googleapis/python-logging/llms.txt Attaches a handler to Python's root logger, forwarding all standard log records to Cloud Logging automatically. ```APIDOC ## Attaching to Python's Standard `logging` Module ### Description The simplest integration — a single call routes all standard-library log records to Cloud Logging. ### Method ```python import logging import google.cloud.logging # Set up the Cloud Logging handler client = google.cloud.logging.Client(project="my-gcp-project") client.setup_logging() # attaches handler to the root logger # Now use the standard library as usual logger = logging.getLogger(__name__) logger.info("Application started") logger.warning("Disk usage above 80%%") logger.error("Unhandled exception", exc_info=True) ``` ### Usage After calling `client.setup_logging()`, standard Python logging calls like `logging.info()`, `logging.warning()`, etc., will automatically send logs to Cloud Logging. These logs will appear under the default log name "python" with their respective severity levels. ``` -------------------------------- ### Initialize Cloud Logging Client Source: https://context7.com/googleapis/python-logging/llms.txt Initialize the client using Application Default Credentials. For local development, run `gcloud auth application-default login`. ```python import google.cloud.logging # Uses Application Default Credentials automatically client = google.cloud.logging.Client(project="my-gcp-project") ``` -------------------------------- ### List All Log Sinks in Project Source: https://context7.com/googleapis/python-logging/llms.txt Iterate through and print the names and destinations of all log sinks configured in the current Google Cloud project. ```python from google.cloud import logging as cloud_logging client = cloud_logging.Client(project="my-gcp-project") # List all sinks in the project for s in client.list_sinks(): print(s.name, "->", s.destination) ``` -------------------------------- ### Initialize Client Source: https://context7.com/googleapis/python-logging/llms.txt Initializes the Cloud Logging client using Application Default Credentials. You can optionally specify the GCP project ID. ```APIDOC ## Initialize Client ### Description Initializes the Cloud Logging client using Application Default Credentials. You can optionally specify the GCP project ID. ### Method ```python import google.cloud.logging client = google.cloud.logging.Client(project="my-gcp-project") ``` ### Parameters * **project** (string) - Optional - The GCP project ID to use for logging operations. ``` -------------------------------- ### Create a Log Sink Source: https://context7.com/googleapis/python-logging/llms.txt Configures a log sink to export matching log entries to Cloud Storage, BigQuery, or Pub/Sub in real time. ```APIDOC ## Creating a Log Sink (Export) ### Description Sinks export matching log entries to Cloud Storage, BigQuery, or Pub/Sub in real time. ### Method ```python from google.cloud import logging as cloud_logging client = cloud_logging.Client(project="my-gcp-project") # Export ERROR logs to a Cloud Storage bucket sink = client.sink( "error-logs-to-gcs", filter_='severity="ERROR"', destination="storage.googleapis.com/my-log-archive-bucket", ) if not sink.exists(): sink.create() print(f"Sink '{sink.name}' created.") else: print(f"Sink '{sink.name}' already exists.") # List all sinks in the project for s in client.list_sinks(): print(s.name, "->", s.destination) ``` ### Parameters * **sink name** (string) - The name of the log sink. * **filter_** (string) - A filter expression to determine which log entries are exported. * **destination** (string) - The destination for the exported logs (e.g., a Cloud Storage bucket, BigQuery dataset, or Pub/Sub topic). ### Usage This method allows you to create and manage log sinks for exporting logs. You can specify a filter to select specific logs and a destination for the export. The code also demonstrates how to check if a sink already exists and how to list all existing sinks in the project. ``` -------------------------------- ### List Project-Wide Log Entries with Filter Source: https://context7.com/googleapis/python-logging/llms.txt Retrieve log entries across the entire project using a filter based on resource type, severity, and timestamp. Useful for broad log analysis. ```python from google.cloud import logging as cloud_logging client = cloud_logging.Client(project="my-gcp-project") # List entries project-wide with a filter FILTER = ( 'resource.type="gce_instance" ' 'severity>=WARNING ' 'timestamp>="2024-01-01T00:00:00Z"' ) all_entries = client.list_entries(filter_=FILTER, page_size=50) for entry in all_entries: print(entry.insert_id, entry.payload) ``` -------------------------------- ### Write Structured Log Entry with Monitored Resource Source: https://context7.com/googleapis/python-logging/llms.txt Write a structured (JSON) log entry with a custom monitored resource and labels. This provides more context for log analysis. ```python from google.cloud import logging as cloud_logging from google.cloud.logging import Resource client = cloud_logging.Client(project="my-gcp-project") logger = client.logger("my-application-log") # Write a structured (JSON) entry with a custom monitored resource resource = Resource( type="gce_instance", labels={"instance_id": "1234567890", "zone": "us-central1-a"}, ) logger.log_struct( { "event": "user_login", "user_id": "u-42", "ip_address": "203.0.113.5", "latency_ms": 47, }, severity="INFO", resource=resource, labels={"version": "2.3.1"}, ) print("Entries written successfully.") ``` -------------------------------- ### Create a Logs-Based Metric Source: https://context7.com/googleapis/python-logging/llms.txt Creates a logs-based metric to count log entries matching a filter. Ensure the metric does not already exist before creating. ```python from google.cloud import logging as cloud_logging client = cloud_logging.Client(project="my-gcp-project") metric = client.metric( "error_count", filter_='severity="ERROR"', description="Count of ERROR-level log entries across all resources.", ) if not metric.exists(): metric.create() print(f"Metric '{metric.name}' created.") # Reload and inspect metric.reload() print("Filter:", metric.filter_) print("Description:", metric.description) ``` -------------------------------- ### Create Log Sink for Error Logs to GCS Source: https://context7.com/googleapis/python-logging/llms.txt Create a log sink to export ERROR severity logs to a specified Cloud Storage bucket in real time. Checks if the sink already exists. ```python from google.cloud import logging as cloud_logging client = cloud_logging.Client(project="my-gcp-project") # Export ERROR logs to a Cloud Storage bucket sink = client.sink( "error-logs-to-gcs", filter_='severity="ERROR"', destination="storage.googleapis.com/my-log-archive-bucket", ) if not sink.exists(): sink.create() print(f"Sink '{sink.name}' created.") else: print(f"Sink '{sink.name}' already exists.") ``` -------------------------------- ### Structured Logging with HTTP Request Metadata Source: https://context7.com/googleapis/python-logging/llms.txt Includes HTTP request context in log entries for correlation with load balancer traces. Requires setting up a Cloud Logging handler for the standard Python logger. ```python from google.cloud import logging as cloud_logging from google.cloud.logging_v2.handlers import CloudLoggingHandler import logging client = cloud_logging.Client(project="my-gcp-project") handler = CloudLoggingHandler(client, name="http-requests") std_logger = logging.getLogger("http_logger") std_logger.setLevel(logging.DEBUG) std_logger.addHandler(handler) http_request = { "requestMethod": "GET", "requestUrl": "/api/v1/users/42", "status": 200, "responseSize": 1024, "userAgent": "Mozilla/5.0", "remoteIp": "203.0.113.10", "latency": "0.023s", } std_logger.info( "Request handled", extra={"http_request": http_request, "trace": "projects/my-gcp-project/traces/abc123"}, ) ``` -------------------------------- ### Attach Logging Handler to Standard Library Source: https://context7.com/googleapis/python-logging/llms.txt Attaches a handler to the root logger to automatically forward all standard library log records to Cloud Logging. ```python import logging import google.cloud.logging # Set up the Cloud Logging handler client = google.cloud.logging.Client(project="my-gcp-project") client.setup_logging() # attaches handler to the root logger # Now use the standard library as usual logging = logging.getLogger(__name__) logging.info("Application started") logging.warning("Disk usage above 80%%") logging.error("Unhandled exception", exc_info=True) # Expected: each record appears in Cloud Logging under the default log name # "python" with the appropriate severity (INFO, WARNING, ERROR). ``` -------------------------------- ### Write Plain Text Log Entry Source: https://context7.com/googleapis/python-logging/llms.txt Write a simple text log entry using the logger object. Specify the severity level. ```python from google.cloud import logging as cloud_logging client = cloud_logging.Client(project="my-gcp-project") logger = client.logger("my-application-log") # Write a plain text entry logger.log_text("Server started on port 8080", severity="INFO") ``` -------------------------------- ### List Log Entries Source: https://context7.com/googleapis/python-logging/llms.txt Retrieves log entries from Cloud Logging using filters defined in the Cloud Logging query language. ```APIDOC ## Reading / Listing Log Entries ### Description Retrieve log entries from Cloud Logging using filters written in the [Cloud Logging query language](https://cloud.google.com/logging/docs/view/query-library). ### Method ```python from google.cloud import logging as cloud_logging client = cloud_logging.Client(project="my-gcp-project") logger = client.logger("my-application-log") # List the 10 most recent entries for this logger entries = list(logger.list_entries(page_size=10)) for entry in entries: print(f"[{entry.severity}] {entry.timestamp} — {entry.payload}") # List entries project-wide with a filter FILTER = ( 'resource.type="gce_instance" ' 'severity>=WARNING ' 'timestamp>="2024-01-01T00:00:00Z"' ) all_entries = client.list_entries(filter_=FILTER, page_size=50) for entry in all_entries: print(entry.insert_id, entry.payload) ``` ### Parameters * **logger name** (string) - The name of the logger to retrieve entries from. * **filter_** (string) - A filter expression in the Cloud Logging query language to narrow down the results. * **page_size** (int) - The maximum number of entries to return per page. ``` -------------------------------- ### List Log Entries for a Specific Logger Source: https://context7.com/googleapis/python-logging/llms.txt Retrieve and print log entries for a specific logger, ordered by timestamp. Uses the Cloud Logging query language for filtering. ```python from google.cloud import logging as cloud_logging client = cloud_logging.Client(project="my-gcp-project") logger = client.logger("my-application-log") # List the 10 most recent entries for this logger entries = list(logger.list_entries(page_size=10)) for entry in entries: print(f"[{entry.severity}] {entry.timestamp} — {entry.payload}") ``` -------------------------------- ### Write Log Entries Directly Source: https://context7.com/googleapis/python-logging/llms.txt Uses the `Logger` object for explicit, structured log writes, allowing fine-grained control over log content and metadata. ```APIDOC ## Writing Log Entries Directly ### Description Use the `Logger` object for explicit, structured log writes without going through the standard `logging` module. ### Method ```python from google.cloud import logging as cloud_logging from google.cloud.logging import Resource client = cloud_logging.Client(project="my-gcp-project") logger = client.logger("my-application-log") # Write a plain text entry logger.log_text("Server started on port 8080", severity="INFO") # Write a structured (JSON) entry with a custom monitored resource resource = Resource( type="gce_instance", labels={"instance_id": "1234567890", "zone": "us-central1-a"}, ) logger.log_struct( { "event": "user_login", "user_id": "u-42", "ip_address": "203.0.113.5", "latency_ms": 47, }, severity="INFO", resource=resource, labels={"version": "2.3.1"}, ) ``` ### Parameters * **logger name** (string) - The name of the log to write to. * **text payload** (string) - The plain text content of the log entry. * **struct payload** (dict) - A dictionary representing the structured (JSON) payload of the log entry. * **severity** (string) - Optional - The severity level of the log entry (e.g., "INFO", "WARNING", "ERROR"). * **resource** (google.cloud.logging.Resource) - Optional - A `Resource` object specifying the monitored resource associated with the log entry. * **labels** (dict) - Optional - A dictionary of labels to attach to the log entry. ``` -------------------------------- ### Delete a Logger and Its Entries Source: https://context7.com/googleapis/python-logging/llms.txt Deletes a specified logger and all log entries associated with it. Use with caution as this action is irreversible. ```python from google.cloud import logging as cloud_logging client = cloud_logging.Client(project="my-gcp-project") logger = client.logger("my-application-log") logger.delete() print(f"Logger '{logger.name}' and all its entries deleted.") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.