[Tutor] Python Logging Module
chase.mp at gmail.com
chase.mp at gmail.com
Wed Apr 8 00:34:29 CEST 2009
Hello everyone...
My intention is to create a generic logging function I can use across
scripts. I have a few things I would like this function to be able to
accomplish:
1. log info and above to console
2. log debug and above to file
3. format the output for each differently
4. allow areas of a program to use a different "logger", basically putting
a different name in the event depending on which of my bad ideas broke the
system
5. control log rotation within the script itself
so far I have accomplished a lot of hair pulling...the following does some
of the above:
import logging
import sys
LOG_FILENAME = "./testing.log"
def set_logging():
# Set up a specific logger
my_logger = logging.getLogger(sys.argv[0])
# set up logging defaults
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M:%S',
filename=LOG_FILENAME,
filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
set_logging()
logging.debug("test_debug")
logging.info("testing_info")
I also have a separate bit that can do the rotation:
import glob
import logging
import logging.handlers
import sys
LOG_FILENAME = './logging_rotateout'
# Set up a specific logger with our desired output level
fullscriptname = os.path.split(sys.argv[0])
scriptname = fullscriptname[1]
log = logging.getLogger(scriptname)
log.setLevel(logging.DEBUG)
# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=20,
backupCount=5)
log.addHandler(handler)
#log messages
log.debug("testing")
log.info("console")
I cannot for the life of me seem to combine these two functions, this seems
odd to me, but I think I do not understand what logging.basicConfig does in
the previous example. If I try to add:
handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=20,
backupCount=5)
logging.getLogger('').addHandler(handler)
to the first piece of code I get all kinds of errors, but mainly:
AttributeError: 'module' object has no attribute handlers
I get this even though the line above it obviously adds the console
handler. I have tried many things, I wish I had documented better all of my
attempts at syntax.
Any help would be greatly appreciated. Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090407/c540c968/attachment-0001.htm>
More information about the Tutor
mailing list