1

I'm trying to add a richFormatter() to my existing logging stack, but how can I get it to fit my own logging format: and not wrap the default richLogger outside of it?

#!/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})

From the output you see the first line is rich and the 2nd is my default format:

enter image description here

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}
MortenB
  • 2,749
  • 1
  • 31
  • 35
  • 1
    You have `show_level=True` in your RichHandler. Did you check what it does? It defaults to True already and it's to enable column to show level. So you should probably set it and time column to False. Meaning: `ch = RichHandler(level=logging.DEBUG, show_level=False, show_time=False, show_path=False)` – h4z3 Jan 17 '22 at 13:18
  • @h4z3: You nailed it, it was correct, it took away everything – MortenB Jan 17 '22 at 21:01

0 Answers0