question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[help] How to print functin name on the right hand side during logging

See original GitHub issue

From docs (https://rich.readthedocs.io/en/latest/logging.html#logging-handler):

import logging
from rich.logging import RichHandler

FORMAT = "%(message)s"
logging.basicConfig(
    level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]
)

log = logging.getLogger("rich")
def main():
    log.info("Hello, World!")

main()

Has following output:

image

Instead of the filename could I have the function name on the right hand side as:

[11:53:44] INFO     Hello, World!                                                                main():31

or filename along with the function name:

[11:53:44] INFO     Hello, World!                                                         doo.py:main():31

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6

github_iconTop GitHub Comments

1reaction
samatjaincommented, Mar 9, 2022

@avatar-lavventura Something along the lines of:

from datetime import datetime
from logging import LogRecord
from pathlib import Path
from typing import Optional

from rich.logging import RichHandler
# May be missing some other imports, you can figure it out
...

class MyRichHandler(RichHandler):
    def render(
        self,
        *,
        record: LogRecord,
        traceback: Optional[Traceback],
        message_renderable: "ConsoleRenderable",
    ):
        """Render log for display.
        Args:
            record (LogRecord): logging Record.
            traceback (Optional[Traceback]): Traceback instance or None for no Traceback.
            message_renderable (ConsoleRenderable): Renderable (typically Text) containing log message contents.
        Returns:
            ConsoleRenderable: Renderable to display log.
        """
        path = Path(record.pathname).name + ":" + record.funcName
        level = self.get_level_text(record)
        time_format = None if self.formatter is None else self.formatter.datefmt
        log_time = datetime.fromtimestamp(record.created)

        log_renderable = self._log_render(
            self.console,
            [message_renderable] if not traceback else [message_renderable, traceback],
            log_time=log_time,
            time_format=time_format,
            level=level,
            path=path,
            line_no=record.lineno,
            link_path=record.pathname if self.enable_link_path else None,
        )
        return log_renderable

I get:

[16:20:23] INFO     cp tsmu.py -> host="example.com"                     fabfile.py:deploy_tsmu:130

which I believe is what you want. I believe the hyperlink in the filename/function name also will work, but my shell does not support it to test.

I think this is a little gross. +1 for the extensibility mentioned in https://github.com/Textualize/rich/pull/1705#issuecomment-984904009

1reaction
willmcgugancommented, Sep 30, 2021
class MyLogger(RichLogger):
    def render(self): 
        # your code
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to include the function name into logging - Stack Overflow
Just use %(funcName)s , as documented here.
Read more >
Python Logging Guide - Best Practices and Hands-on Examples
The name argument in the factory function is typically a dot-separated hierarchical name, e.g., a.b.c. This naming convention enables the ...
Read more >
DON'T use Print for logging | How to Log messages in Python
I hope this video was helpful and gives you a good understanding of how to log messages in python using logging module. ·...
Read more >
Your Guide to the Python print() Function
In this step-by-step tutorial, you'll learn about the print() function in Python and discover some of its lesser-known features.
Read more >
Python Logging Levels Explained - LogicMonitor
The functions contained in this module are designed to allow developers to log to different destinations. This is done by defining specific handlers...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found