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 functools 

3 

4__all__ = ['Logged'] 

5 

6 

7class Logged(object): 

8 '''Class which automatically adds a named logger to your class when 

9 interiting 

10 

11 Adds easy access to debug, info, warning, error, exception and log methods 

12 

13 >>> class MyClass(Logged): 

14 ... def __init__(self): 

15 ... Logged.__init__(self) 

16 >>> my_class = MyClass() 

17 >>> my_class.debug('debug') 

18 >>> my_class.info('info') 

19 >>> my_class.warning('warning') 

20 >>> my_class.error('error') 

21 >>> my_class.exception('exception') 

22 >>> my_class.log(0, 'log') 

23 ''' 

24 def __new__(cls, *args, **kwargs): 

25 cls.logger = logging.getLogger( 

26 cls.__get_name(__name__, cls.__class__.__name__)) 

27 return super(Logged, cls).__new__(cls) 

28 

29 @classmethod 

30 def __get_name(cls, *name_parts): 

31 return '.'.join(n.strip() for n in name_parts if n.strip()) 

32 

33 @classmethod 

34 @functools.wraps(logging.debug) 

35 def debug(cls, msg, *args, **kwargs): 

36 cls.logger.debug(msg, *args, **kwargs) 

37 

38 @classmethod 

39 @functools.wraps(logging.info) 

40 def info(cls, msg, *args, **kwargs): 

41 cls.logger.info(msg, *args, **kwargs) 

42 

43 @classmethod 

44 @functools.wraps(logging.warning) 

45 def warning(cls, msg, *args, **kwargs): 

46 cls.logger.warning(msg, *args, **kwargs) 

47 

48 @classmethod 

49 @functools.wraps(logging.error) 

50 def error(cls, msg, *args, **kwargs): 

51 cls.logger.error(msg, *args, **kwargs) 

52 

53 @classmethod 

54 @functools.wraps(logging.exception) 

55 def exception(cls, msg, *args, **kwargs): 

56 cls.logger.exception(msg, *args, **kwargs) 

57 

58 @classmethod 

59 @functools.wraps(logging.log) 

60 def log(cls, lvl, msg, *args, **kwargs): 

61 cls.logger.log(lvl, msg, *args, **kwargs) 

62