Python3之logging按天分割+控制台根据日志级别颜色区分

调用案例,不多说上代码,相关说明都在注释了

import time
import LoggerConfig
import logging

#定义日志文件名称和日志级别
loggerall = logging.getLogger('logs/all.log')
LoggerConfig.configure_logging(logging.DEBUG, 'logs/all.log', 'midnight', 10, 2)
loggererror = logging.getLogger('logs/error.log')
LoggerConfig.configure_logging(logging.ERROR, 'logs/error.log', 'midnight', 10, 2)

cnt=0
while True:
    cnt=cnt+1
    loggerall.info('loggerall info %d',cnt)
    loggerall.debug('loggerall debug %d',cnt)
    loggerall.warning('loggerall warning %d',cnt)
    loggerall.error('loggerall error %d',cnt)

    loggererror.info('info %d', cnt)
    loggererror.debug('debug %d', cnt)
    loggererror.warning('warning %d', cnt)
    loggererror.error('error %d', cnt)

    time.sleep(1)

logging配置:LoggerConfig.py

import logging
from logging import handlers
import time
import os
'''
        # interval是时间间隔(wher=midnight时interval不生效),backupCount是备份文件的个数,如果超过这个个数,就会自动删除,when是间隔的时间单位,单位有以下几种:
        # S 秒
        # M 分
        # H 小时、
        # D 天、
        # W 每星期(interval==0时代表星期一)
        # midnight 每天凌晨
        默认DEUG级别,文件路径/logs/logfile.log,每天凌晨按天分割日志文件,保留100个日志文件,记录间隔默认1,when=H intervel=3表示3小时分割
'''
def configure_logging(level,filename,when,backupCount,interval):
    #创建默认路径,设置默认参数
    if (not os.access('logs/', os.R_OK)):
        os.mkdir('logs')

    if level==None:
        when=logging.DEBUG
    if filename==None:
        filename='/logs/logfile.log'
    if when==None:
        when='midnight'
    if backupCount==None:
        backupCount=100
    if interval==None:
        interval=1

    # add 'levelname_c' attribute to log resords
    orig_record_factory = logging.getLogRecordFactory()
    log_colors = {
        logging.DEBUG:     "\033[1;34m",  # blue
        logging.INFO:      "\033[1;32m",  # green
        logging.WARNING:   "\033[1;35m",  # magenta
        logging.ERROR:     "\033[1;31m",  # red
        logging.CRITICAL:  "\033[1;41m",  # red reverted
    }
    def record_factory(*args, **kwargs):
        record = orig_record_factory(*args, **kwargs)
        record.levelname_c = "{}{}{}".format(
            log_colors[record.levelno], record.levelname, "\033[0m")
        return record

    logging.setLogRecordFactory(record_factory)

    # now each log record object would contain 'levelname_c' attribute
    # and you can use this attribute when configuring logging using your favorite
    # method.
    # for demo purposes I configure stderr log right here

    #根据需要可设置文件和控制台不同的formatter格式
    formatter_c = logging.Formatter("[%(asctime)s]-[%(module)s]-[line:%(lineno)d]-[%(thread)d]-[%(threadName)s]-%(levelname_c)s: %(message)s")
    format_str = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')  # 设置日志格式

    stderr_handler = logging.StreamHandler()
    stderr_handler.setLevel(level)
    stderr_handler.setFormatter(formatter_c)
    time_handler = handlers.TimedRotatingFileHandler(filename=filename, when=when, backupCount=backupCount,interval=interval,
                                           encoding='utf-8')  # 往文件里写入#指定间隔时间自动生成文件的处理器
    time_handler.setLevel(level)
    time_handler.setFormatter(format_str)  # 设置文件里写入的格式
    root_logger = logging.getLogger(filename)
    root_logger.setLevel(level)
    root_logger.addHandler(stderr_handler) # 把对象加到logger里
    root_logger.addHandler(time_handler) # 把对象加到logger里


def main():
    logger = logging.getLogger('logs/filename1.log')
    configure_logging(logging.DEBUG,'logs/filename1.log','S',3)
    while True:
        logger.debug("debug  %s",'aaaaaaaaa')
        logger.info("info ")
        logger.critical("something unusual happened")
        logger.warning('war')
        time.sleep(1)

if __name__ == '__main__':
    main()

补充说明Formatter参数,参考python中formatter的用法_python中logging模块的用法

%(name)s
Logger的名字
%(levelno)s
数字形式的日志级别
%(levelname)s
文本形式的日志级别
%(pathname)s
调用日志输出函数的模块的完整路径名,可能没有
%(filename)s
调用日志输出函数的模块的文件名
%(module)s
调用日志输出函数的模块名
%(funcName)s
调用日志输出函数的函数名
%(lineno)d
调用日志输出函数的语句所在的代码行
%(created)f
当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d
输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s
字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d
线程ID。可能没有
%(threadName)s
线程名。可能没有
%(process)d
进程ID。可能没有
%(message)s

用户输出的消息

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值