genkit-google-cloud 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,246 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """GCP Cloud Logging integration for Genkit telemetry.
18
+
19
+ This module provides a logger that writes structured logs directly to
20
+ Google Cloud Logging with trace correlation, enabling visibility in
21
+ the Firebase AIM dashboard.
22
+
23
+ This is analogous to the JavaScript implementation in:
24
+ - js/plugins/google-cloud/src/gcpLogger.ts
25
+
26
+ Usage:
27
+ from genkit_google_cloud.telemetry.gcp_logger import gcp_logger
28
+
29
+ # Initialize during telemetry setup
30
+ gcp_logger.initialize(project_id="my-project", credentials=creds, export=True)
31
+
32
+ # Write structured logs
33
+ gcp_logger.log_structured("Input[path, feature]", {"content": "...", "traceId": "..."})
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ from typing import TYPE_CHECKING, Any
39
+
40
+ import structlog
41
+ from google.auth.credentials import Credentials
42
+ from opentelemetry import trace
43
+
44
+ if TYPE_CHECKING:
45
+ from google.cloud.logging_v2 import Logger as CloudLogger
46
+
47
+ logger = structlog.get_logger(__name__)
48
+
49
+
50
+ class GcpLogger:
51
+ """Logger for writing structured logs to Cloud Logging.
52
+
53
+ This class provides a simple interface for writing logs that appear
54
+ in the Firebase AIM dashboard. It writes directly to Cloud Logging
55
+ using the google-cloud-logging client library.
56
+ """
57
+
58
+ def __init__(self) -> None:
59
+ """Initialize logger state."""
60
+ self._initialized = False
61
+ self._export = False
62
+ self._project_id: str | None = None
63
+ self._cloud_logger: CloudLogger | None = None
64
+
65
+ def initialize(
66
+ self,
67
+ *,
68
+ project_id: str | None = None,
69
+ credentials: Credentials | dict[str, Any] | None = None,
70
+ export: bool = False,
71
+ ) -> None:
72
+ """Initialize the GCP logger.
73
+
74
+ This method MUST be called before any log_structured() calls.
75
+
76
+ Args:
77
+ project_id: GCP project ID (required if export=True).
78
+ credentials: GCP credentials (Credentials object or dict).
79
+ export: Whether to export logs to Cloud Logging (GCP).
80
+
81
+ Behavior:
82
+ - export=False: Local logging only (console output)
83
+ - export=True: Logs sent to Cloud Logging for AIM visibility
84
+ """
85
+ if self._initialized:
86
+ logger.debug('GcpLogger already initialized, skipping re-initialization')
87
+ return
88
+
89
+ self._export = export
90
+ self._project_id = project_id
91
+
92
+ if not export:
93
+ logger.info(
94
+ 'GcpLogger initialized in LOCAL mode',
95
+ export=False,
96
+ project_id=project_id or '<not-set>',
97
+ note='Logs written to console only, not exported to GCP',
98
+ )
99
+ self._initialized = True
100
+ return
101
+
102
+ # Export mode: validate required configuration
103
+ if not project_id:
104
+ logger.error(
105
+ 'GcpLogger initialization FAILED: project_id required for export=True',
106
+ export=True,
107
+ project_id=None,
108
+ consequence='Telemetry logs will NOT appear in Cloud Logging or AIM dashboard',
109
+ fix='Provide project_id when calling enable_google_cloud_telemetry()',
110
+ )
111
+ self._initialized = True # Mark initialized to prevent repeated errors
112
+ return
113
+
114
+ try:
115
+ from google.cloud import logging as cloud_logging
116
+
117
+ # Cloud Logging Client accepts Credentials object or None
118
+ # If credentials is a dict, let it use Application Default Credentials
119
+ creds = credentials if isinstance(credentials, Credentials) else None
120
+
121
+ client = cloud_logging.Client(
122
+ project=project_id,
123
+ credentials=creds,
124
+ )
125
+ self._cloud_logger = client.logger('genkit_log')
126
+ logger.info(
127
+ 'GcpLogger initialized for CLOUD LOGGING export',
128
+ export=True,
129
+ project_id=project_id,
130
+ log_name='genkit_log',
131
+ consequence='Logs will appear in Cloud Logging and AIM dashboard',
132
+ )
133
+ except ImportError:
134
+ logger.error(
135
+ 'GcpLogger initialization FAILED: google-cloud-logging not installed',
136
+ export=True,
137
+ project_id=project_id,
138
+ consequence='Telemetry logs will NOT be exported to Cloud Logging',
139
+ fix='Install with: pip install google-cloud-logging>=3.10.0',
140
+ )
141
+ except Exception as e:
142
+ logger.error(
143
+ 'GcpLogger initialization FAILED: Cloud Logging client error',
144
+ export=True,
145
+ project_id=project_id,
146
+ error=str(e),
147
+ error_type=type(e).__name__,
148
+ consequence='Telemetry logs will NOT be exported to Cloud Logging',
149
+ fix='Check credentials and project_id, ensure GCP access is configured',
150
+ )
151
+
152
+ self._initialized = True
153
+
154
+ def _get_trace_context(self) -> dict[str, str]:
155
+ """Extract trace context from current span if available.
156
+
157
+ Returns:
158
+ Dictionary with trace fields for Cloud Logging, empty if no trace.
159
+ """
160
+ span = trace.get_current_span()
161
+ if not (span and span.is_recording()):
162
+ return {}
163
+
164
+ ctx = span.get_span_context()
165
+ if not (ctx and ctx.trace_id):
166
+ return {}
167
+
168
+ trace_id = format(ctx.trace_id, '032x')
169
+ span_id = format(ctx.span_id, '016x')
170
+
171
+ return {
172
+ 'logging.googleapis.com/trace': (
173
+ f'projects/{self._project_id}/traces/{trace_id}' if self._project_id else trace_id
174
+ ),
175
+ 'logging.googleapis.com/spanId': span_id,
176
+ 'logging.googleapis.com/trace_sampled': str(ctx.trace_flags.sampled),
177
+ }
178
+
179
+ def _write(self, message: str, payload: dict[str, Any], severity: str) -> None:
180
+ """Write log to Cloud Logging or fallback to console.
181
+
182
+ Args:
183
+ message: Log message for fallback logging.
184
+ payload: Structured payload with all metadata.
185
+ severity: Cloud Logging severity (INFO, ERROR).
186
+ """
187
+ if self._export and self._cloud_logger:
188
+ try:
189
+ self._cloud_logger.log_struct(payload, severity=severity, labels={'module': 'genkit'})
190
+ except Exception as e:
191
+ logger.error('Failed to write to Cloud Logging', error=str(e), message=message)
192
+ # Fallback to console
193
+ if severity == 'ERROR':
194
+ logger.error(message, **payload)
195
+ else:
196
+ logger.info(message, **payload)
197
+ else:
198
+ if severity == 'ERROR':
199
+ logger.error(message, **payload)
200
+ else:
201
+ logger.info(message, **payload)
202
+
203
+ def log_structured(self, message: str, metadata: dict[str, Any] | None = None) -> None:
204
+ """Write a structured log entry.
205
+
206
+ This method is called by telemetry handlers to write structured logs.
207
+ If not initialized, logs an error once and falls back to console logging.
208
+
209
+ Args:
210
+ message: Log message.
211
+ metadata: Additional structured metadata.
212
+ """
213
+ if not self._initialized:
214
+ # Log error ONCE to avoid spam
215
+ if not hasattr(self, '_logged_init_error'):
216
+ logger.error(
217
+ 'gcp_logger.log_structured() called before initialization',
218
+ message=message,
219
+ hint='Ensure enable_google_cloud_telemetry() or gcp_logger.initialize() was called',
220
+ )
221
+ self._logged_init_error = True
222
+
223
+ # Fall back to console logging for debugging
224
+ logger.warning(f'[FALLBACK] {message}', **(metadata or {}))
225
+ return
226
+
227
+ payload = metadata.copy() if metadata else {}
228
+ payload['message'] = message
229
+ payload.update(self._get_trace_context())
230
+ self._write(message, payload, 'INFO')
231
+
232
+ def log_structured_error(self, message: str, metadata: dict[str, Any] | None = None) -> None:
233
+ """Write a structured error log entry.
234
+
235
+ Args:
236
+ message: Log message.
237
+ metadata: Additional structured metadata.
238
+ """
239
+ payload = metadata.copy() if metadata else {}
240
+ payload['message'] = message
241
+ payload.update(self._get_trace_context())
242
+ self._write(message, payload, 'ERROR')
243
+
244
+
245
+ # Singleton instance
246
+ gcp_logger = GcpLogger()