2
votes

I can't figure out why log events are being printed to the console when I have not defined a console handler. All of the examples I read through have explicitly defined a console handler (streamhandler) in order to print messages to the console.

I want these events to be printed to a file only.

import logging
logger = logging.getLogger(__name__)

my_format = '%(asctime)-25s  %(levelname)-8s  LOGGER: %(name)-12s  MODULE: %(module)-15s FUNCTION: %(funcName)-30s MSG: %(message)s'
my_datefmt ='%m/%d/%Y %I:%M:%S%p'
logging.basicConfig(format=my_format, datefmt=my_datefmt, level=logging.DEBUG)
formatter = logging.Formatter(my_format, datefmt=my_datefmt)
logger.setLevel(logging.DEBUG)
handler1 = logging.FileHandler('mylog.txt')
handler1.setLevel(logging.DEBUG)
handler1.setFormatter(formatter)
logger.addHandler(handler1)

logger.debug("Why is this printed to the console")

EDIT:

It has been pointed out that I was not considering the root logger. Upon calling logging.basicConfig, a default streamhandler is added to the root logger (logger = getLogger())

The root logger's handler can be modified, however I have found that I can just prevent my logger from propagating logs up to the root logger.

This can be done like so:

import logging
logger = logging.getLogger(__name__)

my_format = '%(asctime)-25s  %(levelname)-8s  LOGGER: %(name)-12s  MODULE: %(module)-15s FUNCTION: %(funcName)-30s MSG: %(message)s'
my_datefmt ='%m/%d/%Y %I:%M:%S%p'
logging.basicConfig(format=my_format, datefmt=my_datefmt, level=logging.DEBUG)
formatter = logging.Formatter(my_format, datefmt=my_datefmt)
logger.setLevel(logging.DEBUG)
handler1 = logging.FileHandler('mylog.txt')
handler1.setLevel(logging.DEBUG)
handler1.setFormatter(formatter)
logger.addHandler(handler1)
logger.propagate = False             ####
logger.debug("Why is this printed to the console")
1
Thanks! For quick reference: The only addition you made is: logger.propagate = Falselode

1 Answers

4
votes
> ipython
import logging
logging.basicConfig?

*****************logging.basicConfig**************
Signature: logging.basicConfig(**kwargs)
Docstring:
Do basic configuration for the logging system.

This function does nothing if the root logger already has handlers
configured. It is a convenience method intended for use by simple scripts
to do one-shot configuration of the logging package.

The default behaviour is to create a StreamHandler which writes to
sys.stderr, set a formatter using the BASIC_FORMAT format string, and
add the handler to the root logger.
...

You have 2 handlers.