2023-08-10 01:49:33 +08:00
|
|
|
import logging
|
2024-01-04 22:13:08 +08:00
|
|
|
import os
|
2023-08-10 01:49:33 +08:00
|
|
|
|
2023-11-17 03:43:59 +08:00
|
|
|
try:
|
2024-01-04 22:13:08 +08:00
|
|
|
from tqdm import tqdm
|
|
|
|
|
2023-11-17 00:20:33 +08:00
|
|
|
|
2023-11-17 03:43:59 +08:00
|
|
|
class TqdmLoggingHandler(logging.Handler):
|
2024-01-04 22:13:08 +08:00
|
|
|
def __init__(self, fallback_handler: logging.Handler):
|
|
|
|
super().__init__()
|
|
|
|
self.fallback_handler = fallback_handler
|
2023-11-17 00:20:33 +08:00
|
|
|
|
2023-11-17 03:43:59 +08:00
|
|
|
def emit(self, record):
|
|
|
|
try:
|
2024-01-04 22:13:08 +08: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-17 03:43:59 +08:00
|
|
|
except Exception:
|
2024-01-04 22:13:08 +08:00
|
|
|
self.fallback_handler.emit(record)
|
2023-11-17 03:43:59 +08:00
|
|
|
|
|
|
|
except ImportError:
|
2024-01-04 22:13:08 +08:00
|
|
|
TqdmLoggingHandler = None
|
|
|
|
|
2023-08-10 01:49:33 +08:00
|
|
|
|
|
|
|
def setup_logging(loglevel):
|
|
|
|
if loglevel is None:
|
|
|
|
loglevel = os.environ.get("SD_WEBUI_LOG_LEVEL")
|
|
|
|
|
2024-01-04 22:13:08 +08: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-17 03:43:59 +08:00
|
|
|
|
2024-01-04 22:13:08 +08:00
|
|
|
handler.setFormatter(formatter)
|
2023-11-17 03:43:59 +08:00
|
|
|
|
2024-01-04 22:13:08 +08:00
|
|
|
log_level = getattr(logging, loglevel.upper(), None) or logging.INFO
|
|
|
|
logging.root.setLevel(log_level)
|
|
|
|
logging.root.addHandler(handler)
|