python exception message capturing

前端 未结 11 1700
醉梦人生
醉梦人生 2020-12-12 09:06
import ftplib
import urllib2
import os
import logging
logger = logging.getLogger(\'ftpuploader\')
hdlr = logging.FileHandler(\'ftplog.log\')
formatter = logging.Form         


        
11条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 09:29

    Updating this to something simpler for logger (works for both python 2 and 3). You do not need traceback module.

    import logging
    
    logger = logging.Logger('catch_all')
    
    def catchEverythingInLog():
        try:
            ... do something ...
        except Exception as e:
            logger.error(e, exc_info=True)
            ... exception handling ...
    

    This is now the old way (though still works):

    import sys, traceback
    
    def catchEverything():
        try:
            ... some operation(s) ...
        except:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            ... exception handling ...
    

    exc_value is the error message.

提交回复
热议问题