简体   繁体   中英

own Logger doesn't log Exception, but root logger does

I am trying to log all exceptions within my application. I want to have different handlers, one handler to log all information to a file and only critical problems to my email.

I created a file_handler, which should log everything and email_handler for the critical problems. The handlers work, apart from catching unexpected errors. I tried to log everything with the root logger, which has the same configuration as the file_handler, which works. Why doesn't my file_handler catch unexpected errors?

Here is my code:

# root logger
logging.basicConfig(filename='flask.log', level=logging.WARNING)

# own logger
logger = logging.getLogger('flask')
file_handler = logging.handlers.TimedRotatingFileHandler('flask.log', when='D', interval=1)
email_handler = SMTPHandler(...)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger.setLevel(logging.DEBUG)
file_handler.setLevel(logging.DEBUG)
email_handler.setLevel(logging.WARNING)
file_handler.setFormatter(formatter)
email_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(email_handler)

If I have an error in a function (example Class A doesn't has attribute X), the unexpected problem only gets logged by the root logger.

Workaround:

If I don't give "my" logger a name, I get the root logger. My handlers then take his information and distribute them. It is not ideal, because it should work with "my" logger as well.

Workaround code:

# own logger
logger = logging.getLogger() # no name -> logger = root logger
file_handler = logging.handlers.TimedRotatingFileHandler('flask.log', when='D', interval=1)
email_handler = SMTPHandler(...)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger.setLevel(logging.DEBUG)
file_handler.setLevel(logging.DEBUG)
email_handler.setLevel(logging.WARNING)
file_handler.setFormatter(formatter)
email_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(email_handler)

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