Last active
June 16, 2020 11:56
-
-
Save CMCDragonkai/599653a5479cffc383a71fa4842170e4 to your computer and use it in GitHub Desktop.
Python Logging #python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
import argparse | |
import logging | |
import custom_module | |
def verbose_to_loglevel(c): | |
loglevel = logging.WARNING | |
if c == 1: | |
loglevel = logging.INFO | |
elif c >= 2: | |
loglevel = logging.DEBUG | |
return loglevel | |
def main(args): | |
args_parser = argparse.ArgumentParser() | |
args_parser.add_argument( | |
'-v', | |
'--verbose', | |
help='Log Verbose Messages', | |
action='count', | |
default=0) | |
args = args_parser.parse_args(args) | |
logging.basicConfig(level=verbose_to_loglevel(args.verbose)) | |
# in a script or executable module, the __name__ becomes __main__ | |
logger = logging.getLogger(__name__) | |
logger.info('Done!') | |
if __name__ == '__main__': | |
main(sys.argv[1:]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
# by convention the logger name corresponds to the module name | |
# which we can utilise by just using __name__ | |
logger = logging.getLogger(__name__) | |
def f1(): | |
logger.info('calling f1') | |
return | |
def f2(): | |
# we don't always have to use the module name | |
# especially if we think that f2 represents its own unique entity | |
# do note there's also %(funcName)s that is available in the format | |
# however that's global | |
logger.getLogger(__name__ + '.f2') | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment