Mayil-AI-Sandbox / loguru-Jan2023

MIT License
0 stars 0 forks source link

[Question]How can I show "pretty logging with colors" in the GUI? (hashtag660) #63

Closed vikramsubramanian closed 2 months ago

vikramsubramanian commented 2 months ago

Loguru's color logging is very pretty. Can I use it in the GUI to display colored info? I tried to "redirect" the stdout to a Text control and it (of course) does not display colors. What can I do? (sorry this is not an issue, and sorry for my bad English)

import tkinter as tk import sys from loguru import logger

class ExampleApp(tk.Tk): def init(self): tk.Tk.init(self) self.text = tk.Text(self) self.text.pack()

    hashtag stdout redirect
    sys.stdout = TextRedirector(self.text, "stdout")

    hashtag add an logger (without remove ,for compare)
    logger.add(sys.stdout, level="TRACE")

    hashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtagTESThashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtag
    print ("print to  stdout")        hashtag print
    logger.error("log to stdout ")    hashtag loguru
    hashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtaghashtag

class TextRedirector(object): hashtag thanks to Bryan Oakley's answer at
def init(self, widget, tag="stdout"): self.widget = widget self.tag = tag

def write(self, str):
    self.widget.configure(state="normal")
    self.widget.insert("end", str, (self.tag,))
    self.widget.configure(state="disabled")

app = ExampleApp() app.mainloop()

vikramsubramanian commented 2 months ago

Hi

Is it possible to configure() your widget and colorize it? You'll probably need to add a handler in charge of creating and colorizing the text.

def add_log_to_gui(self, message):
    color = {"INFO": "white", "DEBUG": "grey", "ERROR": "red", "WARNING": "yellow"}
    self.widget.insert("end", message)
    self.widget.configure(color=color.get(message["level"].name, "white"))

logger.add(add_log_to_gui)
vikramsubramanian commented 2 months ago

Please, re-open the issue if my answer did not solve your issue.