Page MenuHomec4science

bdlogging.py
No OneTemporary

File Metadata

Created
Fri, Nov 15, 13:05

bdlogging.py

#!/usr/bin/env python
from __future__ import print_function
__all__ = [ "BDLogging" ]
import logging,traceback,os
################################################################
def invalidPrint(x):
raise Exception('print should not be used in that class: use the logging system instead: "{0}"'.format(x))
################################################################
file_handler = None
def setFileHandler(logger,streamformatter):
if globals()['file_handler'] == None:
# print ("resetting the file for {0}".format(logger.name))
f = open('bd.log','w')
f.close()
globals()['file_handler'] = logging.FileHandler('bd.log')
file_handler = globals()['file_handler']
file_handler.setFormatter(streamformatter)
if not file_handler in logger.handlers:
logger.addHandler(file_handler)
################################################################
Parent = logging.getLoggerClass()
class BDlogger(Parent):
def __init__(self,name):
self.name = name
self.logger_screen = Parent(name + 'screen')
self.logger_file = Parent(name + 'file')
self.streamformatter = logging.Formatter(fmt='%(levelname)s:%(foo)50s:%(f)15s:%(l)s:' + ' '*10 + '%(message)s')
self.screen_handler = logging.StreamHandler()
self.screen_handler.setFormatter(self.streamformatter)
self.logger_screen.addHandler(self.screen_handler)
self.enable_file = False
self.setScreenLevel(logging.INFO)
def setLogFileLevel(self,level):
self.logger_file.setLevel(level)
def setScreenLevel(self,level):
self.logger_screen.setLevel(level)
def activateFileLog(self,level = logging.DEBUG):
setFileHandler(self.logger_file,self.streamformatter)
self.enable_file = True
self.setLogFileLevel(level)
def getExtra(self):
extra = {}
tr = traceback.extract_stack(limit=3)
tr = tr[0]
fname = os.path.basename(tr[0])
extra['foo'] = tr[2]
extra['f'] = fname
extra['l'] = tr[1]
return extra
def debug(self,x):
self.logger_screen.debug(x,extra=self.getExtra())
if self.enable_file is True:
self.logger_file.debug(x,extra=self.getExtra())
def warning(self,x):
self.logger_screen.warning(x,extra=self.getExtra())
if self.enable_file is True:
self.logger_file.warning(x,extra=self.getExtra())
def info(self,x):
self.logger_screen.info(x,extra=self.getExtra())
if self.enable_file is True:
self.logger_file.info(x,extra=self.getExtra())
def error(self,x):
self.logger_screen.error(x,extra=self.getExtra())
if self.enable_file is True:
self.logger_file.error(x,extra=self.getExtra())
################################################################
logging.setLoggerClass(BDlogger)
################################################################
import logging
logger = logging.getLogger(__name__)
################################################################
def activateFileLogging():
for name,log in logging.Logger.manager.loggerDict.iteritems():
if isinstance(log,BDlogger): log.activateFileLog()

Event Timeline