码迷,mamicode.com
首页 > 其他好文 > 详细

精简版logging

时间:2019-11-09 00:45:45      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:encoding   print   ISE   scheduler   expect   sdi   fun   else   rate   

# coding=utf-8
import logging
import time
import os
import logging.handlers
import re


def logger(schedule_name, console_print=True, logging_level=None,console_debug_level=logging.INFO):
    """
    :param schedule_name: the log scheduler  name 
    :param console_print: if True console print log ,False not .
    :param logging_level: file logging generate levels support: ["DEBUG","INFO","WARNING","ERROR"].
    :param console_debug_level: it can be str also ,for exp: console_debug_level="INFO",default set logging.INFO.
    :return: logging handlers
    """
    log_fmt = "[%(levelname)s]%(asctime)s line %(lineno)d :\n%(message)s"
    c_fmt = "[%(levelname)s]%(asctime)s %(filename)s.%(funcName)s():line %(lineno)d :\n%(message)s"
    date_format = "%Y-%m-%d %H:%M:%S %a"
    # 设置控制台输出level
    logging.basicConfig(level=console_debug_level,
                        format=c_fmt,
                        datefmt=date_format,

                        )
    levels = []
    if isinstance(logging_level, list):
        for  level in logging_level:
            if level in ["DEBUG","INFO","WARNING","ERROR"]:
                levels.append(level)
        if levels:
            stamp = "dailylog.log"
            logsdir = os.path.join(os.getcwd(), "logs")
            if os.path.exists(logsdir):
                for p in levels:
                    if os.path.exists(os.path.join(logsdir, p)):
                        pass
                    else:
                        os.mkdir(os.path.join(logsdir, p))
            else:
                os.mkdir(logsdir)
                for p in levels:
                    os.mkdir(os.path.join(logsdir, p))

            logging_level_path = {}
            for i in levels:
                filename = os.path.join(logsdir, i, stamp)
                logging_level_path[i] = filename
            logger = logging.getLogger(schedule_name)
            print(logging_level_path)
            for k, v in logging_level_path.items():
                handler = logging.handlers.TimedRotatingFileHandler(filename=v, when=‘MIDNIGHT‘, interval=1,
                                                                    backupCount=4,encoding="utf-8")
                handler.suffix = "%Y-%m-%d.log"
                handler.extMatch = r"^\d{4}-\d{2}-\d{2}.log$"
                handler.extMatch = re.compile(handler.extMatch)
                h_fmt = logging.Formatter(log_fmt)
                handler.setFormatter(h_fmt)
                if k in ["DEBUG","INFO","WARNING","ERROR"]:
                   handler.setLevel(k)
                logger.addHandler(handler)
            logger.propagate = console_print
            return logger
        else:
            raise TypeError(‘logging_level support in:["DEBUG","INFO","WARNING","ERROR"]‘)
    else:
        raise NameError("logging_level expect list but get %s"%(type(logging_level).__name__))

  .

精简版logging

标签:encoding   print   ISE   scheduler   expect   sdi   fun   else   rate   

原文地址:https://www.cnblogs.com/SunshineKimi/p/11823729.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!