python logging使用
1 ####################### 2 # 3 # 初始化log 4 # 5 ###################### 6 log_file = "./serverchecklog/servertest%s.log"%time.strftime("%Y%m%d%H%M%S") 7 logging.basicConfig(level=logging.DEBUG, 8 format='[%(asctime)s] %(levelname)-10s %(message)s', 9 filename=log_file) 10 console = logging.StreamHandler() 11 console.setLevel(logging.INFO) 12 formatter = logging.Formatter('[%(asctime)s] %(levelname)-10s %(message)s') 13 console.setFormatter(formatter) 14 logging.getLogger('').addHandler(console)
# 在具体代码中可以直接使用
logging.info(xxx)
logging.error(xxx)
对于非正常情况退出的记录:
try: check_appserver() except Exception, e: exception_log = "./appserverchecklog/exception_%s.log"%time.strftime("%Y%m%d%H%M%S") f=open(exception_log,'a') f.write("[%s] got exceptions\n\n"%time.strftime("%Y-%m-%d %H:%M:%S")) traceback.print_exc(file=f) f.flush() f.close() #TODO 缺一个发送提醒的功能
另外也可以直接用logging来写
try:
xxxx
except Exception, e:
logger.error('Failed to execute xxxx', exc_info = True)