0 votes
1 view
in Python by (19k points)

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 a syntax error, what is the proper way of doing this for logging all kind of exceptions to a file

1 Answer

0 votes
by (107k points)

For python exception message capturing you are required to define which type of exception you want to catch. So to do so you will write except Exception, e: instead of except, e that you have written.

  • So below is the correct way of writing the try/except code which you should write in your code as well to capture the exception message.

  • Another important advice if you are using Python 3.x then instead of except Exception e you are advised to use except Exception as e.

try:

   with open(filepath,'rb') as f:

         con.storbinary('STOR '+ filepath, f)

         logger.info('File successfully uploaded to '+ FTPADDR)

except Exception, e:

       logger.error('Failed to upload to ftp: '+ str(e))

Related questions

0 votes
1 answer
0 votes
1 answer
asked Nov 25, 2020 in Python by ashely (50.5k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...