logging module example

Chris Smith smitty_one_each at bigfoot.com
Sun Jan 1 04:26:02 EST 2006


 One thing that made little sense to me when I was first working on
this is the following variation on the original script:

#--begin test script--
import logging

forest      = ["root","trunk","branch","leaf"]
lumber_jack = {forest[0] : logging.DEBUG
              ,forest[1] : logging.INFO
              ,forest[2] : logging.WARNING
              ,forest[3] : logging.ERROR  }
log_name    = []
for log in forest:
    mounty  = logging.FileHandler("%s%s.txt" % ("/home/smitty/mddl/",log))
    log_name.append(log)
    print "Instantiating %s"  % ".".join(log_name)
    timber  = logging.getLogger(".".join(log_name))

    #Comment out explit setting of level for logger
    #timber.setLevel(lumber_jack[log])

    #Commented out totally, called without argument, or called with
    # logging.NOTSET all produce same output

    #timber.setLevel(logging.NOTSET)
    timber.addHandler(mounty)
    if   lumber_jack[log] == logging.DEBUG:
        timber.debug(  "%s's a lumberjack, and he's OK." % log)
    elif lumber_jack[log] == logging.INFO:
        timber.info(   "%s's a lumberjack, and he's OK." % log)
    elif lumber_jack[log] == logging.WARNING:
        timber.warning("%s's a lumberjack, and he's OK." % log)
    elif lumber_jack[log] == logging.ERROR:
        timber.error(  "%s's a lumberjack, and he's OK." % log)
    mounty.emit( logging.LogRecord( timber
                                  , 0
                                  , "/mnt/dmz/proj/mddl4/mddl.py"
                                  , 37
                                  , "burp?"
                                  , None
                                  , None   ))
#--end test script--

#---
#expected output
#---
$ cat root.txt
root's a lumberjack, and he's OK.
burp?
trunk's a lumberjack, and he's OK.
branch's a lumberjack, and he's OK.
leaf's a lumberjack, and he's OK.
$ cat trunk.txt
trunk's a lumberjack, and he's OK.
burp?
branch's a lumberjack, and he's OK.
leaf's a lumberjack, and he's OK.
$ cat branch.txt
branch's a lumberjack, and he's OK.
burp?
leaf's a lumberjack, and he's OK.
$ cat leaf.txt
leaf's a lumberjack, and he's OK.
burp?


#---
#actual output
#---
$ cat root.txt
burp?
branch's a lumberjack, and he's OK.
leaf's a lumberjack, and he's OK.
$ cat trunk.txt
burp?
branch's a lumberjack, and he's OK.
leaf's a lumberjack, and he's OK.
$ cat branch.txt
branch's a lumberjack, and he's OK.
burp?
leaf's a lumberjack, and he's OK.
$ cat leaf.txt
leaf's a lumberjack, and he's OK.
burp?


#-------
 At any rate, I see now that I want to use logging.setLevel() to lay
in my own, more descriptive, levels, and then the straight
logging.log() function to do that for me.
 Ah, the learning curve.
Best,
Chris



More information about the Python-list mailing list