9

I am trying to include simple logging into my application using TimedRotatingFileHandler. However I get the output both into the designated file and into the standard error. I reduced the problem to a small example:

import logging, logging.handlers
import sys

logging.basicConfig(format='%(asctime)s %(message)s')
loghandler = logging.handlers.TimedRotatingFileHandler("logfile",when="midnight")
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(loghandler)

for k in range(5):
    logger.info("Line %d" %  k)

I get 5 log lines both in my 'logfile' and this program's stderr. What am I doing wrong?

Tsf
  • 1,339
  • 5
  • 17
  • 29

2 Answers2

17

This is the way you can have the print just on the log files and not to stdout/stderr:

import logging
from logging.handlers import TimedRotatingFileHandler

logHandler = TimedRotatingFileHandler("logfile",when="midnight")
logFormatter = logging.Formatter('%(asctime)s %(message)s')
logHandler.setFormatter( logFormatter )
logger = logging.getLogger( 'MyLogger' )
logger.addHandler( logHandler )
logger.setLevel( logging.INFO )

for k in range(5):
    logger.info("Line %d" %  k)
Cinquo
  • 633
  • 1
  • 6
  • 17
5

logging.basicConfig sets up a handler that prints to standard error. logger.addHandler(loghandler) sets up a TimedRotatingFileHandler.

Do you wish to squelch output to standard error? If so, simply remove the call tologging.basicConfig.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Note you can add multiple handlers according to https://docs.python.org/2/howto/logging-cookbook.html#multiple-handlers-and-formatters – MarkHu May 15 '17 at 22:43