0

我正在尝试将richFormatter() 添加到我现有的日志记录堆栈中,但是我怎样才能让它适合我自己的日志记录格式:而不是将默认的richLogger 包装在它之外?

#!/usr/bin/env python3
import logging
from operator import truediv
from rich.logging import RichHandler

# in console we like this because vscode map the fullpath + linenumber
console_fmt = "%(asctime)s.%(msecs)03d|%(levelname)s|%(pathname)s:%(lineno)d|%(message)s"
datefmt = "%Y%m%d%H%M%S"

log = logging.getLogger('root')
log.setLevel(logging.DEBUG)


ch = RichHandler(level=logging.DEBUG, show_level=True)
ch.setLevel(logging.DEBUG)
# this goes inside the rich format, I want it to define it entirely:
ch.setFormatter(logging.Formatter(console_fmt, datefmt))
log.addHandler(ch)

# just to show my existing default format as a 2nd line
olog = logging.getLogger('root')
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(logging.Formatter(console_fmt, datefmt))
olog.addHandler(ch)

log.info({"array": [1,2,3,4], "dict": {'one': 1, 'two': 2, 'three':3}, 'ok': True, 'notok': False})

从输出中你可以看到第一行很丰富,第二行是我的默认格式:

在此处输入图像描述

20220117133730 INFO     20220117133730.649|INFO|C:\dist\work\trk-fullstack-test\bin\logtest.py:26|{'array': [1, 2, 3, 4], 'dict': {'one': 1, 'two': 2, 'three': 3}, 'ok': True, 'notok': False}            logtest.py:26
20220117133730.649|INFO|C:\dist\work\trk-fullstack-test\bin\logtest.py:26|{'array': [1, 2, 3, 4], 'dict': {'one': 1, 'two': 2, 'three': 3}, 'ok': True, 'notok': False}
4

0 回答 0