python 日志+终端颜色区分+按照日期分隔(logging+coloredlogs+TimedRotatingFileHandler)

# -*- coding: utf-8 -*- 
"""
Author: 田野
Data: 2019-07-04 11:17
Introduction:
"""
import logging
import os
from logging.handlers import TimedRotatingFileHandler

import coloredlogs
coloredlogs.DEFAULT_FIELD_STYLES = {'asctime': {'color': 'green'}, 'hostname': {'color': 'magenta'}, 'levelname': {'color': 'green', 'bold': True}, 'request_id':{'color': 'yellow'}, 'name': {'color': 'blue'}, 'programname': {'color': 'cyan'}, 'threadName': {'color': 'yellow'}}

class Log:
    __instances = {}
    @classmethod
    def getLogger(cls, name='sys'):
        if name not in cls.__instances:
            BASE_DIR = os.path.dirname(os.path.abspath(__file__))
            log_dir = 'logs'
            if not log_dir.startswith('/'):
                log_dir = os.path.join(BASE_DIR, log_dir)

            if not os.path.isdir(log_dir):
                os.makedirs(log_dir, mode=0o755)

            log_file = os.path.join(log_dir, "app.log")
            logger = logging.getLogger(name)
            fmt = '%(asctime)s [%(levelname)s] [%(name)s] %(filename)s[line:%(lineno)d] [%(threadName)s] %(message)s'
            formater = logging.Formatter(fmt)
            # if config.isLocal():
            ch = logging.StreamHandler()
            ch.setLevel(Log.__getLogLevel())
            ch.setFormatter(formater)
            logger.addHandler(ch)

            coloredlogs.install(fmt=fmt, level=Log.__getLogLevel(), logger=logger)

            fh = TimedRotatingFileHandler(log_file, when='M', interval=1, backupCount=7, encoding='utf-8')
            fh.setLevel(Log.__getLogLevel())
            fh.setFormatter(formater)
            logger.setLevel(Log.__getLogLevel())
            logger.addHandler(fh)
            cls.__instances[name] = logger
        return cls.__instances[name]

    @staticmethod
    def __getLogLevel():
        return logging.DEBUG

if __name__ == '__main__':
    Log.getLogger('log测试title').error('log测试数据')

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值