import ftplib
import urllib2
import os
import logging
logger = logging.getLogger(\'ftpuploader\')
hdlr = logging.FileHandler(\'ftplog.log\')
formatter = logging.Form
You can use logger.exception("msg")
for logging exception with traceback:
try:
#your code
except Exception as e:
logger.exception('Failed: ' + str(e))
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))
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))
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}")
Use str(ex) to print execption
try:
#your code
except ex:
print(str(ex))