rich icon indicating copy to clipboard operation
rich copied to clipboard

[REQUEST] Add markup support for `Console.log_time_format`

Open rabbit-time opened this issue 3 years ago • 6 comments

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.

rabbit-time avatar Jun 13 '22 23:06 rabbit-time

That would be problematic if the time format contains square brackets. How exactly would you want to format a time for logs?

willmcgugan avatar Jun 14 '22 07:06 willmcgugan

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)

rabbit-time avatar Jun 14 '22 09:06 rabbit-time

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))

willmcgugan avatar Jun 14 '22 09:06 willmcgugan

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.

rabbit-time avatar Jun 14 '22 11:06 rabbit-time

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!")

willmcgugan avatar Jun 15 '22 08:06 willmcgugan

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.

rabbit-time avatar Jun 25 '22 05:06 rabbit-time

Did I solve your problem?

Why not buy the devs a coffee to say thanks?

github-actions[bot] avatar Sep 20 '22 10:09 github-actions[bot]