Python command line or console or log output with color
python console with color output
A few years ago, I wrote a project, and I liked the bells and whistles. I saw other people's output to the console with color, so I wanted it too.
So I don't know where to find the information, it is a patchwork of color code blocks.
It was fine then, and it's fine now. But once it is migrated to other platform devices or called externally, problems will arise.
Early code with color output is as follows:
msg = "我是一个有颜色的字体!"
print('\033[0;33m{}'.format(msg))
The output style is as follows:
Friends who are interested in this method can search for relevant information, but I suggest that if you are really interested, you can read on!
Color exception output example
Use the previous color code to piece together the output. When calling it through the command line, it is found that the color code is directly output instead of the font with color.
Let’s explain it a little bit here.
Setting the color of output text in the terminal can be accomplished using ANSI escape sequences. However, the default console in Windows does not always support ANSI escape sequences and may not display colors correctly.
If you run this code on Windows and the console doesn't display colors correctly, you can install a third-party library colorama
to fix this. colorama
library is a cross-platform Python module that makes it easier to display ANSI escape sequences in the terminal.
Focus on: cross-platform! ! ! (I have invited the boss to do the test. Windows and Mac are perfect!)
Use of colorma module
Install
pip install colorama
basic use
import colorama
from colorama import Fore, Style
# 初始化 colorama 库
colorama.init()
def print_info(msg):
print(Fore.GREEN + msg + Style.RESET_ALL)
By importing colorama
the library and using Fore.GREEN
to set the foreground color of the text to green, Style.RESET_ALL
which is used to reset the style of the text, the color can be displayed correctly on the Windows console.
In order to display colors properly, make sure your console supports ANSI escape sequences or the library is installed colorama
. If you are using another operating system or terminal emulator, you can usually use ANSI escape sequences directly to set the color of the output.
Encapsulate your own color output
import colorama
# 初始化 colorama 库
colorama.init()
def print_info(msg: str):
print(colorama.Fore.GREEN + str(msg) + colorama.Style.RESET_ALL)
def print_waring(msg: str):
print(colorama.Fore.YELLOW + str(msg) + colorama.Style.RESET_ALL)
def print_error(msg):
print(colorama.Fore.RED + str(msg) + colorama.Style.RESET_ALL)
In this way, you can call whichever color you want to output.
If you still want to use print to output, you can use the following code to fix a color.
import time
import colorama
_print = print
def print(msg:str):
_print(colorama.Fore.GREEN + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + " [mwjApiTest] " + str(msg) + colorama.Style.RESET_ALL)
print("我打印一段文字")
The effect is as follows
Supported colors:
BLACK
RED
GREEN
YELLOW
BLUE
MAGENTA
CYAN
WHITE
RESET
# These are fairly well supported, but not part of the standard.
LIGHTBLACK_EX
LIGHTRED_EX
LIGHTGREEN_EX
LIGHTYELLOW_EX
LIGHTBLUE_EX
LIGHTMAGENTA_EX
LIGHTCYAN_EX
LIGHTWHITE_EX
Corresponding output effect
Colored log output
Use colorlog
library
colorlog
is a handy Python logging library that helps add colors and styles to the console to beautify the log output. Here is colorlog
an example of using the library:
- Install
colorlog
library
pip install colorlog
- import
colorlog
import colorlog
- Create
colorlog
a logger for :
logger = colorlog.getLogger()
- Add console handler:
console_handler = colorlog.StreamHandler()
logger.addHandler(console_handler)
#设置输出等级,这里我不进行设置
logger.setLevel("NOTSET")
- Set the logging format:
log_format = '%(log_color)s%(levelname)s:%(message)s'
console_format = colorlog.ColoredFormatter(log_format)
console_handler.setFormatter(console_format)
- Print log:
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')
Output style:
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-zGkUMLtS-1692690396784) (images/image-20230730162030148.png)]
Through colorlog
, variables can be used log_color
to apply colors and styles to log levels ( levelname
) and messages ( message
). The logging format can be customized as needed.
Note that on Windows, to display colors properly, needs to be colorlog
initialized colorama
to handle ANSI escape sequences before using :
import colorama
colorama.init()
The above is colorlog
a basic usage example of the library. You can use more advanced log functions according to your own needs, such as adding file processors, setting log levels, etc. For detailed usage, please refer colorlog
to the documentation: https://pypi.org/project/colorlog/
Hands-On: Writing a Singleton Logger with Colored Output
This code can directly replace your previous log code without color output.
class Logger:
__instance = None
# 往屏幕上输出
screen_output = logging.StreamHandler()
def __new__(cls, path=None, level='DEBUG', RotatingFileHandler: BaseRotatingHandler = None):
'''
单列模式
:param path: 报告的路径
:param level: 日志的等级常用,INFO,DEBUG,WARNING,ERROR
:param RotatingFileHandler:
'''
if not cls.__instance:
colorama.init()
cls.__instance = super().__new__(cls)
log = logging.getLogger("mwjApiTest")
# 设置日志级别
log.setLevel(level)
cls.__instance.log = log
if path:
if not os.path.isdir(path):
os.mkdir(path)
if RotatingFileHandler and isinstance(RotatingFileHandler, BaseRotatingHandler):
fh = RotatingFileHandler
else:
# # 往文件里写入#指定间隔时间自动生成文件的处理器
fh = TimedRotatingFileHandler(os.path.join(path, 'mwjApiTest.log'), when='D', interval=1,
backupCount=7, encoding='utf-8')
fh.setLevel(level)
cls.__instance.log.addHandler(fh)
# 定义handler的输出格式
formatter = logging.Formatter("%(levelname)-8s%(asctime)s%(name)s:%(filename)s:%(lineno)d %(message)s")
fh.setFormatter(formatter)
return cls.__instance
def set_level(self, level):
"""设置日志输出的等级"""
self.log.setLevel(level)
#### 设置输出的颜色
def fontColor(self):
# 不同的日志输出不同的颜色
formatter = colorlog.ColoredFormatter(
'%(log_color)s[%(asctime)s] [%(name)s] [%(levelname)s]: %(message)s',
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red,bg_white',
},
)
self.screen_output.setFormatter(formatter)
self.log.addHandler(self.screen_output)
test
aa = Logger()
aa.debug('This is a debug message')
aa.info('This is an info message')
aa.warning('This is a warning message')
aa.error('This is an error message')
aa.critical('This is a critical message')
Finish!
If you want me to update anything in the future, you can leave a message in the background~
Public account: Meng Wuji’s road to test development