Why does logger.info() only appear after calling logging.info()?

后端 未结 2 2070
隐瞒了意图╮
隐瞒了意图╮ 2021-02-08 10:45

I am using Python 3.6.4. I first encountered an issue where logger.setLevel(logging.INFO) was ignored, and came across this answer, which confused me and gave rise

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-08 11:00

    Refer to the accepted answer on that post:

    If you don't configure logging with any handlers (as in your post - you only configure a level for your logger, but no handlers anywhere), you'll get an internal handler "of last resort" which is set to output just the message (with no other formatting) at the WARNING level.

    Your level is currently less than WARNING, so it is not output. This changes with a call to basicConfig() which you may/should do explicitly, otherwise it's not being handled until it's called from logging.info (or one of the other convenience functions).

    The documentation observes this:

    Note The above module-level convenience functions, which delegate to the root logger, call basicConfig() to ensure that at least one handler is available. Because of this, they should not be used in threads, in versions of Python earlier than 2.7.1 and 3.2, unless at least one handler has been added to the root logger before the threads are started. In earlier versions of Python, due to a thread safety shortcoming in basicConfig(), this can (under rare circumstances) lead to handlers being added multiple times to the root logger, which can in turn lead to multiple messages for the same event.

提交回复
热议问题