rich
rich copied to clipboard
[REQUEST] Add markup support for `Console.log_time_format`
Currently, markup does not work in Console.log_time_format. Although Console is intended to be a high-level console interface, it would be nice if Console.log parsed the markup in the time format.
That would be problematic if the time format contains square brackets. How exactly would you want to format a time for logs?
Pretty easily. Example: '[blue]%m.%d.%y[/blue][red]%I:%M %p[/red]'
You can even run this code and it works fine with strftime:
from datetime import datetime
format = '[blue]%m.%d.%y[/blue][red]%I:%M %p[/red]'
timestamp = datetime.now().strftime(format)
print(timestamp)
Actually, I think there is already a solution. log_time_format may be a callable that returns a Text instance.
Something like this should work:
format = '[blue]%m.%d.%y[/blue][red]%I:%M %p[/red]'
log_time_format = lambda dt: Text.from_markup(dt.strftime(format))
You can't have a Text instance as the log_time_format, since it gets passed directly to strftime when calling Console.log.
log_time_format must be str or a callable that returns str.
Additionally, I've tried to work around it by parsing the markup and then passing it as an str, but it gets overwritten by Console.log's styling.
Try this:
from rich.text import Text
import logging
from rich.logging import RichHandler
FORMAT = "%(message)s"
logging.basicConfig(
level="NOTSET",
format=FORMAT,
handlers=[
RichHandler(
log_time_format=lambda dt:Text.from_markup(f"[red]{dt.ctime()}")
)
]
)
log = logging.getLogger("rich")
log.info("Hello, World!")
This is a viable solution - but I do believe it would be useful to implement this functionality for Console as well. This, of course, is up to you. If you disagree with this, you can go ahead and close the issue.