Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1import logging 

2import logging.config 

3import yaml 

4import sys 

5import re 

6import traceback 

7 

8exclude = re.compile(r"(self|_.*)", re.DOTALL) 

9include = re.compile(r"(.*)", re.DOTALL) 

10#exclude = re.compile(r"(_.*)", re.DOTALL) 

11 

12def logger(name, config='logging.yaml'): 

13 """Get a logger from logger system. 

14 The config file and handlers are loaded just once 

15 avoiding to truncate log files when loggers are 

16 required and returned. 

17 """ 

18 log = logging.getLogger(name) 

19 if not log.handlers: # it seems like logging is not configured already 

20 conf = yaml.load(open(config), Loader=yaml.FullLoader) 

21 logging.config.dictConfig(conf) 

22 log = logging.getLogger(name) 

23 if not log.handlers: 

24 print(f"Logger: {name} is not defined in {config}") 

25 return log 

26 

27 

28def trace(message='', context=None, name=None, log=None, exclude=exclude, include=include, level=logging.INFO, frames=1): 

29 parent = sys._getframe(frames) 

30 name = name or parent.f_code.co_name 

31 

32 if context == None: 

33 context = parent.f_locals 

34 

35 self = context.get('self') 

36 

37 if not isinstance(exclude, re.Pattern): 

38 exclude = re.compile(exclude, re.DOTALL) 

39 if not isinstance(include, re.Pattern): 

40 include = re.compile(include, re.DOTALL) 

41 

42 ctx = dict([(k, v) for k, v in context.items() if include.match(k) and not exclude.match(k)]) \ 

43 or '' 

44 

45 if not log: 

46 mod = parent.f_globals 

47 log = mod.get('log') or logger(mod['__name__']) 

48 

49 if self: 

50 log.log(level, f"{self}.{name}(): {message} : {ctx}") 

51 else: 

52 log.log(level, f"{name}(): {message} : {ctx}") 

53 

54 

55def debug(*args, **kw): 

56 return trace(level=logging.DEBUG, frames=2, *args, **kw) 

57 

58def error(*args, **kw): 

59 return trace(level=logging.ERROR, frames=2, *args, **kw) 

60 

61def warn(*args, **kw): 

62 return trace(level=logging.WARN, frames=2, *args, **kw) 

63 

64def info(*args, **kw): 

65 return trace(level=logging.INFO, frames=2, *args, **kw) 

66 

67def exception(*args, **kw): 

68 #trace(level=logging.ERROR, frames=2, *args, **kw) 

69 exc_type, exc_value, exc_tb = sys.exc_info() 

70 tb = traceback.format_exception(exc_type, exc_value, exc_tb) 

71 tb = ''.join(tb) 

72 trace(message=tb, level=logging.ERROR, frames=2) 

73 

74