python - Logging Formatter record current function executing -
in python logging want record function executing/running. example;
class foo: def bar(self): logging.info("i'm alive") # writes log: '[info]: foo::bar(), i'm alive'
is possible configure logger this? ie, create formatter find out?
logging.config.dictconfig({ 'version': 1, 'disable_existing_loggers': false, 'formatters': { 'standard': { 'format': '[%(levelname)s] %(function_name)s: %(message)s' }, }, ... })
you can adding information context record
of logger. this, need define own contextfilter
class , add instance of logger. notice in order class name, depend on convention of calling self
instance of class, , not using arguments of other functions (it based on question how-to-retrieve-class-information-from-a-frame-object). notice work-around not able determine class of internalfunc
because not have self
argument. see code below.
import inspect import logging def get_class_from_frame(fr): args, _, _, value_dict = inspect.getargvalues(fr) if len(args) , args[0] == 'self': instance = value_dict.get('self', none) if instance: return getattr(instance, '__class__', none) return 'noclass' class contextfilter(logging.filter): """ filter injects contextual information log. """ def filter(self, record): #we adding function field logger record mystack = inspect.stack()[5] record.function = '%s::%s'%(get_class_from_frame(mystack[0]), mystack[3]) return true def buildlogger(): logger = logging.getlogger("root") #now use function field in format myformat = '[%(levelname)s] %(function)s: "%(message)s"' formatter = logging.formatter(myformat) # add instance of contextfilter logger myfilter = contextfilter() logger.addfilter(myfilter) ch = logging.streamhandler() ch.setformatter(formatter) logger.addhandler(ch) logger.propagate = false return logger # testing def mystandalonefunction(): logger.warning('this logged mystandalonefunction') class a(): def afunc(self): def internalfunc(): logger.warning('this logged inside internalfunc call') logger.warning('this logged inside afunc call') internalfunc() logger = buildlogger() logger.warning('this logged module level') mystandalonefunction() = a() a.afunc()
Comments
Post a Comment