python创建日志输出不同颜色的日志,按照步骤创建文件夹,代码可以运行

#!/usr/bin/python
# coding=utf8
# 时间 2024/7/27 1:26


#log.py  envConfig.ini文件 存放日志文件夹两个OutPut、log
"""
Common/conf/envConfig.ini:文件的目录文件

envConfig.ini文件内容:
    [log]
    logPath = baseDir/OutPut/log/
   
Common/conf/envConfig.ini:配置文件创建在conf文件目录下 
baseDir:envConfig.ini文件里面的路径
/OutPut/log/:输出的文件路径

"""



import configparser
import os, time, logging, sys

import colorlog as colorlog






class Log:

    def __init__(self, logPath):
        self.logName = os.path.join(logPath, '{0}.log'.format(time.strftime('%Y-%m-%d')))
    #控制台输出log日志
    def consoleLog(self, level, message):
        # 创建一个logger
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)

        # 创建一个handler 用于debug写入日志文件
        debugFile = logging.FileHandler(self.logName, 'a+', encoding='utf-8')
        debugFile.setLevel(logging.DEBUG)

        # 创建一个handler用于输出到控制台
        outPut = logging.StreamHandler()
        outPut.setLevel(logging.DEBUG)

        # 定义handler的输出格式 %(log_color)s%(levelname)s: %(message)s
        # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        formatter = colorlog.ColoredFormatter(
            '%(log_color)s%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            log_colors={
                'DEBUG': 'cyan',
                'INFO': 'green',
                'WARNING': 'red',
                'ERROR': 'yellow',
                'CRITICAL': 'red,bg_white',
            }
        )

        debugFile.setFormatter(formatter)
        outPut.setFormatter(formatter)

        # 给logger添加handler
        logger.addHandler(debugFile)
        logger.addHandler(outPut)

        # 记录日志
        if level == 'info':
            logger.info(message)
        elif level == 'debug':
            logger.debug(message)
        elif level == 'warning':
            logger.warning(message)
        elif level == 'error':
            logger.error(message)

        logger.removeHandler(outPut)
        logger.removeHandler(debugFile)
        debugFile.close()

    def debug(self, message):
        self.consoleLog('debug', message)

    def info(self, message):
        self.consoleLog('info', message)

    def warning(self, message):
        self.consoleLog('warning', message)

    def error(self, message):
        self.consoleLog('error', message)




BASE_DIR = (os.path.dirname(os.path.dirname(__file__)))
print(BASE_DIR)

if sys.platform == "win32":
    ENV_CONF_DIR = os.path.join(BASE_DIR, 'Common/conf/envConfig.ini').replace('/', '\\')
else:
    ENV_CONF_DIR = os.path.join(BASE_DIR, 'Common/conf/envConfig.ini')


def readConfig(configFilePath, field, key):
    readConfigParser = configparser.ConfigParser()
    try:
        readConfigParser.read(configFilePath, encoding='utf-8')
        if sys.platform == "win32":
            result = readConfigParser.get(field, key).replace('baseDir', str(BASE_DIR)).replace('/', '\\')
        else:
            result = readConfigParser.get(field, key).replace('baseDir', str(BASE_DIR))
    except:
        sys.exit(1)
    return result


logPath = readConfig(ENV_CONF_DIR, "log", "logPath")
if __name__ == '__main__':
    Log(logPath).info("FAHDIOAHDO")
    Log(logPath).error("JASODJFAO")

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值