Low Orbit Flux Logo 2 F

Python How To Log Errors

Logging errors in Python is relatively easy and painless. There exists a logging module with functions that makes this easy.


import logging

logging.debug('Debugging info goes here.')
logging.info('Informational message goes here.')
logging.warning('Something isn't right.')
logging.error('The application is broken.')
logging.critical('The entire system is down.')

Logging is set to warning or above by default. Anything else won’t be logged. You can change it like this.


logging.basicConfig(level=logging.DEBUG)

You can log to a file like this:


logging.basicConfig(filename='mycustomapplication.log', filemode='w')

You can set the format of a log message like this:


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

Calling basic config more than once will overwrite the configs you set initially. You can combine all of those together like this.


logging.basicConfig(level=logging.DEBUG, filename='mycustomapplication.log', filemode='w', format='%(process)d-%(levelname)s-%(message)s')

Here is an example showing you you might put everything together.


import logging

logging.basicConfig(level=logging.DEBUG, filename='mycustomapplication.log', filemode='w', format='%(process)d-%(levelname)s-%(message)s')

logging.debug('Debugging info goes here.')
logging.info('Informational message goes here.')
logging.warning('Something isn't right.')
logging.error('The application is broken.')
logging.critical('The entire system is down.')