2023-08-09 11:49:33 -06:00
|
|
|
import logging
|
2024-01-04 07:13:08 -07:00
|
|
|
import os
|
2023-08-09 11:49:33 -06:00
|
|
|
|
2023-11-16 12:43:59 -07:00
|
|
|
try:
|
2024-01-04 07:13:08 -07:00
|
|
|
from tqdm import tqdm
|
|
|
|
|
2023-11-16 09:20:33 -07:00
|
|
|
|
2023-11-16 12:43:59 -07:00
|
|
|
class TqdmLoggingHandler(logging.Handler):
|
2024-01-04 07:13:08 -07:00
|
|
|
def __init__(self, fallback_handler: logging.Handler):
|
|
|
|
super().__init__()
|
|
|
|
self.fallback_handler = fallback_handler
|
2023-11-16 09:20:33 -07:00
|
|
|
|
2023-11-16 12:43:59 -07:00
|
|
|
def emit(self, record):
|
|
|
|
try:
|
2024-01-04 07:13:08 -07:00
|
|
|
# If there are active tqdm progress bars,
|
|
|
|
# attempt to not interfere with them.
|
|
|
|
if tqdm._instances:
|
|
|
|
tqdm.write(self.format(record))
|
|
|
|
else:
|
|
|
|
self.fallback_handler.emit(record)
|
2023-11-16 12:43:59 -07:00
|
|
|
except Exception:
|
2024-01-04 07:13:08 -07:00
|
|
|
self.fallback_handler.emit(record)
|
2023-11-16 12:43:59 -07:00
|
|
|
|
|
|
|
except ImportError:
|
2024-01-04 07:13:08 -07:00
|
|
|
TqdmLoggingHandler = None
|
|
|
|
|
2023-08-09 11:49:33 -06:00
|
|
|
|
|
|
|
def setup_logging(loglevel):
|
|
|
|
if loglevel is None:
|
|
|
|
loglevel = os.environ.get("SD_WEBUI_LOG_LEVEL")
|
|
|
|
|
2024-01-04 07:13:08 -07:00
|
|
|
if not loglevel:
|
|
|
|
return
|
|
|
|
|
|
|
|
if logging.root.handlers:
|
|
|
|
# Already configured, do not interfere
|
|
|
|
return
|
|
|
|
|
|
|
|
if os.environ.get("SD_WEBUI_RICH_LOG"):
|
|
|
|
from rich.logging import RichHandler
|
|
|
|
handler = RichHandler()
|
|
|
|
else:
|
|
|
|
handler = logging.StreamHandler()
|
|
|
|
|
|
|
|
if TqdmLoggingHandler:
|
|
|
|
handler = TqdmLoggingHandler(handler)
|
|
|
|
|
|
|
|
formatter = logging.Formatter(
|
|
|
|
'%(asctime)s %(levelname)s [%(name)s] %(message)s',
|
|
|
|
'%Y-%m-%d %H:%M:%S',
|
|
|
|
)
|
2023-11-16 12:43:59 -07:00
|
|
|
|
2024-01-04 07:13:08 -07:00
|
|
|
handler.setFormatter(formatter)
|
2023-11-16 12:43:59 -07:00
|
|
|
|
2024-01-04 07:13:08 -07:00
|
|
|
log_level = getattr(logging, loglevel.upper(), None) or logging.INFO
|
|
|
|
logging.root.setLevel(log_level)
|
|
|
|
logging.root.addHandler(handler)
|