Using print statements only to debug
The logging
module has everything you could want. It may seem excessive at first, but only use the parts you need. I'd recommend using logging.basicConfig
to toggle the logging level to stderr
and the simple log methods, debug
, info
, warning
, error
and critical
.
import logging, sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logging.debug('A debug message!')
logging.info('We processed %d records', len(processed_records))
A simple way to do this is to call a logging function:
DEBUG = True
def log(s):
if DEBUG:
print s
log("hello world")
Then you can change the value of DEBUG
and run your code with or without logging.
The standard logging
module has a more elaborate mechanism for this.
Use the logging built-in library module instead of printing.
You create a Logger
object (say logger
), and then after that, whenever you insert a debug print, you just put:
logger.debug("Some string")
You can use logger.setLevel
at the start of the program to set the output level. If you set it to DEBUG, it will print all the debugs. Set it to INFO or higher and immediately all of the debugs will disappear.
You can also use it to log more serious things, at different levels (INFO, WARNING and ERROR).