Skip to content

Commit 209babe

Browse files
authored
Merge pull request googleapis#2600 from dhermes/gax-logging-use-messagetodict
Use MessageToDict in logging._gax
2 parents 6b11fe5 + 19fd83d commit 209babe

File tree

2 files changed

+146
-407
lines changed

2 files changed

+146
-407
lines changed

logging/google/cloud/logging/_gax.py

+13-225
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,14 @@
1818
from google.gax import INITIAL_PAGE
1919
from google.gax.errors import GaxError
2020
from google.gax.grpc import exc_to_code
21-
from google.logging.type.log_severity_pb2 import LogSeverity
2221
from google.logging.v2.logging_config_pb2 import LogSink
2322
from google.logging.v2.logging_metrics_pb2 import LogMetric
2423
from google.logging.v2.log_entry_pb2 import LogEntry
24+
from google.protobuf.json_format import MessageToDict
2525
from google.protobuf.json_format import ParseDict
2626
from grpc import StatusCode
2727

28-
from google.cloud._helpers import _datetime_to_pb_timestamp
29-
from google.cloud._helpers import _pb_timestamp_to_rfc3339
28+
from google.cloud._helpers import _datetime_to_rfc3339
3029
from google.cloud.exceptions import Conflict
3130
from google.cloud.exceptions import NotFound
3231

