文章

Python 日志

Python 日志

print

colorama 三方模块

1
pip install colorama

可支持的颜色:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 
![image.png1000](https://raw.githubusercontent.com/hacket/ObsidianOSS/master/obsidian/20240313154957.png)

使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import time  
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)  
  
  
_print = 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)  
  
  
if __name__ == '__main__':  
    print_info("info")  
    print_waring("waring")  
    print_error("error")  
  
    print('sss' + colorama.Fore.RED + str('重点') + colorama.Style.RESET_ALL)
![image.png1000](https://raw.githubusercontent.com/hacket/ObsidianOSS/master/obsidian/20240313154854.png)

logging

colorlog 三方模块

1
pip install colorlog

使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import colorlog  # pip install colorlog  
  
# Create a logger object.  
logger = colorlog.getLogger()  
  
# Set the log level to info.  
# 设置输出等级,这里我不进行设置  
logger.setLevel("NOTSET")  
  
# Create a handler for the console log.  
console = colorlog.StreamHandler()  
console.setFormatter(colorlog.ColoredFormatter())  
  
# Add the handler to the logger.  
logger.addHandler(console)  
  
# Send log messages.  
logger.debug("debug")  
logger.info("info")  
logger.warning("warning")  
logger.error("error")  
logger.critical("critical")
![image.png1000](https://raw.githubusercontent.com/hacket/ObsidianOSS/master/obsidian/20240313143847.png)

loguru

GitHub - Delgan/loguru: Python logging made (stupidly) simple

本文由作者按照 CC BY 4.0 进行授权