I have a simple FreeSimpleGui application (PySimpleGui). It shows a text window and there is a custom logger which writes to that text window:
How is it possible to change the format of the custom logger? I seem only to be able to change the config of the root logger, but my custom logger just ignores it.
import FreeSimpleGUI as sg
import logging
class OutputHandler(logging.Handler):
window: sg.Window
def __init__(self, window: sg.Window):
super().__init__()
self.window = window
def emit(self, record):
self.window["txtLog"].print(record)
layout = [
[sg.Multiline(default_text="", size=(100, 10), disabled=True, autoscroll=True, key="txtLog")]
]
window = sg.Window('Form', layout, finalize=True)
outHandler = OutputHandler(window)
log = logging.getLogger("root")
log.setLevel(logging.INFO)
log.addHandler(outHandler)
i = 0
while True:
event, values = window.read(timeout = 1000, timeout_key=sg.TIMEOUT_KEY, close=False)
if event == sg.WIN_CLOSED or event == 'Exit':
break
logging.info("Hello World " + str(i))
i += 1
window.close()
record
in your emit
function is a logging.LogRecord
object, which haven't been formatted yet, you can make a formatted string with attributes of record
:
def emit(self, record):
message = "%s:%s" % (record.pathname, record.msg)
self.window["txtLog"].print(message)
or make a formatted string with help of logging
's Formatter
:
def emit(self, record):
if self.formatter:
message = self.formatter.format(record)
else:
message = record
self.window["txtLog"].print(message)
...
format = logging.Formatter(
fmt="%(pathname)s:%(message)s",
style="%"
)
outHandler = OutputHandler(window)
outHandler.setFormatter(format)
log = logging.getLogger("mylogger")
log.setLevel(logging.INFO)
log.addHandler(outHandler)
...