Mat*_*att 5 python logging exception raise
处理我想将异常记录到控制台、文件等然后终止程序的情况的最佳方法是什么?假设我读入配置并验证给出的条目是否有意义。如果没有,我想引发 InvalidConfigError,记录此错误并终止,因为无法从中恢复。
try:
config = validate_config(read_config(cfg_file_path))
except InvalidConfigError:
logging.getLogger(__name__).exception(f'Config validation failed.')
exit(1)
Run Code Online (Sandbox Code Playgroud)
当我这样做时(注意raise
)
try:
config = validate_config(read_config(cfg_file_path))
except InvalidConfigError:
logging.getLogger(__name__).exception(f'Config validation failed.')
raise
Run Code Online (Sandbox Code Playgroud)
由于我记录了整个事件(包括),因此我将在控制台日志中获得重复的回溯。我的异常日志记录调用中的回溯,然后再次引发它,这将再次打印整个内容。
有一个更好的方法吗?我觉得 exit(1) 不是特别好。
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]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
789 次 |
最近记录: |