remove fallback logger and clean up sharedLogging

This commit is contained in:
petrucci4prez 2017-05-29 21:48:01 -04:00
parent fb4f04fb76
commit 6475ce178c
2 changed files with 39 additions and 49 deletions

19
main.py
View File

@ -1,15 +1,14 @@
#! /bin/python #! /bin/python
import os, time, signal, traceback import os, time, signal, traceback, logging
import RPi.GPIO as GPIO import RPi.GPIO as GPIO
from auxilary import fallbackLogger from sharedLogging import unmountGluster
from sharedLogging import MasterLogger
logger = MasterLogger(__name__, 'DEBUG') logger = logging.getLogger(__name__)
def printTrace(t): def printTrace(t):
fallbackLogger(__name__, 'CRITICAL', '\n' + t) logger.critical('\n' + t)
def clean(): def clean():
GPIO.cleanup() GPIO.cleanup()
@ -21,11 +20,9 @@ def clean():
try: try:
logger.info('Terminated root process - PID: %s', os.getpid()) logger.info('Terminated root process - PID: %s', os.getpid())
logger.unmountGluster() unmountGluster()
except NameError:
pass
except Exception: except Exception:
printTrace(traceback.format_exc()) logger.critical(traceback.format_exc())
def sigtermHandler(signum, stackFrame): def sigtermHandler(signum, stackFrame):
logger.info('Caught SIGTERM') logger.info('Caught SIGTERM')
@ -38,8 +35,6 @@ if __name__ == '__main__':
GPIO.setwarnings(False) GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM) GPIO.setmode(GPIO.BCM)
logger.mountGluster()
from notifier import criticalError from notifier import criticalError
from stateMachine import StateMachine from stateMachine import StateMachine
@ -63,7 +58,7 @@ if __name__ == '__main__':
try: try:
logger.critical(t) logger.critical(t)
except NameError: except NameError:
printTrace(t) logger.critical(t)
finally: finally:
clean() clean()

View File

@ -1,8 +1,21 @@
import logging, os, logging.handlers import logging, os
from subprocess import run, PIPE, CalledProcessError from subprocess import run, PIPE, CalledProcessError
from logging.handlers import TimedRotatingFileHandler from logging.handlers import TimedRotatingFileHandler
from auxilary import fallbackLogger # formats console output depending on whether we have gluster
def _formatConsole(rotatingFile=False):
c = '' if rotatingFile else '[CONSOLE ONLY] '
fmt = logging.Formatter('[%(name)s] [%(levelname)s] ' + c + '%(message)s')
console.setFormatter(fmt)
console = logging.StreamHandler()
_formatConsole(False)
rootLogger = logging.getLogger()
rootLogger.setLevel(logging.DEBUG)
rootLogger.addHandler(console)
logger = logging.getLogger(__name__)
class GlusterFSHandler(TimedRotatingFileHandler): class GlusterFSHandler(TimedRotatingFileHandler):
def __init__(self, server, volume, mountpoint, options=None): def __init__(self, server, volume, mountpoint, options=None):
@ -19,8 +32,8 @@ class GlusterFSHandler(TimedRotatingFileHandler):
if not os.path.exists(logdest): if not os.path.exists(logdest):
os.mkdir(logdest) os.mkdir(logdest)
elif os.path.isfile(logdest): elif os.path.isfile(logdest):
fallbackLogger(__name__, 'CRITICAL', '{} is present but is a file (vs a directory). ' \ logger.critical('%s is present but is a file (vs a directory). ' \
'Please (re)move this file to prevent data loss'.format(logdest)) 'Please (re)move this file to prevent data loss', logdest)
raise SystemExit raise SystemExit
self._mount() self._mount()
@ -33,7 +46,7 @@ class GlusterFSHandler(TimedRotatingFileHandler):
def _mount(self): def _mount(self):
if os.path.ismount(self._mountpoint): if os.path.ismount(self._mountpoint):
# NOTE: this assumes that the already-mounted device is the one intended # NOTE: this assumes that the already-mounted device is the one intended
fallbackLogger(__name__, 'WARNING', 'Device already mounted at {}'.format(self._mountpoint)) logger.warning('Device already mounted at {}'.format(self._mountpoint))
else: else:
dst = self._server + ':/' + self._volume dst = self._server + ':/' + self._volume
cmd = ['mount', '-t', 'glusterfs', dst, self._mountpoint] cmd = ['mount', '-t', 'glusterfs', dst, self._mountpoint]
@ -51,42 +64,24 @@ class GlusterFSHandler(TimedRotatingFileHandler):
# we assume that this will only get thrown when the logger is not # we assume that this will only get thrown when the logger is not
# active, so use fallback to get the explicit mount errors # active, so use fallback to get the explicit mount errors
stderr = e.stderr.decode('ascii').rstrip() stderr = e.stderr.decode('ascii').rstrip()
fallbackLogger(__name__, 'CRITICAL', stderr) logger.critical(stderr)
raise SystemExit raise SystemExit
def close(self): def close(self):
TimedRotatingFileHandler.close(self) # must close file stream before unmounting TimedRotatingFileHandler.close(self) # must close file stream before unmounting
self._unmount() self._unmount()
class MasterLogger(): gluster = GlusterFSHandler(
def __init__(self, name, level): server = '192.168.11.39',
self._console = logging.StreamHandler() volume = 'pyledriver',
self._formatConsole(False) mountpoint = '/mnt/glusterfs/pyledriver',
options = 'backupvolfile-server=192.168.11.48'
)
self._rootLogger = logging.getLogger() _formatConsole(True)
self._rootLogger.addHandler(self._console) rootLogger.addHandler(gluster)
self._rootLogger.setLevel(getattr(logging, level))
# since the logger module sucks and doesn't allow me to init def unmountGluster():
# a logger in a subclass, need to "fake" object inheritance rootLogger.removeHandler(gluster)
for i in ['debug', 'info', 'warning', 'error', 'critical']: _formatConsole(False)
setattr(self, i, getattr(logging.getLogger(name), i))
def mountGluster(self):
self._gluster = GlusterFSHandler(
server = '192.168.11.39',
volume = 'pyledriver',
mountpoint = '/mnt/glusterfs/pyledriver',
options = 'backupvolfile-server=192.168.11.48'
)
self._formatConsole(True)
self._rootLogger.addHandler(self._gluster)
def unmountGluster(self):
self._rootLogger.removeHandler(self._gluster)
self._formatConsole(False)
def _formatConsole(self, rotatingFile=False):
c = '' if rotatingFile else '[CONSOLE ONLY] '
fmt = logging.Formatter('[%(name)s] [%(levelname)s] ' + c + '%(message)s')
self._console.setFormatter(fmt)