python logging模块日志回滚RotatingFileHandler

本文深入探讨了Python中日志模块的使用方法,包括如何配置不同级别的日志输出,如Error、Info、Warning和Debug,以及如何将日志信息输出到控制台和文件。通过实例演示了如何创建一个日志记录器,设置日志格式,以及如何处理日志文件的滚动。此外,还介绍了如何根据不同的日志级别将日志信息存储在不同的文件夹下。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

def logger(appname,rootstdout=True):

    log_fmt= "%(asctime)s --%(name)s [%(levelname)s]:\n%(message)s"
    c_fmt="%(asctime)s --%(name)s [%(levelname)s]:\n%(message)s"
    date_format = "%Y-%m-%d %H:%M:%S %a"
    #设置Console输出level
    logging.basicConfig(level=logging.DEBUG,
                            format=c_fmt,
                            datefmt=date_format,

                            )

    list_level=["Error","Info","Warning","Debug"]
    stamp = time.strftime("%Y%m%d", time.localtime())+".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(root)

    for k,v in f_dict.items():
            handler=logging.handlers.RotatingFileHandler(filename=v, maxBytes=1024*1024*50, backupCount=5,encoding="utf-8",delay=False)
            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)
    logger.propagate = rootstdout
    return  logger

if __name__ == "__main__":
        logger=logger("root",rootstdout=True)
        while True:
            time.sleep(0.01)
            logger.info("file test",exc_info=True)
            logger.debug("bebug test")
            logger.error("error test")
            logger.warning("warning test")

C:\Python37\python.exe C:/Users/Administrator/PycharmProjects/Supro/src/rotating_rewrite.py
2019-03-21 23:32:40 Thu --SshTest.class [INFO]:
file test
NoneType: None
2019-03-21 23:32:40 Thu --SshTest.class [DEBUG]:
bebug test
2019-03-21 23:32:40 Thu --SshTest.class [ERROR]:
error test
2019-03-21 23:32:40 Thu --SshTest.class [WARNING]:
warning test
2019-03-21 23:32:40 Thu --SshTest.class [INFO]:
file test
NoneType: None
2019-03-21 23:32:40 Thu --SshTest.class [DEBUG]:

 

转载于:https://www.cnblogs.com/SunshineKimi/p/10540178.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值