16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

386 CHAPTER 19 ■ PLAYFUL PROGRAMMING<br />

the data accumulate, for that matter). A very simple form of logging can be done with the print<br />

statement. Just put a statement like this at the beginning of your program:<br />

log = open('logfile.txt', 'w')<br />

You can then later put any interesting information about the state of your program in<strong>to</strong><br />

this file as follows:<br />

print >> log, ('Downloading file from URL %s' % url)<br />

text = urllib.urlopen(url).read()<br />

print >> log, 'File successfully downloaded'<br />

This approach won’t work well if your program crashes during the download. It would be<br />

safer if you opened and closed your file for every log statement (or, at least, flushed the file after<br />

writing). Then, if your program crashed, you could see that the last line in your log file said<br />

“Downloading file from . . .” and you would know that the download wasn’t successful.<br />

The way <strong>to</strong> go, actually, is using the logging module in the standard library. Basic usage is<br />

pretty straightforward, as demonstrated by the program in Listing 19-3.<br />

Listing 19-3. A Program Using the logging Module<br />

import logging<br />

logging.basicConfig(level=logging.INFO, filename='mylog.log')<br />

logging.info('Starting program')<br />

logging.info('Trying <strong>to</strong> divide 1 by 0')<br />

print 1 / 0<br />

logging.info('The division succeeded')<br />

logging.info('Ending program')<br />

Running that program would result in the following log file (called mylog.log):<br />

INFO:root:Starting program<br />

INFO:root:Trying <strong>to</strong> divide 1 by 0<br />

As you can see, nothing is logged after trying <strong>to</strong> divide 1 by 0 because this error effectively<br />

kills the program. Because this is such a simple error, you can tell what is wrong by the exception<br />

traceback that prints as the program crashes. However, the most difficult type of bug <strong>to</strong> track<br />

down is one that doesn’t s<strong>to</strong>p your program but simply makes it behave strangely. Examining<br />

a detailed log file may help you find out what’s going on.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!