Logging vs printing

alisonken1 alisonken1 at gmail.com
Mon May 8 13:21:20 EDT 2006


Leo Breebaart wrote:

<SNIP>
> Also, assume that I have set it up as above. Now I want certain
> other print statements to go to sys.stderr alone. If I understand
> the docs correctly (possibly I don't), the way to do this is to
> start attaching explicit StreamHandlers and whatnot. Whereas with
> print, I can say "print >>sys.stderr, msg".
<SNIP>

Something else to consider, every time your script calls "print
>>sys.stderr, msg", it is making another file open request.

I've run across situations where this format will actually cause a
system to return "too many open files" error.

As was pointed out earlier, it's much easier to learn how to use the
logging facility and create a default stdout logger as well as a
secondary stderr logger that only maintains one file handle than to try
to find out where you're getting some errors that are not script errors
but system limit errors.

The other nice aspect of using the logging facility is the availability
of changing the logger to save output to a file or stdout/stderr than
to try and go through a more-than-one-file program.

It's easy to learn how to redirect stdout/stderr within a script, but
it's usually more flexible to use the logging facility that's already
been included. Before the logging module was included in the library, I
usually ended up writing my own logging module to do the same thing.
Especially since the logger allows you to specify levels.

For example, I typically have my logging facility setup as follows:

10 - Very basic logging - typically main routine changes
20 - Log imports
30 - Log class instantiation
40 - Log module calls
50 - Log function calls

The other aspect of using the logging facility, you can also define
your own in-between log levels:

51 - Entering function
52 - Exiting function
53 - Function sub-routines
60 - Everyhing under the sun

As part of the configParser options:
-v : Increment logging level by 1 level for every -v option on command
line
-loglevel=<level> : Specify log level
-logfile=<filename> : File to save stdout messages
-errfile=<filename> : File to save stderr messages

Once you get used to the logging module, it's hard to go back to using
file redirects and the <sometimes> system limits troubleshooting in
larger programs.




More information about the Python-list mailing list