Skip to content

Instantly share code, notes, and snippets.

@BibMartin
Created May 6, 2022 10:53
Show Gist options
  • Save BibMartin/36d3e993c6e859f6f7adb06df7ce64ef to your computer and use it in GitHub Desktop.
Save BibMartin/36d3e993c6e859f6f7adb06df7ce64ef to your computer and use it in GitHub Desktop.
Python logging tips
import sys
import logging
# 1 - Choose a logger (where logs should come from)
# logger = logging.getLogger() # Root logger ; if you're in a notebook of end-user script
logger = logging.getLogger(__name__) # Lib-named logger ; if you're in a module
# logger = logging.getLogger(None if __name__=='__main__' else __name__)
# 2 - Choose the (minimal) log level
logger.setLevel(logging.DEBUG)
# 3 - Create one (or several handlers)
if True:
# 3-a - Choose where logs should go
log_handler = logging.StreamHandler() # Default ; log to formatted (pink) space in notebooks
# log_handler = logging.StreamHandler(stream=sys.stdout) # Log to the console
# log_handler = logging.FileHandler(filename='./logs.log', mode='a') # Log to a file
# import io
# io = io.StringIO()
# log_handler = logging.StreamHandler(stream=io) # Logs to io.StringIO
# 3-b - Choose the log level (>= logger.level)
log_handler.setLevel(logging.WARNING)
# 3-c - Choose the log format
log_handler.setFormatter(logging.Formatter(
'%(asctime)s (%(name)s:%(filename)s:%(lineno)s)- %(levelname)s - %(message)s'))
# 3-d - Add the handler to the logger
logger.addHandler(log_handler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment