python - logging.raiseExceptions = True does not re-raise an exception -
i trying have following functionality in code:
- log info , error messages , exceptions console and/or file, without interrupting program flow (i.e., swallowing exceptions, kind of run mode)
- get development mode, exceptions raised, setting
develop = true
flag
currently, using python3 logging
module, (according this) should have functionality built-in. flag logging.raiseexceptions = true
.
however, not getting work in mwe: exception throwing not re-raised, whatever setting of flag is.
# mwe.py import logging import logging.config if __name__ == '__main__': # configure logging , set flag raise exceptions logging.config.fileconfig('log.conf') logging.raiseexceptions = true logger = logging.getlogger('root') logger.info('started') # test whether exceptions raised try: raise runtimeerror("ooops.") except runtimeerror: try: logger.exception('there oops.') # same logger.error('...', exc_info=true) except: print("gotcha! exception re-raised.") logger.info('finished')
the corresponding config file:
# log.conf [loggers] keys=root [handlers] keys=consolehandler [formatters] keys=consoleformatter [logger_root] handlers=consolehandler level=debug [handler_consolehandler] class=logging.streamhandler formatter=consoleformatter args=(sys.stdout,) [formatter_consoleformatter] format=%(filename)s (%(lineno)d) %(levelname)-8s - %(message)s
this produces following output:
mwe.py (12) info - started mwe.py (19) error - there oops. traceback (most recent call last): file "mwe.py", line 16, in <module> raise runtimeerror("ooops.") runtimeerror: ooops. mwe.py (24) info - finished
why not getting gotcha
part, although default value of raiseexceptions
true
, additionally setting true
? wrong configuration?
or have big misunderstanding use of logging
purpose?
(little bonus question: there way configure raiseexception
flag in log.conf
file?)
you got wrong. not re-raise custom exception. meant change default behaviour of logging module swallowing internal logging exceptions i.e. misconfigured logger trying write file has no permissions write. fail silently default , setting logging.raiseexception = true
cause logger misconfiguration or other problem within logging module raise exception have handle.
now point of trying achieve. having exception traceback logged without suppressing exception (letting propagate) default behaviour. if logging not configured traceback goes stderr. if logging configured, it's written logging handler desired location.
in order achieve goal, should not handle exception @ all. if know how handle exception (meaning know causes exception) don't need traceback logged.
if insist can still use logger.exception(...)
inside except runtimeerror
clause , re-raise exception pure raise
:
try: raise runtimeerror("ooops.") except runtimeerror: logger.exception('there oops.') raise
Comments
Post a Comment