#!/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")
python创建日志输出不同颜色的日志,按照步骤创建文件夹,代码可以运行
最新推荐文章于 2024-08-08 11:54:17 发布