1 import logging, logging.handlers, os, time, queue, threading, subprocess
6 import __main__ as main
7 self.name = os.path.basename(main.__file__)
8 self.logger = logging.getLogger(self.name)
9 self.logger.setLevel(logging.INFO)
10 self.handler = logging.handlers.SysLogHandler(address = '/dev/log', facility = logging.handlers.SysLogHandler.LOG_LOCAL0)
11 self.logger.addHandler(self.handler)
13 def log (self, lvl, what):
14 thestr = "%s[%d]: %s" % (self.name,os.getpid(),what)
16 self.logger.log(lvl, thestr)
18 def debug(self, what):
19 self.log(logging.DEBUG, what)
21 self.log(logging.INFO, what)
22 def warning(self, what):
23 self.log(logging.WARNING, what)
24 def error(self, what):
25 self.log(logging.ERROR, what)
26 def critical(self, what):
27 self.log(logging.CRITICAL, what)
31 # run a command asynchronously and log the return value if not 0
32 # prefix must be a string identifying the code position where the call came from
33 def fire_and_forget (cmd, log, prefix):
34 def _fire_and_forget ():
35 with open("/dev/null", "w") as fnull:
36 retcode = subprocess.call(cmd, stdout=fnull, stderr=fnull)
38 log("%sReturn code %d at command: %s" % (prefix,retcode,str(cmd)))
39 t = threading.Thread(target=_fire_and_forget)
42 # Threaded callback class
43 class ThreadFunction():
47 def __init__(self, f):
49 self._q = queue.Queue()
50 self._t = threading.Thread(target=self._thread_func)
53 def _thread_func(self):
55 (cmd, data) = self._q.get()
61 logger.error("ThreadFunction: Got exception out of handler thread: %s" % str(e))
66 logger.error("ThreadFunction: Command %d does not exist" % cmd)
68 def __call__(self, *arg):
69 self._q.put((self._CALL, arg))
72 self._q.put((_TERM, None))
75 # Thread timer-repeater class: Call a function every <sleep_time> seconds
76 class ThreadRepeater():
77 def __init__(self, f, sleep_time):
80 self._sleep_time = sleep_time
81 self._t = threading.Thread(target=self._thread_func)
89 time.sleep(sleep_time)