I am new to Python. I now need to make use of logging and here is the experiment I did:
I have 2 files:
logtest_1.py, logtest_2.py
logtest_1.py:
import logging
from logtest_2 import loglib
format = '%(asctime)s: %(levelname)s: %(message)s'
logging.basicConfig(format=format,level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.info('Before calling loglib...')
loglib()
logger.info('Loglib done.')
logtest_2.py: import logging from logging.handlers import TimedRotatingFileHandler import time
def loglib():
logger_2 = logging.getLogger(__name__)
logger_3 = logging.getLogger('TimeRotateLogger')
logger_3.setLevel(logging.DEBUG)
handler = TimedRotatingFileHandler('timerotate.log',
when='s',
interval=2,
backupCount=10)
logger_3.addHandler(handler)
logger_2.info('This is a log from logtest_2.')
time.sleep(1)
for i in range(5):
logger_3.info('Rotation test...')
time.sleep(2)
I try to use logger_3 to write info to those time rotation files. Actually, this works. However, it also prints out to the screen:
2015-02-16 15:26:34,010: INFO: Before calling loglib...
2015-02-16 15:26:34,011: INFO: This is a log from logtest_2.
2015-02-16 15:26:35,019: INFO: Rotation test...
2015-02-16 15:26:37,029: INFO: Rotation test...
2015-02-16 15:26:39,039: INFO: Rotation test...
2015-02-16 15:26:41,049: INFO: Rotation test...
2015-02-16 15:26:43,059: INFO: Rotation test...
2015-02-16 15:26:45,070: INFO: Loglib done.
I only want logger_3 to log into those files. How can I prevent it from printing to the screen?
Also, why this is happening? I've already given the handler to logger_3 which writes to files.
If I really want to keep logging.basicConfig(format=format,level=logging.DEBUG) in the logtest_1.py, what should I do?