durusmail: quixote-users: Re: debug output with time stamp?
debug output with time stamp?
Re: debug output with time stamp?
2003-07-22
2003-07-22
Re: debug output with time stamp?
Graham Fawcett
2003-07-22
Mark Bucciarelli wrote:
> is there an easy way to prefix a timestamp to debug output generated
> with print statements?
>
> regards,

My two cents' would be to investigate the logging package available with
Python 2.3. Note that you would use `somelog.debug()` instead of print.
But it's definitely worth the effort.


The code on which the 2.3 logging package is based is available at:

        http://www.red-dove.com/python_logging.html

though I'm sure the latest and best is available, and backportable, from
Python CVS.

Here's a crappy example of using it. In your startup script, add
something like:

     import logging
     logging.basicConfig()
     root = logging.getLogger()
     root.setLevel(logging.DEBUG)
     root.handlers[0].setFormatter(
         logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))


Actually, that's really ugly, but read the docs & you'll find a better
way to do it. What you've done here is initialized logging, set the
filter level to show DEBUG or higher messages, and given a format string.

Then in your various modules:


     import logging
     ....
     logging.info('this is the time')
     logging.debug('so is this')

would result in:

     2003-07-22 12:48:23,358 [INFO] this is the time
     2003-07-22 12:48:23,358 [DEBUG] so is this

The int after the comma is the clock() time since the process started.

What I like most about the package is the ability, at one point (in my
example, the root.setLevel() call), to turn off a whole category of
output. By setting the level higher, e.g. to logging.INFO, all the
debug() statements in your code are disabled, and will not print out.

Note that you can set up different log objects for different modules
(with different formatters), and you can redirect particular logs to
files, sockets, etc. I haven't done it justice, check out the docs.

-- Graham



reply