Stop Using “print” for Debugging: A 5 Minute Quickstart Guide to Python’s logging Module

  • This tutorial is short.
  • To figure out bugs in your code, you might put in print statements/print() calls to display the value of variables.
  • Don’t do this. Use the Python logging module.

The logging is better than printing because:

  • It’s easy to put a timestamp in each message, which is very handy.
  • You can have different levels of urgency for messages, and filter out less urgent messages.
  • When you want to later find/remove log messages, you won’t get them confused for real print() calls.
  • If you just print to a log file, it’s easy to leave the log function calls in and just ignore them when you don’t need them. (You don’t have to constantly pull out print() calls.)

Using print is for coders with too much time on their hands. Use logging instead. Also, learn to use the Python debugger to debug bugs and Pylint to prevent bugs and make your code readable.

To print log messages to the screen, copy and paste this code:

import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('This is a log message.')

To write log messages to a file, you can copy and paste this code (the only difference is in bold):

import logging
logging.basicConfig(filename='log_filename.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('This is a log message.')

Later runs of the program will append to the end of the log file, rather than overwrite the file.

To log messages to a file AND printed to the screen, copy and paste the following:
(more…)

Read More