Last active
January 18, 2024 14:22
-
-
Save asyd/1e1630dbfa59dbd944aa775312b98a6e to your computer and use it in GitHub Desktop.
Python logging example
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 | |
import argparse | |
logger = logging.getLogger(__name__) | |
def main(): | |
logger.debug("debug message not visible except if you use --debug") | |
logger.critical("critical message, always visible") | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser( | |
"my super script", | |
# This will default value in usage | |
formatter_class=argparse.ArgumentDefaultsHelpFormatter | |
) | |
parser.add_argument("--debug", help="Enable debug", default=False, action='store_true') | |
parser.add_argument("--debug-requests", help="Debug HTTPs requests", default=False, action='store_true') | |
logging.basicConfig() | |
args = parser.parse_args() | |
if args.debug: | |
logging.getLogger(__name__).setLevel(logging.DEBUG) | |
if args.debug_requests: | |
import http.client as http_client | |
http_client.HTTPConnection.debuglevel = 1 | |
requests_logger = logging.getLogger('requests') | |
requests_logger.setLevel(logging.DEBUG) | |
requests_logger.propagate = True | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment