Python 日志记录完整的异常信息

2023-01-31 02:01:25 记录 异常 完整
基本范式是:

try:

    do-something-block

except:

    logger.exception("Exception Logged")

def setLogger():  
    # 创建一个logger,可以考虑如何将它封装  
    logger = logging.getLogger('mylogger')  
    logger.setLevel(logging.DEBUG)  

    # 创建一个handler,用于写入日志文件  
    fh = logging.FileHandler(os.path.join(os.getcwd(), 'log.txt'))  
    fh.setLevel(logging.DEBUG)  

    # 再创建一个handler,用于输出到控制台  
    ch = logging.StreamHandler()  
    ch.setLevel(logging.DEBUG)  

    # 定义handler的输出格式  
    fORMatter = logging.Formatter('%(asctime)s - %(module)s.%(funcName)s.%(lineno)d - %(levelname)s - %(message)s')  
    fh.setFormatter(formatter)  
    ch.setFormatter(formatter)  

    # 给logger添加handler  
    logger.addHandler(fh)  
    logger.addHandler(ch)  

    # 记录一条日志  
    logger.info('hello world, i\'m log helper in python, may i help you')  
    return logger  



#对单个表插入一个元组,其定义有  
def insertOneData(conn,tableName,listColumn,lData):  
    try:  
        cursor=conn.cursor()  
        sql="insert into "+tableName+"("  
        i=0  
        length=len(listColumn)  
        for column in listColumn:  
            if(i!=(length-1)):  
                sql=sql+column+","  
            else:  
                sql=sql+column+") values("  
            i=i+1  
        for i in range(0,length):  
            if(i!=(length-1)):  
                sql=sql+"%s,"  
            else:  
                sql=sql+"%s);"  
        logger.info(sql)  
        logger.info(lData)  
        cursor.execute(sql,lData);  
        conn.commit()  
    except:  
        logger.exception("Exception Logged")  

参考资料:

1、Python日志记录完整的异常信息traceback stack

https://blog.csdn.net/waleking/article/details/7524854


相关文章