简体   繁体   中英

Include stderr and stdout when logging in python

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 eg 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?

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM