multiple logger

P

peiyin.li

Hi,

I want to have two loggers that logs to two different files. Here is
what I have:

import logging
import logging.handlers

project1Handler = logging.handlers.RotatingFileHandler( 'project1.log',
maxBytes=1024)
project1Handler.setLevel(logging.INFO)
formatter1 = logging.Formatter('%(name)-12s: %(levelname)-8s
%(message)s')
project1Handler.setFormatter(formatter1)
logging.getLogger('project1').addHandler(project1Handler)
logger1 = logging.getLogger('project1')

logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger1.warning('Jail zesty vixen who grabbed pay from quack.')
logger1.error('The five boxing wizards jump quickly.')


project2Handler = logging.handlers.RotatingFileHandler( 'project2.log',
maxBytes=1024)
project2Handler.setLevel(logging.DEBUG)
formatter2 = logging.Formatter('%(name)-12s: %(levelname)-8s
%(message)s')
project2Handler.setFormatter(formatter2)
logging.getLogger('project2').addHandler(project2Handler)
logger2 = logging.getLogger('project2')

logger2.debug('Quick zephyrs blow, vexing daft Jim.')
logger2.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')


However, I got this for project1.log:

project1 : WARNING Jail zesty vixen who grabbed pay from quack.
project1 : ERROR The five boxing wizards jump quickly.

and this for project2.log:

project2 : WARNING Jail zesty vixen who grabbed pay from quack.
project2 : ERROR The five boxing wizards jump quickly.

Where are the DEBUG and INFO messages go?

I then add this at the begining of my code:

logging.basicConfig(level=logging.DEBUG)

Now it seems that both project1.log and project2.log has the correct
output. But I also see all the log message going to the console, which
I really don't want.

What did I miss here? Do I have to set a handler for the root logger
before I can set something for the child loggers? If yes, how do I make
the root logger logs to nowhere?

Thanks in advance!

Albert
 
V

Vinay Sajip

Just replace

logging.basicConfig(level=logging.DEBUG)

with

logging.getLogger().setLevel(logging.DEBUG)

and you will no longer get messages written to the console. The
basicConfig() method is meant for really basic use of logging - it
allows one call to set level, and to add either a console handler a
simple (non-rotating) file handler to the root logger. See the
documentation for more information.

Vinay Sajip
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,586
Members
45,084
Latest member
HansGeorgi

Latest Threads

Top