0

I'm trying to add some logging to my application however I can't seem to get the correct log level statements to display. I have set my logger to INFO yet it only displays warnings and errors in both the console and log file

Am I missing anything?

import logging

logger = logging.getLogger("mo_test")
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

fh = logging.FileHandler('test.log')
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
fh.setLevel(logging.INFO)
fh.setFormatter(formatter)
ch.setFormatter(formatter)

logger.addHandler(fh)
logger.addHandler(ch)

logger.info("This is an Info")
logger.debug("this is a debug")
logger.warning("This is a warning")
logger.error("Oh error")

The content of the log file and console is then only:

2015-03-09 15:32:44,601 - mo_test - WARNING - This is a warning
2015-03-09 15:32:44,601 - mo_test - ERROR - Oh error

Thanks

Mo.
  • 40,243
  • 37
  • 86
  • 131

2 Answers2

1

Set the logging level on the logger. If you don't set it, the default logging level is 30, i.e. logging.WARNING:

logger = logging.getLogger("mo_test")
logger.setLevel(logging.INFO)

The logging flow chart shows how the logger itself filters by logging level ("Logger enabled for level of call?") even before the handlers get a chance to handle the record ("Handler enabled for level of LogRecord?"):

enter image description here

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

You seem to be missing a call to ``logging.basicConfig(). Without this call,logging` is in an unconfigured state and anything can happen.

msw
  • 42,753
  • 9
  • 87
  • 112
  • Vinay Sajip, maintainer/developer of the logging module, [shows `basicConfig` is just a convenience function](http://stackoverflow.com/a/4139462/190597). You are free to set up logging without it. – unutbu Mar 09 '15 at 19:43