代码如下:
def analysis():
logging.basicConfig( filename='exception1.log', filemode='a', level=logging.ERROR, format= '%(asctime)s - %(levelname)s - %(message)s')
logging.FileHandler('/home/aim/top/exception1.log')
try:
some_func()
except Exception as e:
logging.error("Exception occurred", exc_info=True)
cur.execute("UPDATE column SET STATUS='FAILED'")
mydb.commit()
else:
cur.execute("UPDATE column SET STATUS='FINISHED'")
mydb.commit()
cur.close()
def analysis1():
logging.basicConfig( filename='exception2.log', filemode='a', level=logging.ERROR, format= '%(asctime)s - %(levelname)s - %(message)s')
logging.FileHandler('/home/aim/top-dev/exception1.log')
try:
some_func()
except Exception as e:
logging.error("Exception occurred", exc_info=True)
cur.execute("UPDATE column SET STATUS='FAILED'")
mydb.commit()
else:
cur.execute("UPDATE column SET STATUS='FINISHED'")
mydb.commit()
cur.close()
def process():
if req_type==1:
analysis()
if req_type==2:
analysis1()
运行并获取异常信息后,将正确执行mysql命令,将在两个不同目录中创建日志文件,但在两个文件中的任何一个中均未写入错误。它们是空白。我在做什么错..
答案 0 :(得分:0)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
def setup_logger(name, log_file, level=logging.ERROR):
"""To setup as many loggers as you want"""
handler = logging.FileHandler(log_file, 'a')
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
return logger
在每个函数内部调用此函数时,该函数将使用不同的名称为两个函数创建两个单独的日志记录。
def analysis():
logging.basicConfig( filename='logfile.log', filemode='a', level=logging.ERROR, format= '%(asctime)s - %(levelname)s - %(message)s')
logging.FileHandler('/logfile.log')
try:
some_func()
except Exception as e:
first_logger = setup_logger('first_logger', '/logfile.log')
first_logger.error("Exception occurred", exc_info=True)
cur.execute("UPDATE column SET STATUS='FAILED'")
mydb.commit()
else:
cur.execute("UPDATE column SET STATUS='FINISHED'")
mydb.commit()
cur.close()
def analysis1():
logging.basicConfig( filename='logfile2.log', filemode='a', level=logging.ERROR, format= '%(asctime)s - %(levelname)s - %(message)s')
logging.FileHandler('/logfile2.log')
try:
some_func()
except Exception as e:
seccond_logger = setup_logger('second_logger', '/logfile2.log')
second_logger.error("Exception occurred", exc_info=True)
cur.execute("UPDATE column SET STATUS='FAILED'")
mydb.commit()
else:
cur.execute("UPDATE column SET STATUS='FINISHED'")
mydb.commit()
cur.close()
def process():
if req_type==1:
analysis()
if req_type==2:
analysis1()
由于仅为这两个功能创建了一个日志记录实例,所以它不起作用。