Example of how to use logging for both screen and file

Ville Vainio ville at spammers.com
Fri Oct 22 08:26:18 EDT 2004


Just posting this for the sake of google:

Like everyone else, I figured it's time to start using the 'logging'
module.  

I typically want to dump "info" level (and up) log information to
screen, and "debug" level (and up) to a log file for in-depth
analysis. This is for scripts, so date/time/severity information is
not wanted. I assumed such a simple use case would have an example in
the docs (py 2.4), but no luck.

Here's what worked for me:

import logging

def setupLogging():
    global log
    log = logging.getLogger("myapp")
    log.setLevel(logging.DEBUG)
    sth = logging.StreamHandler()
    sth.setLevel(logging.INFO)
    log.addHandler(sth)
    fhnd = logging.FileHandler('/tmp/myapp.log')
    fhnd.setLevel(logging.DEBUG)
    log.addHandler(fhnd)

setupLogging()

log.info("foo")  # appears on screen and file
log.debug("bar") # appears in the file only


The example might not be ideal, but something like this should really
be in the module documentation. The example config file mostly serves
to intimidate would-be users ("I need to do *that*?!?), and many of
them probably wouldn't want to introduce a third-party wrapper module
either (I think that should be the point of the standard logging
module after all).

-- 
Ville Vainio   http://tinyurl.com/2prnb



More information about the Python-list mailing list