qkslvrwolf
qkslvrwolf

Reputation: 199

python logging and handler usage

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.

Upvotes: 1

Views: 196

Answers (1)

qkslvrwolf
qkslvrwolf

Reputation: 199

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.

Upvotes: 1

Related Questions