为日志添加颜色和格式
plogs的Python项目详细描述
扑通一声-漂亮的圆木
项目目标
最初,漂亮日志的目标是创建一个为可伸缩项目设计的彩色日志系统。后来, 我对漂亮日志的愿景在范围上有所扩展,包括在javascript和 在python中不是很容易得到。
在将来,我们希望能够更好地控制日志设置的配置和调试日志级别,其中调试工具 只能打印到。
安装
你可以通过pip安装漂亮的日志。pypi link
$ pip install --upgrade plogs
设置
将漂亮的日志导入到项目中非常简单。所需的只是导入plogs并实例化logger的实例。
fromplogsimportget_loggerlogging=get_logger()
建议在项目根级别的__init__.py
文件中执行以下步骤,以便可以在整个应用程序中引用漂亮的日志。
带有颜色的日志
漂亮日志的主要特点是对不同的日志级别和状态进行颜色编码。默认日志记录级别设置为:
Log Level | Color |
---|---|
logging.info | gray |
logging.status | bold |
logging.success | green |
logging.warning | orange |
logging.error | red |
logging.critical | red highlights |
登录到文件
漂亮的日志可以将彩色日志写入文件。这是通过漂亮的logs'config函数完成的。
fromplogsimportget_loggerlogging=get_logger()logging.config(to_file=True)logging.info('this is will be written to a file')
默认情况下,文件被写入/var/log/plogs/plog_01.log
。/var/log/
被选为默认目录,因为它通常用于基于unix的计算机和
Docker图像服务。
如果要使用其他文件名和位置,只需对其进行如下编辑即可:
logging.config(to_file=True,file_location='your/filepath/here/',filename='new_file.log')
注意:建议使用less
终端命令查看彩色日志-如果less
不起默认作用,则less -r
值得尝试。还有,漂亮的圆木
不是为了在vim、atom、sublime和其他流行的文本编辑器中显示彩色文件而设计的。
格式化日志
漂亮的日志允许很多定制。定制日志是通过编辑日志config并提供格式化字符串的漂亮日志来完成的。
以下是所有可配置变量:
Variable | Type | Format Keyword | Description |
---|---|---|---|
^{ | ^{ | ^{ | Setting to ^{ |
^{ | ^{ | ^{ | Setting to ^{ |
^{ | ^{ | ^{ | Setting to ^{ |
^{ | ^{ | ^{ | Setting to ^{ |
^{ | ^{ | ^{ | Default ^{ |
^{ | ^{ | ^{ | Default log file is ^{ |
^{ | ^{ | ^{ | Shows the log message in formatted log |
格式化日志的示例如下:
fromplogsimportget_loggerlogging=get_logger()# configure plogs to allow logging level and date/timelogging.config(show_levels=True,show_time=True)# config logs with the `{level}` keyword to show the logging level,# `{time}` to show the date & time of when the log was written# and `{msg} to show the logging messagelogging.format('[{level}] - {time} - {msg}')# finally write logslogging.status('Show me the logs')logging.info('We got some info')# Output:# [STATUS] - 2018-12-11 11:56:05 - Show me the logs# [INFO] - 2018-12-11 11:56:09 - We got some info
注意:为了格式化漂亮的日志,您必须将要写入的变量放入{}
-例如:{filename}
、{file_location}
、{levels}
等。
这些值将替换为它们所表示的变量
我该怎么做?
如果你想贡献自己,可以查看how to contribute doc