Route the standard logging module into the viewer. The handler colors the
level name and hands each line to the GUI thread through a queued signal, so
records logged from worker threads are safe too.
Sample records, the last one from a background thread.examples/logging_handler.py
"""Route Python ``logging`` into an AnsiTextViewer, colored by level.Run with ``uv run python examples/logging_handler.py``. Records logged fromany thread land in the viewer, because the handler hands each line to theGUI thread through a queued Qt signal."""importloggingimportrandomimportsysimportthreadingfromPySide6.QtCoreimportQObject,QTimer,SignalfromPySide6.QtWidgetsimportQApplicationfromansi_text_viewerimportAnsiTextViewerLEVEL_COLORS={logging.DEBUG:"36",# cyanlogging.INFO:"32",# greenlogging.WARNING:"33",# yellowlogging.ERROR:"31",# redlogging.CRITICAL:"1;31",# bold red}classAnsiFormatter(logging.Formatter):"""Format records normally, then color the level name."""defformat(self,record:logging.LogRecord)->str:"""Return the formatted record with its level name in ANSI color."""text=super().format(record)color=LEVEL_COLORS.get(record.levelno,"0")colored=f"\x1b[{color}m{record.levelname}\x1b[0m"returntext.replace(record.levelname,colored,1)class_Bridge(QObject):line=Signal(str)classViewerHandler(logging.Handler):"""A logging handler that appends to a viewer, safe from any thread."""def__init__(self,viewer:AnsiTextViewer):"""Connect to *viewer*; the connection is queued across threads."""super().__init__()self._bridge=_Bridge()self._bridge.line.connect(viewer.appendAnsiText)defemit(self,record:logging.LogRecord)->None:"""Send one formatted record to the viewer."""try:self._bridge.line.emit(self.format(record)+"\n")exceptException:self.handleError(record)defbuild()->tuple[AnsiTextViewer,logging.Logger]:"""Create the viewer and a logger that writes into it."""viewer=AnsiTextViewer()viewer.setWindowTitle("logging -> AnsiTextViewer")handler=ViewerHandler(viewer)handler.setFormatter(AnsiFormatter("%(asctime)s%(levelname)-8s%(name)s: %(message)s","%H:%M:%S"))logger=logging.getLogger("app")logger.setLevel(logging.DEBUG)logger.addHandler(handler)returnviewer,loggerSAMPLES=[(logging.INFO,"server listening on :8080"),(logging.DEBUG,"cache warmed with 412 entries"),(logging.WARNING,"slow query took 1.8s"),(logging.ERROR,"upstream returned 502"),(logging.INFO,"request served in 41ms"),(logging.CRITICAL,"disk almost full (98%)"),]defworker(logger:logging.Logger,stop:threading.Event)->None:"""Log from a background thread to show the handler is thread-safe."""log=logger.getChild("worker")whilenotstop.wait(1.3):log.info("background job tick")defmain()->None:"""Show the viewer and keep logging sample records."""app=QApplication(sys.argv)viewer,logger=build()viewer.resize(820,420)viewer.show()timer=QTimer(interval=700)timer.timeout.connect(lambda:logger.log(*random.choice(SAMPLES)))timer.start()stop=threading.Event()threading.Thread(target=worker,args=(logger,stop),daemon=True).start()app.aboutToQuit.connect(stop.set)sys.exit(app.exec())if__name__=="__main__":main()
A command box with Run and Stop. Output streams in as the process writes it,
\r progress lines overwrite in place, the view clears on each run, and the
exit code is reported in green or red. Leave the box empty to run a built-in
demo build.
The demo build run to completion; utils.py:3 is a clickable file link.examples/run_command.py
"""A small command runner: type a command, press Run, watch it stream.Run with ``uv run python examples/run_command.py``. Output is decodedincrementally, the view clears on every new run, and the exit code isreported in color when the process ends."""importcodecsimportshleximportsysfromPySide6.QtCoreimportQProcessfromPySide6.QtWidgetsimport(QApplication,QHBoxLayout,QLineEdit,QPushButton,QVBoxLayout,QWidget,)fromansi_text_viewerimportAnsiTextViewer# A self-contained default so the example works anywhere Python runs.DEMO=r"""import timefor step in range(0, 101, 25): print(f"\rbuilding... {step}%", end="", flush=True) time.sleep(0.15)print()print("\x1b[32mok\x1b[0m compiled 12 modules")print("\x1b[33mwarn\x1b[0m unused import in utils.py:3")print("\x1b[31mfail\x1b[0m test_session.py::test_load")raise SystemExit(1)"""classCommandRunner(QWidget):"""A command line, Run/Stop buttons, and a viewer for the output."""def__init__(self):"""Build the window and wire the process signals."""super().__init__()self.setWindowTitle("Run a command")self.command=QLineEdit(placeholderText="Command to run (empty: demo build)")self.run_button=QPushButton("Run")self.stop_button=QPushButton("Stop",enabled=False)self.viewer=AnsiTextViewer()self.viewer.setClearOnStart(True)bar=QHBoxLayout()bar.addWidget(self.command)bar.addWidget(self.run_button)bar.addWidget(self.stop_button)layout=QVBoxLayout(self)layout.addLayout(bar)layout.addWidget(self.viewer)self.process=QProcess(self)self.process.setProcessChannelMode(QProcess.ProcessChannelMode.MergedChannels)self.process.readyReadStandardOutput.connect(self.read_output)self.process.finished.connect(self.finished)self.run_button.clicked.connect(self.run)self.stop_button.clicked.connect(self.process.kill)defrun(self)->None:"""Start the typed command, or the demo build when the box is empty."""text=self.command.text().strip()args=shlex.split(text)iftextelse[sys.executable,"-c",DEMO]self.decoder=codecs.getincrementaldecoder("utf-8")(errors="replace")self.viewer.beginNewStream()self.viewer.appendAnsiText(f"\x1b[90m$ {textor'demo build'}\x1b[0m\n")self.process.start(args[0],args[1:])self.run_button.setEnabled(False)self.stop_button.setEnabled(True)defread_output(self)->None:"""Append whatever the process has written so far."""data=self.process.readAllStandardOutput().data()self.viewer.appendAnsiText(self.decoder.decode(data))deffinished(self,code:int,status:QProcess.ExitStatus)->None:"""Report the exit code and re-enable Run."""self.viewer.appendAnsiText(self.decoder.decode(b"",final=True))color="32"ifcode==0else"31"self.viewer.appendAnsiText(f"\x1b[{color}m[exit {code}]\x1b[0m\n")self.run_button.setEnabled(True)self.stop_button.setEnabled(False)defbuild()->CommandRunner:"""Create the runner window."""returnCommandRunner()defmain()->None:"""Show the runner."""app=QApplication(sys.argv)runner=build()runner.resize(820,420)runner.show()sys.exit(app.exec())if__name__=="__main__":main()
tail -f for any file: pass a path, or run it without one to follow a demo
log. The file is polled, which works on every platform and for files any
program writes; when the file shrinks (rotation, truncation) the view says so
and starts again from the top.
Four lines appended, then the file truncated and written again.examples/tail_file.py
"""Follow a growing log file, like ``tail -f``.Run with ``uv run python examples/tail_file.py path/to/app.log``. Without apath, it writes a demo log to a temporary file and follows that. The file ispolled, which works on every platform and for files written by any program;if the file shrinks (log rotation, truncation) it starts again from the top."""importcodecsimportsysimporttempfilefrompathlibimportPathfromPySide6.QtCoreimportQTimerfromPySide6.QtWidgetsimportQApplicationfromansi_text_viewerimportAnsiTextViewerclassFileTail:"""Poll *path* and append new bytes to *viewer*."""def__init__(self,viewer:AnsiTextViewer,path:Path,interval_ms:int=250):"""Start following *path* from its beginning."""self.viewer=viewerself.path=pathself.offset=0self.decoder=codecs.getincrementaldecoder("utf-8")(errors="replace")self.timer=QTimer(interval=interval_ms)self.timer.timeout.connect(self.poll)self.timer.start()self.poll()defpoll(self)->None:"""Read anything appended since the last poll."""try:size=self.path.stat().st_sizeexceptFileNotFoundError:returnifsize<self.offset:# rotated or truncatedself.offset=0self.decoder.reset()self.viewer.appendAnsiText(f"\x1b[33m--- {self.path.name} truncated ---\x1b[0m\n")ifsize==self.offset:returnwithself.path.open("rb")asf:f.seek(self.offset)data=f.read()self.offset+=len(data)self.viewer.appendAnsiText(self.decoder.decode(data))DEMO_LINES=["\x1b[32mINFO \x1b[0m worker started (pid 4120)","\x1b[36mDEBUG\x1b[0m polling queue 'jobs'","\x1b[32mINFO \x1b[0m job 17 done in 220ms","\x1b[33mWARN \x1b[0m job 18 retry 1/3","\x1b[31mERROR\x1b[0m job 18 failed: connection reset",]defdemo_writer(path:Path)->QTimer:"""Append a demo line to *path* every 600 ms."""count=iter(range(10**9))defwrite():n=next(count)withpath.open("a",encoding="utf-8")asf:f.write(DEMO_LINES[n%len(DEMO_LINES)]+"\n")timer=QTimer(interval=600)timer.timeout.connect(write)timer.start()returntimerdefbuild(path:Path)->tuple[AnsiTextViewer,FileTail]:"""Create a viewer following *path*."""viewer=AnsiTextViewer()viewer.setWindowTitle(f"tail -f {path}")returnviewer,FileTail(viewer,path)defmain()->None:"""Follow the path given on the command line, or a demo file."""app=QApplication(sys.argv)iflen(sys.argv)>1:path,writer=Path(sys.argv[1]),Noneelse:path=Path(tempfile.gettempdir())/"qansitextviewer-demo.log"path.write_text("",encoding="utf-8")writer=demo_writer(path)viewer,tail=build(path)viewer.resize(820,420)viewer.show()exit_code=app.exec()delwriter,tailsys.exit(exit_code)if__name__=="__main__":main()
Plain text with no ANSI codes can still be colored. Three small rules dim
client addresses, color HTTP status codes by class, and bold every timing.
See Highlighting for the rule protocol.
An access log colored by three custom rules.examples/custom_highlight.py
"""Add your own highlight rules: durations, HTTP status codes, IP addresses.Run with ``uv run python examples/custom_highlight.py``. A rule is anyobject with ``spans(text)`` that yields ``Span`` objects; it colors plainlog text that carries no ANSI codes of its own."""importreimportsysfromcollections.abcimportIterablefromPySide6.QtGuiimportQColorfromPySide6.QtWidgetsimportQApplicationfromansi_text_viewerimportAnsiTextViewerfromansi_text_viewer.highlightimportSpanclassDurationRule:"""Bold orange for timings like ``41ms`` or ``2.5s``."""pattern=re.compile(r"\b\d+(?:\.\d+)?(?:ms|s)\b")defspans(self,text:str)->Iterable[Span]:"""Yield one span per duration in *text*."""forminself.pattern.finditer(text):yieldSpan(m.start(),m.end(),foreground=QColor(214,110,0),bold=True)classStatusRule:"""HTTP status codes: 2xx green, 3xx blue, 4xx amber, 5xx red."""pattern=re.compile(r"\" ([1-5]\d\d) ")colors={"2":QColor(0,140,60),"3":QColor(30,100,200),"4":QColor(190,120,0),"5":QColor(200,30,30),}defspans(self,text:str)->Iterable[Span]:"""Yield a bold span on the status code of an access-log line."""m=self.pattern.search(text)ifmandm.group(1)[0]inself.colors:color=self.colors[m.group(1)[0]]yieldSpan(m.start(1),m.end(1),foreground=color,bold=True)classIpRule:"""Dim the client address so the request stands out."""pattern=re.compile(r"^\d{1,3}(?:\.\d{1,3}){3}")defspans(self,text:str)->Iterable[Span]:"""Yield a gray span over a leading IPv4 address."""m=self.pattern.match(text)ifm:yieldSpan(m.start(),m.end(),foreground=QColor(120,120,120))ACCESS_LOG="""\10.0.0.12 - - "GET /api/v1/users HTTP/1.1" 200 1532 41ms10.0.0.12 - - "GET /static/app.js HTTP/1.1" 304 0 3ms192.168.4.7 - - "POST /api/v1/login HTTP/1.1" 401 88 120ms10.0.0.31 - - "GET /api/v1/reports?year=2026 HTTP/1.1" 200 90210 2.4s192.168.4.7 - - "GET /old-page HTTP/1.1" 301 0 2ms10.0.0.44 - - "POST /api/v1/upload HTTP/1.1" 502 0 30.0s10.0.0.12 - - "DELETE /api/v1/users/17 HTTP/1.1" 204 0 18ms"""defbuild()->AnsiTextViewer:"""Create a viewer with the three custom rules and a sample access log."""viewer=AnsiTextViewer()viewer.setWindowTitle("Custom highlight rules")# Access logs are full of URL paths that are not local files; keep the# built-in file and URL link rules from underlining them.viewer.setLinksEnabled(False)forrulein(IpRule(),StatusRule(),DurationRule()):viewer.add_highlight_rule(rule)viewer.appendAnsiText(ACCESS_LOG)returnviewerdefmain()->None:"""Show the highlighted access log."""app=QApplication(sys.argv)viewer=build()viewer.resize(820,300)viewer.show()sys.exit(app.exec())if__name__=="__main__":main()
Load hundreds of thousands of lines without freezing the window:
appendAnsiTextAsync() inserts one chunk per event-loop turn, a progress bar
follows asyncAppendProgress, and Cancel drops the rest. The example raises
setMaximumBlocks(), since the default keeps only the newest 10,000 lines.
60,000 generated lines, loaded in the background.examples/big_file.py
"""Open a huge log without freezing the window.Run with ``uv run python examples/big_file.py path/to/huge.log``. Without apath, it generates 200,000 colored lines. The text goes in through``appendAnsiTextAsync()``, one chunk per event-loop turn, while a progressbar follows along and Cancel stops the rest."""importsysfrompathlibimportPathfromPySide6.QtWidgetsimport(QApplication,QHBoxLayout,QLabel,QProgressBar,QPushButton,QVBoxLayout,QWidget,)fromansi_text_viewerimportAnsiTextViewerLEVELS=["\x1b[32mINFO \x1b[0m","\x1b[36mDEBUG\x1b[0m","\x1b[33mWARN \x1b[0m"]defsynthetic_log(lines:int)->str:"""Return *lines* lines of colored sample log text."""return"".join(f"{LEVELS[i%3]} request {i:>6} handled in {i%97+3}ms\n"foriinrange(lines))classBigFileWindow(QWidget):"""A viewer, a progress bar, and a Cancel button."""def__init__(self):"""Build the window and wire the async progress signals."""super().__init__()self.setWindowTitle("Big file")self.viewer=AnsiTextViewer()self.viewer.setMaximumBlocks(250_000)# default keeps the newest 10,000self.progress=QProgressBar()self.status=QLabel("idle")self.cancel=QPushButton("Cancel",enabled=False)self.total=0bar=QHBoxLayout()bar.addWidget(self.progress,1)bar.addWidget(self.status)bar.addWidget(self.cancel)layout=QVBoxLayout(self)layout.addWidget(self.viewer)layout.addLayout(bar)self.viewer.asyncAppendProgress.connect(self.on_progress)self.viewer.asyncAppendFinished.connect(self.on_finished)self.cancel.clicked.connect(self.on_cancel)defload(self,text:str)->None:"""Queue *text* for non-blocking insertion."""self.viewer.clear()self.total=0self.cancel.setEnabled(True)self.status.setText("loading...")self.viewer.appendAnsiTextAsync(text,chunk_lines=2000)defon_progress(self,done:int,total:int)->None:"""Mirror the async queue in the progress bar."""self.total=totalself.progress.setMaximum(total)self.progress.setValue(done)self.status.setText(f"{done:,} / {total:,} lines")defon_finished(self)->None:"""Report completion."""self.cancel.setEnabled(False)self.status.setText(f"done, {self.total:,} lines")defon_cancel(self)->None:"""Drop whatever has not been inserted yet."""dropped=self.viewer.cancelAsyncAppends()self.cancel.setEnabled(False)self.status.setText(f"cancelled ({dropped} chunks dropped)")defbuild()->BigFileWindow:"""Create the window."""returnBigFileWindow()defmain()->None:"""Load the file named on the command line, or generated lines."""app=QApplication(sys.argv)window=build()window.resize(820,480)window.show()iflen(sys.argv)>1:text=Path(sys.argv[1]).read_text(encoding="utf-8",errors="replace")else:text=synthetic_log(200_000)window.load(text)sys.exit(app.exec())if__name__=="__main__":main()