1

I'm trying to understand the way that python logging works.

I get that it is a singleton instance that applies to the entire running interpreter.

I have this function:

def setup_logging(options=None):
  '''setup the logger and return it'''
  logging.basicConfig(level=logging.WARNING,
                      format='%(levelname)s: %(message)s',
                      filename='/tmp/pluser.log')

  logger =  logging.getLogger('pluser')
  console = logging.StreamHandler()
  console.setLevel(logging.DEBUG)
  print(console.level)
  logger.addHandler(console)
  return logger

That I call using this:

  console = setup_logging(options)

  console.debug('Initializing database')
  connect_to_db()
  console.debug('Database initialized')

(This is preparation for doing more logging to different places.)

Now, "console" is a "logging.Logger" instance. It has a StreamHandler. That streamhandler has a level of 10 (which is logging.DEBUG). However, that StreamHandler doesn't appear to get the messages, because things only print to console (which should have stderr and stdout on it) at console.warning, error, or critical.

So, I'm clearly missing something about the way that logger interacts with either the system or the StreamHandler.

My goal is for when the StreamHandler's level is to debug, everything prints to console, but I'd also like to understand why this isn't working.

1
  • I added "logging.StreamHandler(sys.stdout), and then it prints 3 times in a row if I do console.warning, but still doesn't print at debug. Commented Apr 9, 2013 at 16:47

1 Answer 1

1

Ok, so this was answered here: logging setLevel, how it works

To summarize: the logger that you add handlers to needs to be at the level of your handler or lower, otherwise the logger rejects the message before it gets passed to the handler.

So what I had to do was set my basicConfig default to DEBUG, rather than WARNING. If I then want to add another handler that ONLY handles WARNING and above, I would do that, rather than leaving it default.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.