|
13 | 13 | # We also remove periods, so labels can be distinguished.
|
14 | 14 | _INVALID_GRAPHITE_CHARS = re.compile(r"[^a-zA-Z0-9_-]")
|
15 | 15 |
|
| 16 | +LOG = logging.getLogger('graphite-bridge') |
16 | 17 |
|
17 | 18 | def _sanitize(s):
|
18 | 19 | return _INVALID_GRAPHITE_CHARS.sub('_', s)
|
@@ -40,39 +41,46 @@ def run(self):
|
40 | 41 | try:
|
41 | 42 | self._pusher.push(prefix=self._prefix)
|
42 | 43 | except IOError:
|
43 |
| - logging.exception("Push failed") |
| 44 | + LOG.error("Push failed") |
44 | 45 |
|
45 | 46 |
|
46 | 47 | class GraphiteBridge(object):
|
47 |
| - def __init__(self, address, registry=core.REGISTRY, timeout_seconds=30, _time=time): |
| 48 | + def __init__(self, address, registry=core.REGISTRY, timeout_seconds=30, _time=time, label_templates={}): |
48 | 49 | self._address = address
|
49 | 50 | self._registry = registry
|
50 | 51 | self._timeout = timeout_seconds
|
51 | 52 | self._time = _time
|
| 53 | + self._label_templates = label_templates |
52 | 54 |
|
53 | 55 | def push(self, prefix=''):
|
54 | 56 | now = int(self._time.time())
|
55 | 57 | output = []
|
56 | 58 |
|
57 |
| - prefixstr = '' |
58 |
| - if prefix: |
59 |
| - prefixstr = prefix + '.' |
| 59 | + prefixstr = prefix or '' |
60 | 60 |
|
61 | 61 | for metric in self._registry.collect():
|
62 | 62 | for name, labels, value in metric.samples:
|
63 |
| - if labels: |
64 |
| - labelstr = '.' + '.'.join( |
65 |
| - ['{0}.{1}'.format( |
66 |
| - _sanitize(k), _sanitize(v)) |
67 |
| - for k, v in sorted(labels.items())]) |
| 63 | + label_dict = dict( |
| 64 | + (_sanitize(k), _sanitize(v)) |
| 65 | + for k, v in sorted(labels.items())) |
| 66 | + label_dict['name'] = name |
| 67 | + if name in self._label_templates: |
| 68 | + labelstr = self._label_templates[name].format( **label_dict) |
68 | 69 | else:
|
69 |
| - labelstr = '' |
70 |
| - output.append('{0}{1}{2} {3} {4}\n'.format( |
71 |
| - prefixstr, _sanitize(name), labelstr, float(value), now)) |
| 70 | + labelstr = '.'.join([_sanitize(name)] + |
| 71 | + ['{0}.{1}'.format( |
| 72 | + _sanitize(k), _sanitize(v)) |
| 73 | + for k, v in sorted(labels.items())]) |
| 74 | + output.append('{0}.{1} {2} {3}\n'.format( |
| 75 | + prefixstr, labelstr, float(value), now)) |
72 | 76 |
|
73 |
| - conn = socket.create_connection(self._address, self._timeout) |
74 |
| - conn.sendall(''.join(output).encode('ascii')) |
75 |
| - conn.close() |
| 77 | + |
| 78 | + try: |
| 79 | + conn = socket.create_connection(self._address, self._timeout) |
| 80 | + conn.sendall(''.join(output).encode('ascii')) |
| 81 | + conn.close() |
| 82 | + except Exception as e: |
| 83 | + LOG.error('Could not connect to graphite at %s', self._address) |
76 | 84 |
|
77 | 85 | def start(self, interval=60.0, prefix=''):
|
78 | 86 | t = _RegularPush(self, interval, prefix)
|
|
0 commit comments