flask 服务器,后台打印日志,如果直接 使用
TimedRotatingFileHandler ,基本上就是移动数据,而不是真正意义上按日期打印日志文件,这里使用改造的方法打印日志,已测试通过
import time
import logging
import os
import socket
hostname = socket.gethostname()
# date = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M')
current_directory = os.path.dirname(os.path.abspath(__file__))
root_path = os.path.abspath(os.path.dirname(current_directory) + os.path.sep + ".")
project_name = (root_path.split(os.path.sep))[-1]
def get_current_time():
# current_time = time.strftime('%Y-%m-%d-%H-%M', time.localtime(time.time())) # 返回当前时间
current_time = time.strftime('%Y-%m-%d-%H', time.localtime(time.time())) # 返回当前时间
return current_time
class Logger(object):
level_relations = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL
} # 日志级别关系映射
count = 0
def __init__(self, fmt='%(message)s'):
self.current_time = get_current_time()
filename = str(root_path) + '/logs/tr/track' + "-" + get_current_time() + '.log'
self.logger = logging.getLogger(filename)
self.format_str = logging.Formatter(fmt) # 设置日志格式
self.create_handler()
Logger.count += 1
def create_handler(self):
self.current_time = get_current_time()
filename = str(root_path) + '/logs/tr/track' + "-" + get_current_time() + '.log'
self.logger = logging.getLogger(filename)
self.logger.setLevel(logging.INFO) # 设置日志级别
sh = logging.StreamHandler() # 往屏幕上输出
sh.setFormatter(self.format_str) # 设置屏幕上显示的格式
th = logging.FileHandler(filename=filename, encoding='utf-8')
th.setFormatter(self.format_str) # 设置文件里写入的格式
self.logger.addHandler(sh) # 把对象加到logger里
self.logger.addHandler(th)
def info(self, msg):
current_time = get_current_time()
if self.current_time != current_time:
self.create_handler()
self.logger.info(msg)
# self.logger.removeHandler(self.logger.handlers)
# cls.log.info(msg)
print("有{}个日志打印类对象".format(Logger.count))
return
def warning(self, msg):
current_time = get_current_time()
if self.current_time != current_time:
self.create_handler()
self.logger.warning(msg)
return
def error(self, msg):
current_time = get_current_time()
if self.current_time != current_time:
self.create_handler()
self.logger.error(msg)
return
# 查看系统类型
# platform_ = platform.system()
# if platform_ == "Windows":
# log_file_path = str(root_path) + '/logs/' + project_name + "-" + date + '.log'
# else:
# log_file_path = '/home/logs/' + hostname + '.log'
if __name__ == '__main__':
log = Logger()
log.logger.debug('debug')
log.logger.info('info')
log.logger.warning('警告')
log.logger.error('报错')
log.logger.critical('严重')
Logger().logger.error('error')