import logging from collections import defaultdict import time class S

 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
import logging
from collections import defaultdict
import time
class Stat(object):
def __init__(self, log_file='var/stat.log'):
self.time = time.time()
self.count_prev = 0
self.count = 0
self.extra_counters = defaultdict(int)
self.logger = logging.getLogger('stat')
self.logger.addHandler(logging.FileHandler(log_file, 'w'))
self.logger.setLevel(logging.DEBUG)
def tick(self):
self.count += 1
now = time.time()
if now - self.time > 5:
count = self.count - self.count_prev
qps = count / (now - self.time)
extra = []
for key in sorted(self.extra_counters.keys()):
extra.append('%s:%d' % (key, self.extra_counters[key]))
self.logger.debug('qps: %.2f [%s]' % (qps, '/'.join(extra)))
self.count_prev = self.count
self.time = now
def inc_counter(self, key):
self.extra_counters[key] += 1