• python logging模块日志回滚TimedRotatingFileHandler


    # coding=utf-8
    import logging
    import time
    import os
    import logging.handlers
    import re
    def logger(appname,rootstdout=True):
    
        log_fmt= "%(asctime)s --%(name)s [%(levelname)s]:\n%(message)s"
        c_fmt="%(asctime)s --%(name)s %(filename)s.%(funcName)s():%(lineno)d [%(levelname)s]:\n%(message)s"
        date_format = "%Y-%m-%d %H:%M:%S %a"
        # 设置控制台输出level
        logging.basicConfig(level=logging.DEBUG,
                                format=c_fmt,
                                datefmt=date_format,
    
                                )
    
        list_level=["Error","Info","Warning","Debug"]
        stamp = "dailylog.log"
        logsdir=os.path.join(os.getcwd(),"logs")
        if os.path.exists(logsdir):
            for p in list_level:
                if os.path.exists(os.path.join(logsdir,p)):
                    pass
                else:
                    os.mkdir(os.path.join(logsdir,p))
        else:
            os.mkdir(logsdir)
            list_level=["Error","Info","Warning","Debug"]
            for p in list_level:
                 print(os.path.join(logsdir,p))
                 os.mkdir(os.path.join(logsdir,p))
    
        f_dict={}
        for i in list_level:
            filename=os.path.join(logsdir,i,stamp)
            f_dict[i]=filename
        logger= logging.getLogger(appname)
    
        for k,v in f_dict.items():
                handler=logging.handlers.TimedRotatingFileHandler(filename=v,when='MIDNIGHT', interval=1, backupCount=4)
                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==list_level[0]:
                    handler.setLevel(logging.ERROR)
                elif k==list_level[1]:
                    handler.setLevel(logging.INFO)
                elif k== list_level[2]:
                     handler.setLevel(logging.WARNING)
                else :
                     handler.setLevel(logging.DEBUG)
                logger.addHandler(handler)
       #是否控制台输出stdout logger.propagate
    = rootstdout return logger
    if __name__ == "__main__":
    logger=logger("root",rootstdout=True)

    time.sleep(0.01)
    try:
    assert 1==2
    except Exception as e:
            # exc_info用来抛出异常到控制台或日志文件
    logger.info("ddd",exc_info=True)

    logger.debug("bebug test")
    logger.error("error test")
    logger.warning("warning test")

    2019-03-21 23:27:52 Thu --root timeromat.py.<module>():67 [INFO]:
    ddd
    Traceback (most recent call last):
    File "C:/Users/Administrator/PycharmProjects/Supro/src/timeromat.py", line 65, in <module>
    assert 1==2
    AssertionError
    2019-03-21 23:27:52 Thu --root timeromat.py.<module>():69 [DEBUG]:
    bebug test
    2019-03-21 23:27:52 Thu --root timeromat.py.<module>():70 [ERROR]:
    error test
    2019-03-21 23:27:52 Thu --root timeromat.py.<module>():71 [WARNING]:
    warning test

    Process finished with exit code 0

  • 相关阅读:
    VS2022修改默认字符集
    Unity 实现简单力场效果
    网页前端(Html)video播放m3u8(HLS)&Vue使用video.js播放m3u8
    ORACLE WITH AS 用法
    utf8和utf8mb4的区别
    mysql锁表原因及解决方法
    C#实现Stream、string、byte[]、文件、Bitmap、二进制之间的转换
    Spring循环依赖。为什么是三级缓存,二级不行吗?
    微信小程序 wx:for 遍历 Map集合
    Rust问题解决合集
  • 原文地址:https://www.cnblogs.com/SunshineKimi/p/10540171.html
Copyright © 2020-2023  润新知