Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/opencensus/trace/attributes.py: 75%
32 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-06 06:04 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-06 06:04 +0000
1# Copyright 2017, OpenCensus Authors
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.
14import six
16from opencensus.common import utils
19def _format_attribute_value(value):
20 if isinstance(value, bool):
21 value_type = 'bool_value'
22 elif isinstance(value, int):
23 value_type = 'int_value'
24 elif isinstance(value, six.string_types):
25 value_type = 'string_value'
26 value = utils.get_truncatable_str(value)
27 elif isinstance(value, float):
28 value_type = 'double_value'
29 else:
30 return None
32 return {value_type: value}
35class Attributes(object):
36 """A set of attributes, each in the format [KEY]:[VALUE].
38 :type attributes: dict
39 :param attributes: The set of attributes. Each attribute's key can be up
40 to 128 bytes long. The value can be a string up to 256
41 bytes, an integer, a floating-point number, or the
42 Boolean values true and false.
43 """
44 def __init__(self, attributes=None):
45 self.attributes = attributes or {}
47 def set_attribute(self, key, value):
48 """Set a key value pair."""
49 self.attributes[key] = value
51 def delete_attribute(self, key):
52 """Delete an attribute given a key if existed."""
53 self.attributes.pop(key, None)
55 def get_attribute(self, key):
56 """Get a attribute value."""
57 return self.attributes.get(key, None)
59 def format_attributes_json(self):
60 """Convert the Attributes object to json format."""
61 attributes_json = {}
63 for key, value in self.attributes.items():
64 key = utils.check_str_length(key)[0]
65 value = _format_attribute_value(value)
67 if value is not None:
68 attributes_json[key] = value
70 result = {
71 'attributeMap': attributes_json
72 }
74 return result