import logging
import sys
import pymysql
class MySQLHandler(logging.Handler):
def __init__(self, host, user, password, database):
super().__init__()
self.connection = pymysql.connect(
host=host,
user=user,
passwd=password,
database=database,
charset="utf8"
)
self.cursor = self.connection.cursor()
def emit(self, record):
log_entry = self.format(record)
query = "INSERT INTO error_log (time, level, message) VALUES (%s, %s, %s)"
self.cursor.execute(query, (record.asctime, record.levelname, log_entry))
# 提交事务并关闭连接
self.connection.commit()
self.cursor.close()
self.connection.close()
def error_log():
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
db_handler = MySQLHandler(host,user, password, database)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
db_handler.setFormatter(formatter)
logger.addHandler(db_handler)
return logger
def exexception_hook():
def E_H(exc_type, exc_value, tb):
test=''
while tb:
filename = tb.tb_frame.f_code.co_filename
name = tb.tb_frame.f_code.co_name
line_no = tb.tb_lineno
temp=f"File {filename} line {line_no}, in {name}"
print(temp)
test=test+',\r'+temp
tb = tb.tb_next
temp=f"{exc_type.__name__}, Message: {exc_value}"
print(temp)
test=test+',\r'+temp
logger = error_log()
logger.error(test)
sys.excepthook = E_H
if __name__ == '__main__':
exexception_hook()
result = 10 / 0#引起异常