import logging
import logging.handlers
import time
class GetLogToTwoFile: # 根据日志等级写到对应等级的日志文件中
logger = None
@classmethod
def get_log_to_file(self, log_path):
if self.logger is None:
self.logger = logging.getLogger()
self.logger.setLevel(logging.INFO)
fm = "%(asctime)s %(levelname)s %(filename)s %(funcName)s:lines-%(lineno)d ,message: %(message)s"
fmt = logging.Formatter(fm)
# debug级以上的信息输出到debug文件
debug = logging.FileHandler(filename="{}server-debug.log".format(log_path), mode="w", encoding="utf-8")
debug.setLevel(logging.DEBUG)
debug.setFormatter(fmt)
self.logger.addHandler(debug)
# info级以上的信息输出到info文件
info = logging.FileHandler(filename="{}server-info.log".format(log_path), mode="w", encoding="utf-8")
info.setLevel(logging.INFO)
info.setFormatter(fmt)
self.logger.addHandler(info)
# warn级以上的信息输出到warn文件
warn = logging.FileHandler(filename="{}server-warn.log".format(log_path), mode="w", encoding="utf-8")
warn.setLevel(logging.WARN)
warn.setFormatter(fmt)
self.logger.addHandler(warn)
# error级以上的信息输出到error文件
error = logging.FileHandler(filename="{}server-error.log".format(log_path), mode="w", encoding="utf-8")
error.setLevel(logging.ERROR)
error.setFormatter(fmt)
self.logger.addHandler(error)
# critical级以上的信息输出到critical文件
critical = logging.FileHandler(filename="{}server-critical.log".format(log_path), mode="w",
encoding="utf-8")
critical.setLevel(logging.CRITICAL)
critical.setFormatter(fmt)
self.logger.addHandler(critical)
return self.logger
if __name__ == '__main__':
start_time = time.time()
log = GetLogToTwoFile().get_log_to_file("../log/")
while True:
if time.time() > (start_time + 5): # 5秒增加一条记录
log.info("info {}".format(time.time()))
log.error("error log in file:debug, info, warn, error")
start_time = time.time() + 5
日志分级写入日志文件
最新推荐文章于 2022-12-30 07:30:00 发布