Logging

Python Loggin module is logging

Five standated logging leveles

  • DEBUG
  • INFO
  • WARNING
  • ERROR
  • CRITICAL

Default logging level is WARNING

To set the logging level:
logging.basicConfig(level=logging.DEBUG)

To create a log file:
logging.basicConfig(filename='test.log', level=logging.DEBUG)

To change the Log format to output time, loglevel and message:

logging.basicConfig(filename='test.log', level=logging.DEBUG,
    format='%(asctime)s:%(levelname)s:%(message)s)'

For list of attribute names:
https://docs.python.org/3/library/logging.html#logrecord-attributes

It is recomended to use a separate logger, else root logger would be used.

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s')

# To send the logs to file and set the format
file_handler = loggin.FileHandler('filename.log')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)


# To send the logs to console output and set the format
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)

# To send the logs level error or more
logger.error('some error goes here')
# To include traceback in addition the error message
logger.exception('some error goes here')
logger.info('some information goes here')

Note

By default, logger.exception uses the log level of ERROR. Alternatively, you can use the regular logging methods— logger.debug(), logger.info(), logger.warn(), etc. and pass the exc_info parameter, setting it to True.

Example

while True:
    try:
        main_loop()
    except Exception:
        logger.warning("Fatal error in main loop", exc_info=True)