slybloty
slybloty

Reputation: 6506

logging level vs handler level

What is the difference between setting the logging level from the logger and from the handler?

The following code:

myLogging = logging.getLogger('myOp')
myLogging.setLevel(10)
hdlr = logging.FileHandler(myLogFile)
myLogging.addHandler(hdlr)
myLogging.debug("Message here")

will log to myLogFile, but this other one won't:

myLogging = logging.getLogger('myOp')
hdlr = logging.FileHandler(myLogFile)
hdlr.setLevel(10)
myLogging.addHandler(hdlr)
myLogging.debug("Message here")

Why is it that the FileHandler.setLevel() won't write to myLogFile?

Upvotes: 5

Views: 2199

Answers (2)

MEOWWWWWWWW
MEOWWWWWWWW

Reputation: 325

When LoggingCall(like logging.info('blah blah') is occurred in user code, Logger instance determines whether or not to create your LogRecord based on its log level. If the record is created, it will go through filters, and then passed to handlers.

So in the second case,

myLogging = logging.getLogger('myOp')
hdlr = logging.FileHandler(myLogFile)
hdlr.setLevel(10)
myLogging.addHandler(hdlr)
myLogging.debug("Message here")

the log you tried to make(myLogging.debug("Message here")) is not created.

See this logging flow illustration on python documentation.

Upvotes: 0

Sraw
Sraw

Reputation: 20214

logger is higher than handler. You can image that handler is a filter. For example, you have one logger with two handlers:

myLogging = logging.getLogger('myOp')
myLogging.setLevel(10)

hdlr1 = xxx
hdlr2 = xxx
hdlr1.setLevel(20)
hdlr2.setLevel(30)

myLogging.addHandler(hdlr1)
myLogging.addHandler(hdlr2)

In this case, logger itself will log 10+,hdlr1 will log more information than hdlr2(20+ vs 30+).

And back to your case, although you have set hdlr.setLevel(10), but suppose your logger's level is 20, this is like an inverted triangle.

Upvotes: 5

Related Questions