feat: add ftRichColorHandler

This commit is contained in:
Matthias
2024-12-29 10:11:00 +01:00
parent af28656138
commit 3e5ab8549f
3 changed files with 48 additions and 9 deletions

View File

@@ -4,14 +4,17 @@ from logging.handlers import RotatingFileHandler, SysLogHandler
from pathlib import Path from pathlib import Path
from rich.console import Console from rich.console import Console
from rich.logging import RichHandler
from freqtrade.constants import Config from freqtrade.constants import Config
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.loggers.buffering_handler import FTBufferingHandler from freqtrade.loggers.buffering_handler import FTBufferingHandler
from freqtrade.loggers.ft_rich_handler import FtRichHandler
from freqtrade.loggers.set_log_levels import set_loggers from freqtrade.loggers.set_log_levels import set_loggers
# from freqtrade.loggers.std_err_stream_handler import FTStdErrStreamHandler
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
LOGFORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" LOGFORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
@@ -37,13 +40,16 @@ def setup_logging_pre() -> None:
logging handlers after the real initialization, because we don't know which logging handlers after the real initialization, because we don't know which
ones the user desires beforehand. ones the user desires beforehand.
""" """
rh = RichHandler(console=error_console) rh = FtRichHandler(console=error_console)
rh.setFormatter(Formatter("%(message)s")) rh.setFormatter(Formatter("%(message)s"))
logging.basicConfig( logging.basicConfig(
level=logging.INFO, level=logging.INFO,
format=LOGFORMAT, format=LOGFORMAT,
# handlers=[FTStdErrStreamHandler(), bufferHandler] handlers=[
handlers=[rh, bufferHandler], # FTStdErrStreamHandler(),
rh,
bufferHandler,
],
) )

View File

@@ -0,0 +1,33 @@
from datetime import datetime
from logging import Handler
from typing import Any
from rich.text import Text
class FtRichHandler(Handler):
def __init__(self, console, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._console = console
def emit(self, record):
try:
msg = self.format(record)
# Format log message
log_time = Text(
datetime.fromtimestamp(record.created).strftime("%Y-%m-%d %H:%M:%S,%f")[:-3],
style="gray46",
)
name = Text(record.name)
log_level = Text(record.levelname, style=f"logging.level.{record.levelname.lower()}")
gray_sep = Text(" - ", style="gray46")
self._console.print(
Text() + log_time + gray_sep + name + gray_sep + log_level + gray_sep + msg
)
self.flush()
except RecursionError:
raise
except Exception:
self.handleError(record)

View File

@@ -16,11 +16,11 @@ from typing import Any
import rapidjson import rapidjson
from joblib import Parallel, cpu_count, delayed, wrap_non_picklable_objects from joblib import Parallel, cpu_count, delayed, wrap_non_picklable_objects
from joblib.externals import cloudpickle from joblib.externals import cloudpickle
from rich.console import Console
from freqtrade.constants import FTHYPT_FILEVERSION, LAST_BT_RESULT_FN, Config from freqtrade.constants import FTHYPT_FILEVERSION, LAST_BT_RESULT_FN, Config
from freqtrade.enums import HyperoptState from freqtrade.enums import HyperoptState
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.loggers import error_console
from freqtrade.misc import file_dump_json, plural from freqtrade.misc import file_dump_json, plural
from freqtrade.optimize.hyperopt.hyperopt_logger import logging_mp_handle, logging_mp_setup from freqtrade.optimize.hyperopt.hyperopt_logger import logging_mp_handle, logging_mp_setup
from freqtrade.optimize.hyperopt.hyperopt_optimizer import HyperOptimizer from freqtrade.optimize.hyperopt.hyperopt_optimizer import HyperOptimizer
@@ -281,13 +281,13 @@ class Hyperopt:
with Parallel(n_jobs=config_jobs) as parallel: with Parallel(n_jobs=config_jobs) as parallel:
jobs = parallel._effective_n_jobs() jobs = parallel._effective_n_jobs()
logger.info(f"Effective number of parallel workers used: {jobs}") logger.info(f"Effective number of parallel workers used: {jobs}")
console = Console( # console = Console(
color_system="auto" if self.print_colorized else None, # color_system="auto" if self.print_colorized else None,
) # )
# Define progressbar # Define progressbar
with get_progress_tracker( with get_progress_tracker(
console=console, console=error_console,
cust_callables=[self._hyper_out], cust_callables=[self._hyper_out],
) as pbar: ) as pbar:
task = pbar.add_task("Epochs", total=self.total_epochs) task = pbar.add_task("Epochs", total=self.total_epochs)