工作上,基于python3开发了一些功能,上线前需要添加日志功能,之前的日志配置可以输出指定规则的日志,但缺少根据时间,自动拆分日志和删除日志,这在使用和运行维护上,很不有好。
经过一番搜索、学习和测试,基于自带的logger,终于配置出自己满意的日志配置,它根据设置自动拆分日志大小,删除多余日志,详细如下:
#coding:utf-8
import logging,os,sys
import logging.handlers
def script_path():
path = os.path.realpath(sys.argv[0])
if os.path.isfile(path):
path = os.path.dirname(path)
return os.path.abspath(path)
message_format = '%(asctime)s %(levelname)s %(pathname)s(line:%(lineno)d) %(message)s'
date_format = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(level=logging.DEBUG,format=message_format)
log = logging.getLogger('log')
log_path = os.path.join(script_path(),'logs')
if not os.path.exists(log_path):
os.makedirs(log_path)
log_file = os.path.join(log_path,'my.log')
'''
when 间隔时间拆分文件:
“S”: Seconds
“M”: Minutes
“H”: Hours
“D”: Days
“W”: Week day (0=Monday)
“midnight”: Roll over at midnight
interval:
等待多少个单位when的时间后,新建日志文件
backupCount:
保存多少个日志文件
'''
file = logging.handlers.TimedRotatingFileHandler(log_file,when="S",interval=1,backupCount=2,encoding='utf-8')
file.setFormatter(logging.Formatter(message_format))
log.addHandler(file)
log.info("加油")
logger.error("Thread Error",exc_info=True)