comparison py/utils.py @ 265:78c542f03030

Limit log
author Matt Johnston <matt@ucc.asn.au>
date Sat, 13 Jun 2015 22:49:14 +0800
parents 26eee8591f61
children 9d0313b685ae
comparison
equal deleted inserted replaced
264:205809a8872f 265:78c542f03030
1 import os 1 import os
2 import sys 2 import sys
3 #import ctypes 3 import ctypes
4 import time 4 import time
5 import select 5 import select
6 import logging 6 import logging
7 import binascii 7 import binascii
8 import json 8 import json
9 import datetime
9 10
10 D = logging.debug 11 D = logging.debug
11 L = logging.info 12 L = logging.info
12 W = logging.warning 13 W = logging.warning
13 E = logging.error 14 E = logging.error
136 return -1 137 return -1
137 138
138 139
139 def json_load_round_float(s, **args): 140 def json_load_round_float(s, **args):
140 return json.loads(s,parse_float = lambda f: round(float(f), 2), **args) 141 return json.loads(s,parse_float = lambda f: round(float(f), 2), **args)
142
143 class NotTooOften(object):
144 """ prevents things happening more than once per limit.
145 Isn't monotonic, good enough for logging. eg
146 self.logfailure = NotTooOften(180) # 3 minutes
147 ...
148 if self.logfailure():
149 L("blah")
150 """
151 def __init__(self, limit):
152 """ limit is a delay in seconds or TimeDelta """
153 if type(limit) is datetime.timedelta:
154 self.limit = limit
155 else:
156 self.limit = datetime.timedelta(seconds=limit)
157
158 # must be positive
159 assert self.limit > datetime.timedelta(0)
160 self.last = datetime.datetime(10, 1, 1)
161
162 def __call__(self):
163 if datetime.datetime.now() - self.last > self.limit:
164 self.last = datetime.datetime.now()
165 return True
166
167 def log(self, msg):
168 """ calls L(msg) if it isn't too often, otherwise D(msg)
169 """
170 if self():
171 L(msg + " (log interval %s)" % str(self.limit))
172 else:
173 D(msg)