Python日志输出不同颜色字体并打印到日志文件
# -*- coding: utf-8 -*-
'''
@Time : 2023-04-03 14:57
@Author : AnTi
@File : test.py
'''
import pandas as pd
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 10000)
pd.set_option('display.max_colwidth', 10000)
pd.set_option('display.max_rows', None)
import logging
import colorlog
import os
import time
# 设置相对路径
ProjectPath = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0]
LogsPath = os.path.join('./', 'logs\log_{0}'.format(time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime())))
# 设置控制台打印的颜色
log_colors_config = {
'DEBUG': 'cyan',
'INFO': 'black',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red',
}
class MyLogs:
"""
在其他文件调用方法
1. from . import MyLogs 把这个文件导入
2. self.log = MyLogs() 实例化类
3. self.log.info("想要打印到日志的话") 这个分五个等级
self.log.error("错误日志")
self.log.info('正常日志信息')
......
4. 使用两个格式,格式一打印到控制台,格式二打印到日志(使用格式一打印因为颜色会出现[30m日志[0m)
Python日志输出不同颜色字体并打印到日志文件
"""
def mylog(self, level, msg):
logger = logging.getLogger('GuangDian_API')
logger.setLevel(logging.DEBUG)
formatter = colorlog.ColoredFormatter(
'%(log_color)s[%(asctime)s] [%(name)s] [%(levelname)s]: %(message)s',
log_colors=log_colors_config)
formatter2 = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s]: %(message)s')
sh = logging.StreamHandler() # 输出到控制台
sh.setLevel(logging.DEBUG)
sh.setFormatter(formatter) # 指定格式
fh = logging.FileHandler(LogsPath, encoding="utf-8")
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter2)
logger.addHandler(sh)
logger.addHandler(fh) # 输出到文件
if level == "DEBUG":
logger.debug(msg)
elif level == "INFO":
logger.info(msg)
elif level == "WARNING":
logger.warning(msg)
elif level == "ERROR":
logger.error(msg)
elif level == "CRITICAL":
logger.critical(msg)
logger.removeHandler(sh)
logger.removeHandler(fh)
fh.close() #不关闭会警告
def debug(self, msg):
self.mylog("DEBUG", msg)
def info(self, msg):
self.mylog("INFO", msg)
def warning(self, msg):
self.mylog("WARNING", msg)
def error(self, msg):
self.mylog("ERROR", msg)
def critical(self, msg):
self.mylog("CRITICAL", msg)
if __name__ == '__main__':
log = MyLogs()
log.debug("---测试开始----")
log.info("操作步骤")
log.warning("----测试结束----")
log.error("----测试错误----")