flask 打印日志 按日期分割

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')

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值