The problem
What is the best way to deal with situation that I want to log an exception to console, file, etc. and then terminate the program? Suppose I read in a config and validate whether the entries given make sense. If not, I want to raise an InvalidConfigError, log this error and terminate since there is no way to recover from this.
What I've done
try:
config = validate_config(read_config(cfg_file_path))
except InvalidConfigError:
logging.getLogger(__name__).exception(f'Config validation failed.')
exit(1)
Thoughts
When I do (notice raise
)
try:
config = validate_config(read_config(cfg_file_path))
except InvalidConfigError:
logging.getLogger(__name__).exception(f'Config validation failed.')
raise
I will get duplicated tracebacks in my console log since I log the whole thing incl. the traceback in my exception logging call and then raise it again which will print the whole thing again.
Is there a better way to do this? I feel like exit(1) is not particularly nice.
My logging config
version: 1
disable_existing_loggers: False
formatters:
simple:
format: "%(asctime)s : %(name)-12s : %(levelname)-10s %(message)s"
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
stream: ext://sys.stdout
info_file_handler:
class: logging.handlers.RotatingFileHandler
level: INFO
formatter: simple
filename: data/logs/info.log
maxBytes: 10485760 # 10MB
backupCount: 5
encoding: utf8
error_file_handler:
class: logging.handlers.RotatingFileHandler
level: ERROR
formatter: simple
filename: data/logs/errors.log
maxBytes: 10485760 # 10MB
backupCount: 5
encoding: utf8
root:
level: DEBUG
handlers: [console, info_file_handler, error_file_handler]