python 日志打印log

Python 中常用的打印 log 的库有以下几个:

logging

Python 标准库中的模块,提供了灵活的日志记录方式,可以输出到控制台或文件,支持级别控制、日志格式化等功能。
使用 logging 模块打印日志的一般步骤如下:
导入 logging 模块:

import logging

配置日志记录器:

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

在这里,我们使用 basicConfig 方法来配置日志记录器,其中 level 参数指定了日志级别为 DEBUGformat 参数指定了日志输出的格式,包括时间、日志名称、日志级别和日志内容。

使用日志记录器输出不同级别的日志:

logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')

在这里,我们使用 logging 模块的不同方法输出了不同级别的日志信息。
完整示例代码如下:

import logging

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')

这段代码将输出以下内容,包括时间、日志名称、日志级别和日志内容:

2021-09-01 21:08:20,017 - root - DEBUG - This is a debug message
2021-09-01 21:08:20,018 - root - INFO - This is an info message
2021-09-01 21:08:20,018 - root - WARNING - This is a warning message
2021-09-01 21:08:20,018 - root - ERROR - This is an error message
2021-09-01 21:08:20,018 - root - CRITICAL - This is a critical message

除了上述基本用法外,logging 模块还支持更加丰富的配置和扩展,比如可以将日志输出到文件、自定义日志处理器等等,具体可以参考 logging 模块的官方文档:https://docs.python.org/3/library/logging.html

loguru

一个类似 logging 的第三方库,提供了更简洁的语法和更方便的配置方式,支持彩色日志、异常捕获、自动旋转日志文件等功能。

使用 loguru 打印日志非常简单,通常只需要三步:

安装 loguru 库,可以使用以下命令进行安装:

pip install loguru

导入 loguru 模块:

from loguru import logger

配置日志记录器:

logger.add("file.log", rotation="500 MB")

在这里,我们使用 logger.add() 方法来配置日志记录器,其中 file.log 参数指定了日志输出到的文件名,rotation 参数指定了日志文件的轮转方式,这里是按照文件大小进行轮转,每个文件最大为 500MB。
最后,我们可以使用 logger 对象打印日志,例如:

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")

loguru 还提供了更多的功能,例如可以自定义日志格式、支持异步日志记录、支持异常记录等等,具体可以参考 loguru 的官方文档:https://loguru.readthedocs.io/en/stable/index.html

coloredlogs

一个可以为 Python 的 logging 模块提供彩色日志输出的库,支持将不同级别的日志输出到不同的日志记录器中。

使用
coloredlogs 打印彩色日志非常简单,通常只需要三步:
安装 coloredlogs 库,可以使用以下命令进行安装:

pip install coloredlogs

导入 coloredlogs 模块:

import coloredlogs

配置日志记录器:

import logging

logger = logging.getLogger(__name__)
coloredlogs.install(level='DEBUG', logger=logger)

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

上述代码中,我们首先创建了一个名为 logger 的日志记录器,然后使用 coloredlogs.install() 方法来配置日志记录器,其中 level 参数指定了日志级别为 DEBUG,logger 参数指定了要配置的日志记录器。

最后,我们使用 logger 对象打印了三条不同级别的日志,这些日志将会以彩色的形式输出到控制台,便于我们快速区分不同级别的日志。
image

除了上述示例中的基本用法外,coloredlogs 还提供了许多其他的配置选项,比如可以自定义日志格式、选择不同的日志颜色等等,具体可以参考 coloredlogs 的官方文档:https://coloredlogs.readthedocs.io/en/latest/

rich

一个终端输出库,可以为 Python 的 logging 模块提供丰富的输出格式,支持彩色日志、代码高亮、表格输出等。

使用 rich 使命令行界面更美观和交互性更强非常简单,以下是一些基本示例:

安装 rich 库,可以使用以下命令进行安装:

pip install rich

导入 rich 模块:

from rich.console import Console

创建 Console 对象:

console = Console()

使用 console 对象打印不同样式的文本:

console.print("Hello, [bold magenta]World[/bold magenta]!", style="bold red")
console.print("This is an [underline]underlined[/underline] text.")
console.print("This is a [link=https://www.google.com]link[/link].")
console.print("This is a [italic]italic[/italic] text.")
console.print("This is a [reverse]reversed[/reverse] text.")
console.print("This is a [blink]blinking[/blink] text.")

//在这里,我们使用 `console.print()` 方法打印了不同样式的文本,例如加粗、颜色、下划线、超链接、斜体、反转和闪烁等。

使用 rich 模块的其他功能,例如表格、进度条和图形等:

from rich.progress import track
from rich.table import Table

table = Table(title="Star Wars Movies")
table.add_column("Episode")
table.add_column("Title")
table.add_column("Director")

table.add_row("IV", "A New Hope", "George Lucas")
table.add_row("V", "The Empire Strikes Back", "Irvin Kershner")
table.add_row("VI", "Return of the Jedi", "Richard Marquand")

console.print(table)

with track(range(100)) as progress:
    for item in progress:
        # do some work here
        pass

from rich.console import Console
from rich.panel import Panel

console = Console()

panel = Panel("Hello, World!", title="[bold green]Message")

console.print(panel)

from rich.graph import Graph

graph = Graph()

graph.add_edge("a", "b")
graph.add_edge("a", "c")
graph.add_edge("a", "d")
graph.add_edge("b", "c")

console.print(graph)

在这里,我们使用了 rich 模块的其他功能,例如表格、进度条和图形等,可以根据需要选择使用。
完整示例代码如下:

from rich.console import Console
from rich.progress import track
from rich.table import Table

console = Console()

console.print("Hello, [bold magenta]World[/bold magenta]!", style="bold red")
console.print("This is an [underline]underlined[/underline] text.")
console.print("This is a [link=https://www.google.com]link[/link].")
console.print("This is a [italic]italic[/italic] text.")
console.print("This is a [reverse]reversed[/reverse] text.")
console.print("This is a [blink]blinking[/blink] text.")

table = Table(title="Star Wars Movies")
table.add_column("Episode")
table.add_column("Title")
table.add_column("Director")

table.add_row("IV", "A New Hope", "George Lucas")
table.add_row("V", "The Empire Strikes Back", "Irvin Kershner")
table.add_row("VI", "Return of the Jedi", "Richard Marquand")

console.print(table)

with track(range(100)) as progress:
    for item in progress:
        # do some work here
        pass

from rich.console import Console
from rich.panel import Panel

console = Console()

panel = Panel("Hello, World!", title="[bold green]Message")

console.print(panel)

from rich.graph import Graph

graph = Graph()

graph.add_edge("a", "b")
graph.add_edge("a", "c")
graph.add_edge("a", "d")
graph.add_edge("b", "c")

console.print(graph)

rich 还提供了很多其他的功能和定制选项,例如表单、列表、选择器、文件树等等,具体可以参考 rich 的官方文档:https://rich.readthedocs.io/en/latest/

总结

以上这些库都可以用来打印 log,选择哪一个库取决于你的具体需求和习惯。其中,logging 是 Python 标准库自带的日志库,使用较为广泛,loguru 是一个较为新的库,使用较为简便,rich 则是一个专注于终端输出的库,可以为 log 提供更加美观的输出效果。