-
Notifications
You must be signed in to change notification settings - Fork 52
/
entries.py
347 lines (288 loc) · 10.9 KB
/
entries.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# Copyright 2016 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.
"""Log entries within the Google Cloud Logging API."""
import collections
import json
import re
from google.protobuf.any_pb2 import Any
from google.protobuf.json_format import MessageToDict
from google.protobuf.json_format import Parse
from google.cloud.logging_v2.resource import Resource
from google.cloud._helpers import _name_from_project_path
from google.cloud._helpers import _rfc3339_nanos_to_datetime
from google.cloud._helpers import _datetime_to_rfc3339
# import officially supported proto definitions
import google.cloud.audit.audit_log_pb2 # noqa: F401
import google.cloud.appengine_logging # noqa: F401
_GLOBAL_RESOURCE = Resource(type="global", labels={})
_LOGGER_TEMPLATE = re.compile(
r"""
projects/ # static prefix
(?P<project>[^/]+) # initial letter, wordchars + hyphen
/logs/ # static midfix
(?P<name>[^/]+) # initial letter, wordchars + allowed punc
""",
re.VERBOSE,
)
def logger_name_from_path(path):
"""Validate a logger URI path and get the logger name.
Args:
path (str): URI path for a logger API request
Returns:
str: Logger name parsed from ``path``.
Raises:
ValueError: If the ``path`` is ill-formed of if the project
from ``path`` does not agree with the ``project`` passed in.
"""
return _name_from_project_path(path, None, _LOGGER_TEMPLATE)
def _int_or_none(value):
"""Helper: return an integer or ``None``."""
if value is not None:
value = int(value)
return value
_LOG_ENTRY_FIELDS = ( # (name, default)
("log_name", None),
("labels", None),
("insert_id", None),
("severity", None),
("http_request", None),
("timestamp", None),
("resource", _GLOBAL_RESOURCE),
("trace", None),
("span_id", None),
("trace_sampled", None),
("source_location", None),
("operation", None),
("logger", None),
("payload", None),
)
_LogEntryTuple = collections.namedtuple(
"LogEntry", (field for field, _ in _LOG_ENTRY_FIELDS)
)
_LogEntryTuple.__new__.__defaults__ = tuple(default for _, default in _LOG_ENTRY_FIELDS)
_LOG_ENTRY_PARAM_DOCSTRING = """\
Args:
log_name (str): The name of the logger used to post the entry.
labels (Optional[dict]): Mapping of labels for the entry
insert_id (Optional[str]): The ID used to identify an entry
uniquely.
severity (Optional[str]): The severity of the event being logged.
http_request (Optional[dict]): Info about HTTP request associated
with the entry.
timestamp (Optional[datetime.datetime]): Timestamp for the entry.
resource (Optional[google.cloud.logging_v2.resource.Resource]):
Monitored resource of the entry.
trace (Optional[str]): Trace ID to apply to the entry.
span_id (Optional[str]): Span ID within the trace for the log
entry. Specify the trace parameter if ``span_id`` is set.
trace_sampled (Optional[bool]): The sampling decision of the trace
associated with the log entry.
source_location (Optional[dict]): Location in source code from which
the entry was emitted.
operation (Optional[dict]): Additional information about a potentially
long-running operation associated with the log entry.
logger (logging_v2.logger.Logger): the logger used
to write the entry.
"""
_LOG_ENTRY_SEE_ALSO_DOCSTRING = """\
See:
https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
"""
class LogEntry(_LogEntryTuple):
__doc__ = (
"""
Log entry.
"""
+ _LOG_ENTRY_PARAM_DOCSTRING
+ _LOG_ENTRY_SEE_ALSO_DOCSTRING
)
received_timestamp = None
@classmethod
def _extract_payload(cls, resource):
"""Helper for :meth:`from_api_repr`"""
return None
@classmethod
def from_api_repr(cls, resource, client, *, loggers=None):
"""Construct an entry given its API representation
Args:
resource (dict): text entry resource representation returned from
the API
client (~logging_v2.client.Client):
Client which holds credentials and project configuration.
loggers (Optional[dict]):
A mapping of logger fullnames -> loggers. If not
passed, the entry will have a newly-created logger.
Returns:
google.cloud.logging.entries.LogEntry: Log entry parsed from ``resource``.
"""
if loggers is None:
loggers = {}
logger_fullname = resource["logName"]
logger = loggers.get(logger_fullname)
if logger is None:
logger_name = logger_name_from_path(logger_fullname)
logger = loggers[logger_fullname] = client.logger(logger_name)
payload = cls._extract_payload(resource)
insert_id = resource.get("insertId")
timestamp = resource.get("timestamp")
if timestamp is not None:
timestamp = _rfc3339_nanos_to_datetime(timestamp)
labels = resource.get("labels")
severity = resource.get("severity")
http_request = resource.get("httpRequest")
trace = resource.get("trace")
span_id = resource.get("spanId")
trace_sampled = resource.get("traceSampled")
source_location = resource.get("sourceLocation")
if source_location is not None:
line = source_location.pop("line", None)
source_location["line"] = _int_or_none(line)
operation = resource.get("operation")
monitored_resource_dict = resource.get("resource")
monitored_resource = None
if monitored_resource_dict is not None:
monitored_resource = Resource._from_dict(monitored_resource_dict)
inst = cls(
log_name=logger_fullname,
insert_id=insert_id,
timestamp=timestamp,
labels=labels,
severity=severity,
http_request=http_request,
resource=monitored_resource,
trace=trace,
span_id=span_id,
trace_sampled=trace_sampled,
source_location=source_location,
operation=operation,
logger=logger,
payload=payload,
)
received = resource.get("receiveTimestamp")
if received is not None:
inst.received_timestamp = _rfc3339_nanos_to_datetime(received)
return inst
def to_api_repr(self):
"""API repr (JSON format) for entry."""
info = {}
if self.log_name is not None:
info["logName"] = self.log_name
if self.resource is not None:
info["resource"] = self.resource._to_dict()
if self.labels is not None:
info["labels"] = self.labels
if self.insert_id is not None:
info["insertId"] = self.insert_id
if self.severity is not None:
info["severity"] = self.severity
if self.http_request is not None:
info["httpRequest"] = self.http_request
if self.timestamp is not None:
info["timestamp"] = _datetime_to_rfc3339(self.timestamp)
if self.trace is not None:
info["trace"] = self.trace
if self.span_id is not None:
info["spanId"] = self.span_id
if self.trace_sampled is not None:
info["traceSampled"] = self.trace_sampled
if self.source_location is not None:
source_location = self.source_location.copy()
source_location["line"] = str(source_location.pop("line", 0))
info["sourceLocation"] = source_location
if self.operation is not None:
info["operation"] = self.operation
return info
class TextEntry(LogEntry):
__doc__ = (
"""
Log entry with text payload.
"""
+ _LOG_ENTRY_PARAM_DOCSTRING
+ """
payload (str): payload for the log entry.
"""
+ _LOG_ENTRY_SEE_ALSO_DOCSTRING
)
@classmethod
def _extract_payload(cls, resource):
"""Helper for :meth:`from_api_repr`"""
return resource["textPayload"]
def to_api_repr(self):
"""API repr (JSON format) for entry."""
info = super(TextEntry, self).to_api_repr()
info["textPayload"] = self.payload
return info
class StructEntry(LogEntry):
__doc__ = (
"""
Log entry with JSON payload.
"""
+ _LOG_ENTRY_PARAM_DOCSTRING
+ """
payload (dict): payload for the log entry.
"""
+ _LOG_ENTRY_SEE_ALSO_DOCSTRING
)
@classmethod
def _extract_payload(cls, resource):
"""Helper for :meth:`from_api_repr`"""
return resource["jsonPayload"]
def to_api_repr(self):
"""API repr (JSON format) for entry."""
info = super(StructEntry, self).to_api_repr()
info["jsonPayload"] = self.payload
return info
class ProtobufEntry(LogEntry):
__doc__ = (
"""
Log entry with protobuf message payload.
"""
+ _LOG_ENTRY_PARAM_DOCSTRING
+ """
payload (google.protobuf.Message): payload for the log entry.
"""
+ _LOG_ENTRY_SEE_ALSO_DOCSTRING
)
@classmethod
def _extract_payload(cls, resource):
"""Helper for :meth:`from_api_repr`"""
return resource["protoPayload"]
@property
def payload_pb(self):
if isinstance(self.payload, Any):
return self.payload
@property
def payload_json(self):
if isinstance(self.payload, collections.abc.Mapping):
return self.payload
def to_api_repr(self):
"""API repr (JSON format) for entry."""
info = super(ProtobufEntry, self).to_api_repr()
proto_payload = None
if self.payload_json:
proto_payload = dict(self.payload_json)
elif self.payload_pb:
proto_payload = MessageToDict(self.payload_pb)
info["protoPayload"] = proto_payload
return info
def parse_message(self, message):
"""Parse payload into a protobuf message.
Mutates the passed-in ``message`` in place.
Args:
message (google.protobuf.Message): the message to be logged
"""
# NOTE: This assumes that ``payload`` is already a deserialized
# ``Any`` field and ``message`` has come from an imported
# ``pb2`` module with the relevant protobuf message type.
Parse(json.dumps(self.payload), message)