新增Log类,输出日志到文件
import os
import logging
PATH = lambda p: os.path.abspath(
os.path.join(os.path.dirname(__file__), p)
)
class Log(object):
"""
log类
"""
def __init__(self):
global logger, logPath, resultPath
resultPath = PATH('../logs')
# logPath = os.path.join(resultPath, time.strftime('%Y%m%d%H%M%S', time.localtime()))
# if not os.path.exists(logPath):
# os.mkdir(logPath)
if not os.path.exists(resultPath):
os.mkdir(resultPath)
# 创建logger,设置日志等级
# DEBUG INFO WARNING ERROR CRITICAL等级依次递增
self.logger = logging.getLogger()
self.logger.setLevel(logging.INFO)
# 创建handler,输出日志到文件
# fh = logging.FileHandler(os.path.join(logPath, 'outPut.log'), encoding='utf-8', mode='a')
fh = logging.FileHandler(os.path.join(resultPath, 'outPut.log'), encoding='utf-8', mode='a')
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
# 创建handler,输出日志到terminal
ch = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
# if str(self.logger.handlers) == '[]':
if not self.logger.handlers:
self.logger.addHandler(fh)
self.logger.addHandler(ch)
else:
self.logger.info('log handler已存在')
ch.close()
fh.close()
def getLogger(self):
"""
get logger
:return:
"""
return self.logger
if __name__ == '__main__':
my_log = Log()
my_log.logger.info('test info')