|
| 1 | +import time |
| 2 | +import re |
| 3 | + |
| 4 | +from logster_helper import MetricObject, LogsterParser |
| 5 | +from logster_helper import LogsterParsingException |
| 6 | + |
| 7 | +# For help with what this is all about, see one of the sample |
| 8 | +# Logster parsers which have more detailed comments about |
| 9 | +# the structure of the class and each method's function. |
| 10 | + |
| 11 | +# Collect arbitrary metric lines and spit out aggregated |
| 12 | +# metric values (MetricObjects) based on the metric names |
| 13 | +# found in the lines. Any conforming metric, one parser. Sweet. |
| 14 | + |
| 15 | +class MetricLogster(LogsterParser): |
| 16 | + |
| 17 | + def __init__(self, option_string=None): |
| 18 | + self.metrics = {} |
| 19 | + # Examples: |
| 20 | + # |
| 21 | + # Mar 30 20:35:03 mail1 whatever[1323]: metric=mail1.my.metric value=9 |
| 22 | + # Mar 31 03:44:28 fs9 blah[9403]: metric=foo.bar value=4484884 |
| 23 | + # |
| 24 | + self.reg = re.compile('.+ metric=(?P<metricname>[-_a-zA-Z0-9.]+) value=(?P<value>[0-9.]+))') |
| 25 | + |
| 26 | + def parse_line(self, line): |
| 27 | + try: |
| 28 | + regMatch = self.reg.match(line) |
| 29 | + |
| 30 | + if regMatch: |
| 31 | + linebits = regMatch.groupdict() |
| 32 | + metric = str(linebits['metricname']) |
| 33 | + value = int(linebits['value']) |
| 34 | + if self.metrics.has_key(metric): |
| 35 | + self.metrics[metric] = self.metrics[metric] + int(value) |
| 36 | + else: |
| 37 | + self.metrics[metric] = int(value) |
| 38 | + else: |
| 39 | + raise LogsterParsingException, "regmatch failed to match" |
| 40 | + |
| 41 | + except Exception, e: |
| 42 | + raise LogsterParsingException, "regmatch or contents failed with %s" % e |
| 43 | + |
| 44 | + |
| 45 | + def get_state(self, duration): |
| 46 | + self.duration = duration |
| 47 | + |
| 48 | + outlines = [] |
| 49 | + |
| 50 | + for k in self.metrics.keys(): |
| 51 | + outlines.append(MetricObject(k, (self.metrics[k] / self.duration), "per sec")) |
| 52 | + |
| 53 | + return outlines |
0 commit comments