python exception message capturing

前端 未结 11 1673
醉梦人生
醉梦人生 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:44

    You can use logger.exception("msg") for logging exception with traceback:

    try:
        #your code
    except Exception as e:
        logger.exception('Failed: ' + str(e))
    
    0 讨论(0)
  • 2020-12-12 09:46

    You have to define which type of exception you want to catch. So write except Exception, e: instead of except, e: for a general exception (that will be logged anyway).

    Other possibility is to write your whole try/except code this way:

    try:
        with open(filepath,'rb') as f:
            con.storbinary('STOR '+ filepath, f)
        logger.info('File successfully uploaded to '+ FTPADDR)
    except Exception, e: # work on python 2.x
        logger.error('Failed to upload to ftp: '+ str(e))
    

    in Python 3.x and modern versions of Python 2.x use except Exception as e instead of except Exception, e:

    try:
        with open(filepath,'rb') as f:
            con.storbinary('STOR '+ filepath, f)
        logger.info('File successfully uploaded to '+ FTPADDR)
    except Exception as e: # work on python 3.x
        logger.error('Failed to upload to ftp: '+ str(e))
    
    0 讨论(0)
  • 2020-12-12 09:48

    The syntax is no longer supported in python 3. Use the following instead.

    try:
        do_something()
    except BaseException as e:
        logger.error('Failed to do something: ' + str(e))
    
    0 讨论(0)
  • 2020-12-12 09:52

    After python 3.6, you can use formatted string literal. It's neat! (https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498)

    try
     ...
    except Exception as e:
        logger.error(f"Failed to upload to ftp: {e}")
    
    0 讨论(0)
  • 2020-12-12 09:54

    Use str(ex) to print execption

    try:
       #your code
    except ex:
       print(str(ex))
    
    0 讨论(0)
提交回复
热议问题