1

Having the following logging:

log_name = pd.datetime.now().date().strftime(format="%Y-%m-%d")+".log" #Current day
log_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))+"/logs/" #Path
logging.basicConfig(filename=log_path+log_name,filemode="a",level = logging.INFO)

is there a way to catch "Unknown" exceptions (such as pd.to_sql errors due to e.g typo in the column name) and write them to the same logger file specified in logging.basicConfig without having try/catches all over the place?

CutePoison
  • 4,679
  • 5
  • 28
  • 63

1 Answers1

1

Most of the times i use a combination of traceback library(standard) and a very big try-except clause under lets say main() function.So any uncaught error can be logged without special treatment. I hope fits your needs. Example:

import logging
import traceback

try:
    main()
except:
    logger.warning(traceback.format_exc())
  • That's exactly the point I referred to as "without having try/catches all over the place", since they are where you can expect an error, but if the error is unexpected it is not caught – CutePoison Mar 17 '21 at 17:28
  • Why not use `logger.exception`? – Daniel Walker Mar 17 '21 at 17:31
  • In a try/catch ? I want a way to catch un-wanted exceptions and log that. In a try/catch you expect an exception to be there. I could of course wrap the entire `main()` in a `try: main; except Exception as e: logging.except(e)` but I doubt that is the cleanest way to do so. – CutePoison Mar 17 '21 at 18:58
  • As @DanielWalker suggested logger.exception can be used,but traceback will log a whole lot of more info.As it seems there was already a popular question https://stackoverflow.com/questions/4990718/about-catching-any-exception with no siginifcant other methodologies.The methodology i suggested works the way you expect.I dont think there is a real alternative other than try-except. – Ευάγγελος Γρηγορόπουλος Mar 18 '21 at 00:31