daily pastebin goal
76%
SHARE
TWEET

Untitled

a guest May 16th, 2018 106 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # main.py
  2. import logging
  3. import mymodule
  4.  
  5. logger = logging.getLogger(__name__)
  6.  
  7. def setup_logging():
  8.     # only cofnigure logger if script is main module
  9.     # configuring logger in multiple places is bad
  10.     # only top-level module should configure logger
  11.     if not len(logger.handlers):
  12.         logger.setLevel(logging.DEBUG)
  13.         # create console handler with a higher log level
  14.         ch = logging.StreamHandler()
  15.         ch.setLevel(logging.DEBUG)
  16.         formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
  17.         ch.setFormatter(formatter)
  18.         logger.addHandler(ch)
  19.  
  20. if __name__ == '__main__':
  21.     setup_logging()
  22.     logger.info('calling mymodule.myfunc()')
  23.     mymodule.myfunc()
  24.    
  25. # mymodule.py
  26. import logging
  27.  
  28. logger = logging.getLogger(__name__)
  29.  
  30. def myfunc():
  31.     msg = 'myfunc is being called'
  32.     logger.info(msg)
  33.     print('done with myfunc')
  34.  
  35.  
  36. if __name__ == '__main__':
  37.      # only cofnigure logger if script is main module
  38.     # configuring logger in multiple places is bad
  39.     # only top-level module should configure logger
  40.     if not len(logger.handlers):
  41.         logger.setLevel(logging.DEBUG)
  42.         # create console handler with a higher log level
  43.         ch = logging.StreamHandler()
  44.         ch.setLevel(logging.DEBUG)
  45.         formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
  46.         ch.setFormatter(formatter)
  47.         logger.addHandler(ch)
  48.     logger.info('myfunc was executed directly')
  49.     myfunc()
  50.    
  51. $>python main.py
  52. INFO: 2016-07-14 18:13:04 <module>(22) -- calling mymodule.myfunc()
  53. done with myfunc
  54.    
  55. $>python main.py
  56. INFO: 2016-07-14 18:13:04 <module>(22) -- calling mymodule.myfunc()
  57. INFO: 2016-07-14 18:15:09 myfunc(8) -- myfunc is being called
  58. done with myfunc
  59.    
  60. 16 log = logging.getLogger() # use this form to initialize the root logger
  61. 17 #log = logging.getLogger(__name__) # never use this one
  62.    
  63. import logging
  64. logger = logging.getLogger()
  65. logger.debug("You will not see this message if you use line 17 in main")
RAW Paste Data
Top