Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # main.py
- import logging
- import mymodule
- logger = logging.getLogger(__name__)
- def setup_logging():
- # only cofnigure logger if script is main module
- # configuring logger in multiple places is bad
- # only top-level module should configure logger
- if not len(logger.handlers):
- logger.setLevel(logging.DEBUG)
- # create console handler with a higher log level
- ch = logging.StreamHandler()
- ch.setLevel(logging.DEBUG)
- formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
- ch.setFormatter(formatter)
- logger.addHandler(ch)
- if __name__ == '__main__':
- setup_logging()
- logger.info('calling mymodule.myfunc()')
- mymodule.myfunc()
- # mymodule.py
- import logging
- logger = logging.getLogger(__name__)
- def myfunc():
- msg = 'myfunc is being called'
- logger.info(msg)
- print('done with myfunc')
- if __name__ == '__main__':
- # only cofnigure logger if script is main module
- # configuring logger in multiple places is bad
- # only top-level module should configure logger
- if not len(logger.handlers):
- logger.setLevel(logging.DEBUG)
- # create console handler with a higher log level
- ch = logging.StreamHandler()
- ch.setLevel(logging.DEBUG)
- formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
- ch.setFormatter(formatter)
- logger.addHandler(ch)
- logger.info('myfunc was executed directly')
- myfunc()
- $>python main.py
- INFO: 2016-07-14 18:13:04 <module>(22) -- calling mymodule.myfunc()
- done with myfunc
- $>python main.py
- INFO: 2016-07-14 18:13:04 <module>(22) -- calling mymodule.myfunc()
- INFO: 2016-07-14 18:15:09 myfunc(8) -- myfunc is being called
- done with myfunc
- 16 log = logging.getLogger() # use this form to initialize the root logger
- 17 #log = logging.getLogger(__name__) # never use this one
- import logging
- logger = logging.getLogger()
- logger.debug("You will not see this message if you use line 17 in main")
Add Comment
Please, Sign In to add comment