python log

记录下python中的log使用demo,可以向文件与控制台同时输出各种信息

log_rule.py

import logging
import os
import sys
from logging.handlers import TimedRotatingFileHandler
from logging.handlers import RotatingFileHandler
import platform
PLATFROM = platform.platform()
if PLATFROM.startswith("Windows"):
    from concurrent_log_handler import ConcurrentRotatingFileHandler


class LogRule(logging.Logger):
    """log rule for all"""
    def __init__(self, name, level="DEBUG"):
        self.name = name
        if not os.path.exists(os.path.dirname(self.name)):
            os.makedirs(os.path.dirname(self.name))
        self.level = level
        logging.Logger.__init__(self, self.name, level=self.level)
        self.__streamHandler__(self.level)
        self.__filesHandler__(self.level)

    def __streamHandler__(self, level=None):
        """向标准输出写log"""
        # 不填入 sys.stdout 则会向 sys.stderr 输出
        handler = logging.StreamHandler(sys.stdout)
        formatter = logging.Formatter('%(asctime)s %(filename)s[line:%('
                                      'lineno)d] %(levelname)s %(message)s')
        handler.setFormatter(formatter)
        handler.setLevel(level)
        self.addHandler(handler)

    def __filesHandler__(self, level=None):
        """文件log"""
        # suffix是指日志文件名的后缀,suffix中通常带有格式化的时间字符串,
        # filename和suffix由“.”连接构成文件名
        # (例如:filename=“runtime”, suffix=“%Y-%m-%d.log”,
        # 生成的文件名为runtime.2015-07-06.log)
        # handler = TimedRotatingFileHandler(self.name, when='D', interval=1,
        #                                    backupCount=5)
        """
        设置log日志文件32M进行拆分,并保存历史文件100个
        """
        handler = RotatingFileHandler(self.name, mode='a',  maxBytes=32*1024*1024,
                                           backupCount=100)
        handler.suffix = '%Y-%m-%d'
        if PLATFROM.startswith("Windows"):
            handler = ConcurrentRotatingFileHandler(self.name, mode='a', maxBytes=32*1024*1024,encoding="utf8",backupCount=100)
        handler.setLevel(level)
        formatter = logging.Formatter('%(asctime)s %(filename)s[line:%('
                                      'lineno)d] %(levelname)s %(message)s')
        handler.setFormatter(formatter)
        self.addHandler(handler)


if __name__ == '__main__':
    mylog1 = LogRule("/tmp/logs/test1.log")
    mylog2 = LogRule("/tmp/logs/test2.log")
    mylog1.debug("tet1")
    mylog2.debug("tet2")

使用

from log_rule import LogRule
log = LogRule('./charge_test.log')
log.info('test')
log.debug('debug')

 

posted @ 2021-12-08 13:45  风,又奈何  阅读(22)  评论(0编辑  收藏  举报