HiveBrain v1.2.0
Get Started
← Back to all entries
debugpythonCritical

python exception message capturing

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
capturingmessageexceptionpython

Problem

import ftplib
import urllib2
import os
import logging
logger = logging.getLogger('ftpuploader')
hdlr = logging.FileHandler('ftplog.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
FTPADDR = "some ftp address"

def upload_to_ftp(con, filepath):
    try:
        f = open(filepath,'rb')                # file to send
        con.storbinary('STOR '+ filepath, f)         # Send the file
        f.close()                                # Close file and FTP
        logger.info('File successfully uploaded to '+ FTPADDR)
    except, e:
        logger.error('Failed to upload to ftp: '+ str(e))


This doesn't seem to work, I get syntax error, what is the proper way of doing this for logging all kind of exceptions to a file

Solution

You have to define which type of exception you want to catch. So write except Exception as e: instead of except, e: for a general exception.

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 as e:      # works on python 3.x
    logger.error('Failed to upload to ftp: %s', repr(e))


In older versions of Python 2.x, use except Exception, e instead of except Exception as e:

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

Code Snippets

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

Context

Stack Overflow Q#4690600, score: 1285

Revisions (0)

No revisions yet.