Logging - sjherrick/code-base GitHub Wiki

Logging

Basic logger

import logging

logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s')

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

logger.info('hello')

Result: __main__ - INFO - Info: hello

Stream Handler

  • To prevent from reformatting Flask built-in debugger. Use with all Flask apps
logger = logging.getLogger(__name__)
ch = logging.StreamHandler(stream=sys.stdout)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.setLevel(logging.INFO)

File Handler

log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
fh = logging.FileHandler(LOG_FILE_PATH, 'a')
fh_formatter = logging.Formatter('%(asctime)s %(levelname)-2s %(lineno)d:%(funcName)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
fh.setFormatter(fh_formatter)
log.addHandler(fh)

Docs

Python Doc: https://docs.python.org/3/howto/logging.html

More complex project structure: https://stackoverflow.com/questions/50714316/how-to-use-logging-getlogger-name-in-multiple-modules