@@ -77,7 +76,7 @@ def list_entries(self, projects, filter_='', order_by='',
7776
page_iter = self._gax_api.list_log_entries(
7877
projects, filter_=filter_, order_by=order_by,
7978
page_size=page_size, options=options)
80-
entries = [_log_entry_pb_to_mapping(entry_pb)
79+
entries = [MessageToDict(entry_pb)
8180
for entry_pb in page_iter.next()]
8281
token = page_iter.page_token or None
8382
return entries, token
@@ -163,7 +162,7 @@ def list_sinks(self, project, page_size=0, page_token=None):
163162
path = 'projects/%s' % (project,)
164163
page_iter = self._gax_api.list_sinks(path, page_size=page_size,
165164
options=options)
166-
sinks = [_log_sink_pb_to_mapping(log_sink_pb)
165+
sinks = [MessageToDict(log_sink_pb)
167166
for log_sink_pb in page_iter.next()]
168167
token = page_iter.page_token or None
169168
return sinks, token
@@ -221,7 +220,7 @@ def sink_get(self, project, sink_name):
221220
if exc_to_code(exc.cause) == StatusCode.NOT_FOUND:
222221
raise NotFound(path)
223222
raise
224-
return _log_sink_pb_to_mapping(sink_pb)
223+
return MessageToDict(sink_pb)
225224

226225
def sink_update(self, project, sink_name, filter_, destination):
227226
"""API call: update a sink resource.
@@ -253,7 +252,7 @@ def sink_update(self, project, sink_name, filter_, destination):
253252
if exc_to_code(exc.cause) == StatusCode.NOT_FOUND:
254253
raise NotFound(path)
255254
raise
256-
return _log_sink_pb_to_mapping(sink_pb)
255+
return MessageToDict(sink_pb)
257256

258257
def sink_delete(self, project, sink_name):
259258
"""API call: delete a sink resource.
@@ -310,7 +309,7 @@ def list_metrics(self, project, page_size=0, page_token=None):
310309
path = 'projects/%s' % (project,)
311310
page_iter = self._gax_api.list_log_metrics(
312311
path, page_size=page_size, options=options)
313-
metrics = [_log_metric_pb_to_mapping(log_metric_pb)
312+
metrics = [MessageToDict(log_metric_pb)
314313
for log_metric_pb in page_iter.next()]
315314
token = page_iter.page_token or None
316315
return metrics, token
@@ -367,7 +366,7 @@ def metric_get(self, project, metric_name):
367366
if exc_to_code(exc.cause) == StatusCode.NOT_FOUND:
368367
raise NotFound(path)
369368
raise
370-
return _log_metric_pb_to_mapping(metric_pb)
369+
return MessageToDict(metric_pb)
371370

372371
def metric_update(self, project, metric_name, filter_, description):
373372
"""API call: update a metric resource.
@@ -399,7 +398,7 @@ def metric_update(self, project, metric_name, filter_, description):
399398
if exc_to_code(exc.cause) == StatusCode.NOT_FOUND:
400399
raise NotFound(path)
401400
raise
402-
return _log_metric_pb_to_mapping(metric_pb)
401+
return MessageToDict(metric_pb)
403402

404403
def metric_delete(self, project, metric_name):
405404
"""API call: delete a metric resource.
@@ -420,225 +419,14 @@ def metric_delete(self, project, metric_name):
420419
raise
421420

422421

423-
def _mon_resource_pb_to_mapping(resource_pb):
424-
"""Helper for :func:_log_entry_pb_to_mapping`.
425-
426-
Performs "impedance matching" between the protobuf attrs and the keys
427-
expected in the JSON API.
428-
"""
429-
mapping = {
430-
'type': resource_pb.type,
431-
}
432-
if resource_pb.labels:
433-
mapping['labels'] = resource_pb.labels
434-
return mapping
435-
436-
437-
def _value_pb_to_value(value_pb):
438-
"""Helper for :func:`_log_entry_pb_to_mapping`.
439-
440-
Performs "impedance matching" between the protobuf attrs and the keys
441-
expected in the JSON API.
442-
"""
443-
kind = value_pb.WhichOneof('kind')
444-
445-
if kind is None:
446-
result = None
447-
448-
elif kind == 'string_value':
449-
result = value_pb.string_value
450-
451-
elif kind == 'bool_value':
452-
result = value_pb.bool_value
453-
454-
elif kind == 'number_value':
455-
result = value_pb.number_value
456-
457-
elif kind == 'list_value':
458-
result = [_value_pb_to_value(element)
459-
for element in value_pb.list_value.values]
460-
461-
elif kind == 'struct_value':
462-
result = _struct_pb_to_mapping(value_pb.struct_value)
463-
464-
else:
465-
raise ValueError('Value protobuf had unknown kind: %s' % (kind,))
466-
467-
return result
468-
469-
470-
def _struct_pb_to_mapping(struct_pb):
471-
"""Helper for :func:`_log_entry_pb_to_mapping`.
472-
473-
Performs "impedance matching" between the protobuf attrs and the keys
474-
expected in the JSON API.
475-
"""
476-
return {key: _value_pb_to_value(struct_pb.fields[key])
477-
for key in struct_pb.fields}
478-
479-
480-
def _log_entry_pb_to_mapping(entry_pb):
481-
"""Helper for :meth:`list_entries`, et aliae
482-
483-
Performs "impedance matching" between the protobuf attrs and the keys
484-
expected in the JSON API.
485-
"""
486-
mapping = {
487-
'logName': entry_pb.log_name,
488-
'resource': _mon_resource_pb_to_mapping(entry_pb.resource),
489-
'severity': LogSeverity.Name(entry_pb.severity),
490-
'insertId': entry_pb.insert_id,
491-
'timestamp': _pb_timestamp_to_rfc3339(entry_pb.timestamp),
492-
'labels': entry_pb.labels,
493-
}
494-
if entry_pb.HasField('text_payload'):
495-
mapping['textPayload'] = entry_pb.text_payload
496-
497-
if entry_pb.HasField('json_payload'):
498-
mapping['jsonPayload'] = _struct_pb_to_mapping(entry_pb.json_payload)
499-
500-
if entry_pb.HasField('proto_payload'):
501-
mapping['protoPayload'] = entry_pb.proto_payload
502-
503-
if entry_pb.http_request:
504-
request = entry_pb.http_request
505-
mapping['httpRequest'] = {
506-
'requestMethod': request.request_method,
507-
'requestUrl': request.request_url,
508-
'status': request.status,
509-
'referer': request.referer,
510-
'userAgent': request.user_agent,
511-
'cacheHit': request.cache_hit,
512-
'requestSize': request.request_size,
513-
'responseSize': request.response_size,
514-
'remoteIp': request.remote_ip,
515-
}
516-
517-
if entry_pb.operation:
518-
operation = entry_pb.operation
519-
mapping['operation'] = {
520-
'producer': operation.producer,
521-
'id': operation.id,
522-
'first': operation.first,
523-
'last': operation.last,
524-
}
525-
526-
return mapping
527-
528-
529-
def _http_request_mapping_to_pb(info, request):
530-
"""Helper for _log_entry_mapping_to_pb
531-
532-
Performs "impedance matching" between the protobuf attrs and the keys
533-
expected in the JSON API.
534-
"""
535-
optional_request_keys = {
536-
'requestMethod': 'request_method',
537-
'requestUrl': 'request_url',
538-
'status': 'status',
539-
'referer': 'referer',
540-
'userAgent': 'user_agent',
541-
'cacheHit': 'cache_hit',
542-
'requestSize': 'request_size',
543-
'responseSize': 'response_size',
544-
'remoteIp': 'remote_ip',
545-
}
546-
for key, pb_name in optional_request_keys.items():
547-
if key in info:
548-
setattr(request, pb_name, info[key])
549-
550-
551-
def _log_operation_mapping_to_pb(info, operation):
552-
"""Helper for _log_entry_mapping_to_pb
553-
554-
Performs "impedance matching" between the protobuf attrs and the keys
555-
expected in the JSON API.
556-
"""
557-
operation.producer = info['producer']
558-
operation.id = info['id']
559-
560-
if 'first' in info:
561-
operation.first = info['first']
562-
563-
if 'last' in info:
564-
operation.last = info['last']
565-
566-
567422
def _log_entry_mapping_to_pb(mapping):
568423
"""Helper for :meth:`write_entries`, et aliae
569424
570-
Performs "impedance matching" between the protobuf attrs and the keys
571-
expected in the JSON API.
425+
Performs "impedance matching" between the protobuf attrs and
426+
the keys expected in the JSON API.
572427
"""
573-
# pylint: disable=too-many-branches
574428
entry_pb = LogEntry()
575-
576-
optional_scalar_keys = {
577-
'logName': 'log_name',
578-
'insertId': 'insert_id',
579-
'textPayload': 'text_payload',
580-
}
581-
582-
for key, pb_name in optional_scalar_keys.items():
583-
if key in mapping:
584-
setattr(entry_pb, pb_name, mapping[key])
585-
586-
if 'resource' in mapping:
587-
entry_pb.resource.type = mapping['resource']['type']
588-
589-
if 'severity' in mapping:
590-
severity = mapping['severity']
591-
if isinstance(severity, str):
592-
severity = LogSeverity.Value(severity)
593-
entry_pb.severity = severity
594-
595429
if 'timestamp' in mapping:
596-
timestamp = _datetime_to_pb_timestamp(mapping['timestamp'])
597-
entry_pb.timestamp.CopyFrom(timestamp)
598-
599-
if 'labels' in mapping:
600-
for key, value in mapping['labels'].items():
601-
entry_pb.labels[key] = value
602-
603-
if 'jsonPayload' in mapping:
604-
ParseDict(mapping['jsonPayload'], entry_pb.json_payload)
605-
606-
if 'protoPayload' in mapping:
607-
ParseDict(mapping['protoPayload'], entry_pb.proto_payload)
608-
609-
if 'httpRequest' in mapping:
610-
_http_request_mapping_to_pb(
611-
mapping['httpRequest'], entry_pb.http_request)
612-
613-
if 'operation' in mapping:
614-
_log_operation_mapping_to_pb(
615-
mapping['operation'], entry_pb.operation)
616-
430+
mapping['timestamp'] = _datetime_to_rfc3339(mapping['timestamp'])
431+
ParseDict(mapping, entry_pb)
617432
return entry_pb
618-
# pylint: enable=too-many-branches
619-
620-
621-
def _log_sink_pb_to_mapping(sink_pb):
622-
"""Helper for :meth:`list_sinks`, et aliae
623-
624-
Performs "impedance matching" between the protobuf attrs and the keys
625-
expected in the JSON API.
626-
"""
627-
return {
628-
'name': sink_pb.name,
629-
'destination': sink_pb.destination,
630-
'filter': sink_pb.filter,
631-
}
632-
633-
634-
def _log_metric_pb_to_mapping(metric_pb):
635-
"""Helper for :meth:`list_metrics`, et aliae
636-
637-
Performs "impedance matching" between the protobuf attrs and the keys
638-
expected in the JSON API.
639-
"""
640-
return {
641-
'name': metric_pb.name,
642-
'description': metric_pb.description,
643-
'filter': metric_pb.filter,
644-
}

0 commit comments

Comments
 (0)