zoukankan      html  css  js  c++  java
  • 精简版logging

    # 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 :
    %(message)s"
        c_fmt = "[%(levelname)s]%(asctime)s %(filename)s.%(funcName)s():line %(lineno)d :
    %(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__))
    

      .

  • 相关阅读:
    火山喷发 计蒜客16862 NOIP模拟赛 概率DP
    洛谷 1429 平面最近点对(加强版) 快排 非点分治或kdtree
    鬼脚图 计蒜客17353 NOIP模拟 归并排序逆序对
    小X的佛光 NOIP模拟赛 倍增LCA 树结构
    小X的质数 NOIP模拟赛 魔改线性筛素数
    Win7Office2010Flash控件无法使用"此演示文稿中一些控件无法激活,可能这些控件未在此计算机中注册"
    【NOILinux】VmWare15使用技巧
    【超链接】导航网站
    C++统计博客园写过的代码行数
    合并多个txt文件到一个
  • 原文地址:https://www.cnblogs.com/SunshineKimi/p/11823729.html
Copyright © 2011-2022 走看看