-
Notifications
You must be signed in to change notification settings - Fork 10.3k
Live terminal output #5396
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
comfyanonymous
merged 7 commits into
comfyanonymous:master
from
pythongosssss:terminal-live-output
Nov 9, 2024
Merged
Live terminal output #5396
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
4f976f6
Add /logs/raw and /logs/subscribe for getting logs on frontend
pythongosssss 07271b2
Use existing send sync method
pythongosssss 67418ee
Fix get_logs should return string
pythongosssss 06efba1
Fix bug
pythongosssss bfa15b2
pass no server
pythongosssss 86816e0
fix tests
pythongosssss 7e6dbe7
Fix output flush on linux
pythongosssss File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
from app.logger import on_flush | ||
import os | ||
|
||
|
||
class TerminalService: | ||
def __init__(self, server): | ||
self.server = server | ||
self.cols = None | ||
self.rows = None | ||
self.subscriptions = set() | ||
on_flush(self.send_messages) | ||
|
||
def update_size(self): | ||
sz = os.get_terminal_size() | ||
changed = False | ||
if sz.columns != self.cols: | ||
self.cols = sz.columns | ||
changed = True | ||
|
||
if sz.lines != self.rows: | ||
self.rows = sz.lines | ||
changed = True | ||
|
||
if changed: | ||
return {"cols": self.cols, "rows": self.rows} | ||
|
||
return None | ||
|
||
def subscribe(self, client_id): | ||
self.subscriptions.add(client_id) | ||
|
||
def unsubscribe(self, client_id): | ||
self.subscriptions.discard(client_id) | ||
|
||
def send_messages(self, entries): | ||
if not len(entries) or not len(self.subscriptions): | ||
return | ||
|
||
new_size = self.update_size() | ||
|
||
for client_id in self.subscriptions.copy(): # prevent: Set changed size during iteration | ||
if client_id not in self.server.sockets: | ||
# Automatically unsub if the socket has disconnected | ||
self.unsubscribe(client_id) | ||
continue | ||
|
||
self.server.send_sync("logs", {"entries": entries, "size": new_size}, client_id) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,31 +1,73 @@ | ||
import logging | ||
from logging.handlers import MemoryHandler | ||
from collections import deque | ||
from datetime import datetime | ||
import io | ||
import logging | ||
import sys | ||
import threading | ||
|
||
logs = None | ||
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") | ||
stdout_interceptor = None | ||
stderr_interceptor = None | ||
|
||
|
||
class LogInterceptor(io.TextIOWrapper): | ||
def __init__(self, stream, *args, **kwargs): | ||
buffer = stream.buffer | ||
encoding = stream.encoding | ||
super().__init__(buffer, *args, **kwargs, encoding=encoding) | ||
self._lock = threading.Lock() | ||
self._flush_callbacks = [] | ||
self._logs_since_flush = [] | ||
|
||
def write(self, data): | ||
entry = {"t": datetime.now().isoformat(), "m": data} | ||
with self._lock: | ||
self._logs_since_flush.append(entry) | ||
|
||
# Simple handling for cr to overwrite the last output if it isnt a full line | ||
# else logs just get full of progress messages | ||
if isinstance(data, str) and data.startswith("\r") and not logs[-1]["m"].endswith("\n"): | ||
logs.pop() | ||
logs.append(entry) | ||
super().write(data) | ||
|
||
def flush(self): | ||
super().flush() | ||
for cb in self._flush_callbacks: | ||
cb(self._logs_since_flush) | ||
self._logs_since_flush = [] | ||
|
||
def on_flush(self, callback): | ||
self._flush_callbacks.append(callback) | ||
|
||
|
||
def get_logs(): | ||
return "\n".join([formatter.format(x) for x in logs]) | ||
return logs | ||
|
||
|
||
def on_flush(callback): | ||
if stdout_interceptor is not None: | ||
stdout_interceptor.on_flush(callback) | ||
if stderr_interceptor is not None: | ||
stderr_interceptor.on_flush(callback) | ||
|
||
def setup_logger(log_level: str = 'INFO', capacity: int = 300): | ||
global logs | ||
if logs: | ||
return | ||
|
||
# Override output streams and log to buffer | ||
logs = deque(maxlen=capacity) | ||
|
||
global stdout_interceptor | ||
global stderr_interceptor | ||
stdout_interceptor = sys.stdout = LogInterceptor(sys.stdout) | ||
stderr_interceptor = sys.stderr = LogInterceptor(sys.stderr) | ||
|
||
# Setup default global logger | ||
logger = logging.getLogger() | ||
logger.setLevel(log_level) | ||
|
||
stream_handler = logging.StreamHandler() | ||
stream_handler.setFormatter(logging.Formatter("%(message)s")) | ||
logger.addHandler(stream_handler) | ||
|
||
# Create a memory handler with a deque as its buffer | ||
logs = deque(maxlen=capacity) | ||
memory_handler = MemoryHandler(capacity, flushLevel=logging.INFO) | ||
memory_handler.buffer = logs | ||
memory_handler.setFormatter(formatter) | ||
logger.addHandler(memory_handler) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems here the handling of progress messages is altering original terminal behavior.