Python 日志记录 - 以格式保存到文件

标签 python linux bash ubuntu

我有 python 的日志记录模块,配置了各种颜色编码的行。 但是,当使用文件处理程序导出到日志文件,然后使用 tail -f 实时跟踪文件时,颜色会丢失。

有没有办法将颜色格式导出到输出文件,例如 tailless 和 co.可以正确显示吗?

python 端的配置是通过以下方式完成的:

coloredlogs.install(
logger=_logger, fmt='%(asctime)s %(message)s', use_chroot=False,
field_styles={'asctime': {'color': 'cyan'}}, datefmt='%d.%m.%Y %H:%M',
level_styles={
    'info': {'color': 'white', 'bold': False},
    'warn': {'color': 'blue', 'bold': True},
    'error': {'color': 'magenta', 'bold': False}
}

)

谢谢

最佳答案

您可以通过设置 isatty 参数来禁用是否应使用彩色格式化程序(默认:在终端 session 中)的自动检测。

https://coloredlogs.readthedocs.io/en/latest/api.html#coloredlogs.install

简短的例子

import coloredlogs, logging

_logger = logging.getLogger(__name__)

coloredlogs.install(
    logger=_logger, fmt='%(asctime)s %(message)s', use_chroot=False,
    field_styles={'asctime': {'color': 'cyan'}}, datefmt='%d.%m.%Y %H:%M',
    level_styles={
        'info': {'color': 'white', 'bold': False},
        'warn': {'color': 'blue', 'bold': True},
        'error': {'color': 'magenta', 'bold': False}
    },
    isatty=True
)

_logger.debug("a debug message")
_logger.info("an info message")
_logger.warning("a warning message")
_logger.error("an error message")
_logger.critical("a critical message")

当您将输出重定向到文件时,该文件将包含 ANSI 转义序列。

00000000  1b 5b 33 36 6d 31 34 2e  31 30 2e 32 30 31 39 20  |.[36m14.10.2019 |
00000010  31 35 3a 31 35 1b 5b 30  6d 20 1b 5b 33 37 6d 61  |15:15.[0m .[37ma|
00000020  6e 20 69 6e 66 6f 20 6d  65 73 73 61 67 65 1b 5b  |n info message.[|
00000030  30 6d 0a 1b 5b 33 36 6d  31 34 2e 31 30 2e 32 30  |0m..[36m14.10.20|
00000040  31 39 20 31 35 3a 31 35  1b 5b 30 6d 20 1b 5b 31  |19 15:15.[0m .[1|
00000050  3b 33 34 6d 61 20 77 61  72 6e 69 6e 67 20 6d 65  |;34ma warning me|
00000060  73 73 61 67 65 1b 5b 30  6d 0a 1b 5b 33 36 6d 31  |ssage.[0m..[36m1|
00000070  34 2e 31 30 2e 32 30 31  39 20 31 35 3a 31 35 1b  |4.10.2019 15:15.|
00000080  5b 30 6d 20 1b 5b 33 35  6d 61 6e 20 65 72 72 6f  |[0m .[35man erro|
00000090  72 20 6d 65 73 73 61 67  65 1b 5b 30 6d 0a 1b 5b  |r message.[0m..[|
000000a0  33 36 6d 31 34 2e 31 30  2e 32 30 31 39 20 31 35  |36m14.10.2019 15|
000000b0  3a 31 35 1b 5b 30 6d 20  61 20 63 72 69 74 69 63  |:15.[0m a critic|
000000c0  61 6c 20 6d 65 73 73 61  67 65 0a                 |al message.|

关于Python 日志记录 - 以格式保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58373674/

相关文章:

linux - `gcloud compute copy-files` : permission denied when copying files

linux - 如何编译交叉引用文件?

在 linux 上为 windows 交叉编译 C,出现编译器错误

bash - 使用 tar/bzip2 通过 SSH 将压缩目录提取到本地计算机

git - 无法使用 bash 脚本从 git 历史记录中删除文件

linux - 为什么我的 Bash 脚本将 <feff> 添加到文件的开头?

python - 缺少所需的参数状态Python社交身份验证电子邮件验证

python - 如何在PyQt 5.9中访问录音音量?

python - pyodbc 返回 ® 作为?

python - 打印空行Python的函数