简体   繁体   中英

Python logging issue?

I am writing the below code to log messages into a file:

#!/usr/bin/python3

import logging 

## init logger
logger = logging.getLogger(__name__)

## create handler file
handler = logging.FileHandler('mylog3.log')

## set log level
handler.setLevel(logging.INFO)

## add handler to logger
logger.addHandler(handler)

l = [1, 2, 3, 4]
i = 3

logger.info('This is an info message')
logger.warning('This is a warning message')
logger.debug('This is a debug message.  I=%d l=%s', i, l)
logger.error('This is an error message. l =%s', l)
logger.fatal('This is a fatal error message')

The problem I am seeing is that no matter what setting I give, it always prints the warning, error and fatal error messages in file. The debug and info messages are never written.

I verified that I am seeing the issue w/ both PyCharm on Windows and also on my Ubuntu linux Python 3. So, it must be that I am doing something wrong. What can it be? I am at a loss!

The debug and info messages are not shown because of the line handler.setLevel(logging.INFO) . This causes all messages of level logging.INFO or less (only info and debug) to not be shown. You can replace loggign.INFO with logging.NOTSET to fix this.

Both loggers and handlers have levels. You've set the level for the handler, but not for the logger - and that defaults to WARNING . If you do eg logger.setLevel(logging.DEBUG) , you should see DEBUG and INFO messages as well (if you don't set a level on the handler at all) or INFO messages but not DEBUG messages (if you set the handler's level to logging.INFO ).

See this diagram for more info on the information flow in logging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM