1

Python3 彩色日志包

 3 years ago
source link: https://segmentfault.com/a/1190000040044926
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python3 彩色日志包

发布于 31 分钟前
pip install colorful-logger

可以直接使用默认的logger实例输出日志,默认的日志等级是warning

from colorful_logger.logger import logger

logger.debug("This is a debug message.")
logger.info("This is a info message.")
logger.warning("This is a warning message.")
logger.error("This is a error message.")
logger.fatal("This is a fatal message.")

default logger

也可以自定义日志等级,保存日志到文件:

import logging
from colorful_logger.logger import get_logger

# name 参数没有什么用,不需要传此参数,因为当前的日志不输出 name 字段
logger = get_logger(name="logger", level=logging.DEBUG, file_path="./test.log")

logger.debug("This is a debug message.")
logger.info("This is a info message.")
logger.warning("This is a warning message.")
logger.error("This is a error message.")
logger.fatal("This is a fatal message.")

custom logger

日志文件./test.log内容

[DEBUG] 2021-05-21 15:08:42 test.py:8 - This is a debug message.
[INFO] 2021-05-21 15:08:42 test.py:9 - This is a info message.
[WARNING] 2021-05-21 15:08:42 test.py:10 - This is a warning message.
[ERROR] 2021-05-21 15:08:42 test.py:11 - This is a error message.
[CRITICAL] 2021-05-21 15:08:42 test.py:12 - This is a fatal message.

输出到文件的日志没有使用彩色格式,因为我个人觉得,保存到文件中的日志没有必要是彩色的。

FATALCRITICAL本就是影响程序运行的严重错误,而 python 默认的日志管理器中此方法与其他方法没有什么区别,这让我觉得莫名其妙,在本包中,我在fatal方法中加入了sys.exit(1)用来退出程序。如果在程序出现严重错误时不想退出程序,可以调用critical方法。

自定义 logger

get_logger方法:

def get_logger(
    name: Optional[str] = None,
    level: str = logging.WARNING,
    show: bool = True,
    file_path: Optional[str] = None,
) -> Logger: ...
  • name 对我来说没有用,以后可能会删除此参数
  • level 日志等级
  • show 是否在终端中显示。如果你想用此彩色日志包的话,通常是想在终端显示的吧
  • file_path 是否保存到文件。默认是None,当其不是None时,会保存到对应的文件中
  • [ ] 改为异步日志,毕竟加入色彩后可能会影响整个程序的性能
  • [ ] 改写保存文件的 formatter,使 fatal日志和critical日志分开,一个退出程序,一个不退出程序

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK