console.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. """Functions to communicate to the user via console."""
  2. from __future__ import annotations
  3. import contextlib
  4. import inspect
  5. import os
  6. import shutil
  7. import time
  8. from pathlib import Path
  9. from types import FrameType
  10. from rich.console import Console
  11. from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn
  12. from rich.prompt import Prompt
  13. from reflex.constants import LogLevel
  14. from reflex.constants.base import Reflex
  15. from reflex.utils.decorator import once
  16. # Console for pretty printing.
  17. _console = Console()
  18. # The current log level.
  19. _LOG_LEVEL = LogLevel.INFO
  20. # Deprecated features who's warning has been printed.
  21. _EMITTED_DEPRECATION_WARNINGS = set()
  22. # Info messages which have been printed.
  23. _EMITTED_INFO = set()
  24. # Warnings which have been printed.
  25. _EMIITED_WARNINGS = set()
  26. # Errors which have been printed.
  27. _EMITTED_ERRORS = set()
  28. # Success messages which have been printed.
  29. _EMITTED_SUCCESS = set()
  30. # Debug messages which have been printed.
  31. _EMITTED_DEBUG = set()
  32. # Logs which have been printed.
  33. _EMITTED_LOGS = set()
  34. # Prints which have been printed.
  35. _EMITTED_PRINTS = set()
  36. def set_log_level(log_level: LogLevel | None):
  37. """Set the log level.
  38. Args:
  39. log_level: The log level to set.
  40. Raises:
  41. TypeError: If the log level is a string.
  42. """
  43. if log_level is None:
  44. return
  45. if not isinstance(log_level, LogLevel):
  46. msg = f"log_level must be a LogLevel enum value, got {log_level} of type {type(log_level)} instead."
  47. raise TypeError(msg)
  48. global _LOG_LEVEL
  49. if log_level != _LOG_LEVEL:
  50. # Set the loglevel persistenly for subprocesses.
  51. os.environ["REFLEX_LOGLEVEL"] = log_level.value
  52. _LOG_LEVEL = log_level
  53. def is_debug() -> bool:
  54. """Check if the log level is debug.
  55. Returns:
  56. True if the log level is debug.
  57. """
  58. return _LOG_LEVEL <= LogLevel.DEBUG
  59. def print(msg: str, dedupe: bool = False, **kwargs):
  60. """Print a message.
  61. Args:
  62. msg: The message to print.
  63. dedupe: If True, suppress multiple console logs of print message.
  64. kwargs: Keyword arguments to pass to the print function.
  65. """
  66. if dedupe:
  67. if msg in _EMITTED_PRINTS:
  68. return
  69. _EMITTED_PRINTS.add(msg)
  70. _console.print(msg, **kwargs)
  71. @once
  72. def log_file_console():
  73. """Create a console that logs to a file.
  74. Returns:
  75. A Console object that logs to a file.
  76. """
  77. from reflex.environment import environment
  78. if not (env_log_file := environment.REFLEX_LOG_FILE.get()):
  79. subseconds = int((time.time() % 1) * 1000)
  80. timestamp = time.strftime("%Y-%m-%d_%H-%M-%S") + f"_{subseconds:03d}"
  81. log_file = Reflex.DIR / "logs" / (timestamp + ".log")
  82. log_file.parent.mkdir(parents=True, exist_ok=True)
  83. else:
  84. log_file = env_log_file
  85. if log_file.exists():
  86. log_file.unlink()
  87. log_file.touch()
  88. return Console(file=log_file.open("a", encoding="utf-8"))
  89. @once
  90. def should_use_log_file_console() -> bool:
  91. """Check if the log file console should be used.
  92. Returns:
  93. True if the log file console should be used, False otherwise.
  94. """
  95. from reflex.environment import environment
  96. return environment.REFLEX_ENABLE_FULL_LOGGING.get()
  97. def print_to_log_file(msg: str, dedupe: bool = False, **kwargs):
  98. """Print a message to the log file.
  99. Args:
  100. msg: The message to print.
  101. dedupe: If True, suppress multiple console logs of print message.
  102. kwargs: Keyword arguments to pass to the print function.
  103. """
  104. log_file_console().print(msg, **kwargs)
  105. def debug(msg: str, dedupe: bool = False, **kwargs):
  106. """Print a debug message.
  107. Args:
  108. msg: The debug message.
  109. dedupe: If True, suppress multiple console logs of debug message.
  110. kwargs: Keyword arguments to pass to the print function.
  111. """
  112. if is_debug():
  113. msg_ = f"[purple]Debug: {msg}[/purple]"
  114. if dedupe:
  115. if msg_ in _EMITTED_DEBUG:
  116. return
  117. _EMITTED_DEBUG.add(msg_)
  118. if progress := kwargs.pop("progress", None):
  119. progress.console.print(msg_, **kwargs)
  120. else:
  121. print(msg_, **kwargs)
  122. if should_use_log_file_console() and kwargs.pop("progress", None) is None:
  123. print_to_log_file(f"[purple]Debug: {msg}[/purple]", **kwargs)
  124. def info(msg: str, dedupe: bool = False, **kwargs):
  125. """Print an info message.
  126. Args:
  127. msg: The info message.
  128. dedupe: If True, suppress multiple console logs of info message.
  129. kwargs: Keyword arguments to pass to the print function.
  130. """
  131. if _LOG_LEVEL <= LogLevel.INFO:
  132. if dedupe:
  133. if msg in _EMITTED_INFO:
  134. return
  135. _EMITTED_INFO.add(msg)
  136. print(f"[cyan]Info: {msg}[/cyan]", **kwargs)
  137. if should_use_log_file_console():
  138. print_to_log_file(f"[cyan]Info: {msg}[/cyan]", **kwargs)
  139. def success(msg: str, dedupe: bool = False, **kwargs):
  140. """Print a success message.
  141. Args:
  142. msg: The success message.
  143. dedupe: If True, suppress multiple console logs of success message.
  144. kwargs: Keyword arguments to pass to the print function.
  145. """
  146. if _LOG_LEVEL <= LogLevel.INFO:
  147. if dedupe:
  148. if msg in _EMITTED_SUCCESS:
  149. return
  150. _EMITTED_SUCCESS.add(msg)
  151. print(f"[green]Success: {msg}[/green]", **kwargs)
  152. if should_use_log_file_console():
  153. print_to_log_file(f"[green]Success: {msg}[/green]", **kwargs)
  154. def log(msg: str, dedupe: bool = False, **kwargs):
  155. """Takes a string and logs it to the console.
  156. Args:
  157. msg: The message to log.
  158. dedupe: If True, suppress multiple console logs of log message.
  159. kwargs: Keyword arguments to pass to the print function.
  160. """
  161. if _LOG_LEVEL <= LogLevel.INFO:
  162. if dedupe:
  163. if msg in _EMITTED_LOGS:
  164. return
  165. _EMITTED_LOGS.add(msg)
  166. _console.log(msg, **kwargs)
  167. if should_use_log_file_console():
  168. print_to_log_file(msg, **kwargs)
  169. def rule(title: str, **kwargs):
  170. """Prints a horizontal rule with a title.
  171. Args:
  172. title: The title of the rule.
  173. kwargs: Keyword arguments to pass to the print function.
  174. """
  175. _console.rule(title, **kwargs)
  176. def warn(msg: str, dedupe: bool = False, **kwargs):
  177. """Print a warning message.
  178. Args:
  179. msg: The warning message.
  180. dedupe: If True, suppress multiple console logs of warning message.
  181. kwargs: Keyword arguments to pass to the print function.
  182. """
  183. if _LOG_LEVEL <= LogLevel.WARNING:
  184. if dedupe:
  185. if msg in _EMIITED_WARNINGS:
  186. return
  187. _EMIITED_WARNINGS.add(msg)
  188. print(f"[orange1]Warning: {msg}[/orange1]", **kwargs)
  189. if should_use_log_file_console():
  190. print_to_log_file(f"[orange1]Warning: {msg}[/orange1]", **kwargs)
  191. def _get_first_non_framework_frame() -> FrameType | None:
  192. import click
  193. import typing_extensions
  194. import reflex as rx
  195. # Exclude utility modules that should never be the source of deprecated reflex usage.
  196. exclude_modules = [click, rx, typing_extensions]
  197. exclude_roots = [
  198. p.parent.resolve() if (p := Path(file)).name == "__init__.py" else p.resolve()
  199. for m in exclude_modules
  200. if (file := m.__file__)
  201. ]
  202. # Specifically exclude the reflex cli module.
  203. if reflex_bin := shutil.which(b"reflex"):
  204. exclude_roots.append(Path(reflex_bin.decode()))
  205. frame = inspect.currentframe()
  206. while frame := frame and frame.f_back:
  207. frame_path = Path(inspect.getfile(frame)).resolve()
  208. if not any(frame_path.is_relative_to(root) for root in exclude_roots):
  209. break
  210. return frame
  211. def deprecate(
  212. feature_name: str,
  213. reason: str,
  214. deprecation_version: str,
  215. removal_version: str,
  216. dedupe: bool = True,
  217. **kwargs,
  218. ):
  219. """Print a deprecation warning.
  220. Args:
  221. feature_name: The feature to deprecate.
  222. reason: The reason for deprecation.
  223. deprecation_version: The version the feature was deprecated
  224. removal_version: The version the deprecated feature will be removed
  225. dedupe: If True, suppress multiple console logs of deprecation message.
  226. kwargs: Keyword arguments to pass to the print function.
  227. """
  228. dedupe_key = feature_name
  229. loc = ""
  230. # See if we can find where the deprecation exists in "user code"
  231. origin_frame = _get_first_non_framework_frame()
  232. if origin_frame is not None:
  233. filename = Path(origin_frame.f_code.co_filename)
  234. if filename.is_relative_to(Path.cwd()):
  235. filename = filename.relative_to(Path.cwd())
  236. loc = f"{filename}:{origin_frame.f_lineno}"
  237. dedupe_key = f"{dedupe_key} {loc}"
  238. if dedupe_key not in _EMITTED_DEPRECATION_WARNINGS:
  239. msg = (
  240. f"{feature_name} has been deprecated in version {deprecation_version}. {reason.rstrip('.').lstrip('. ')}. It will be completely "
  241. f"removed in {removal_version}. ({loc})"
  242. )
  243. if _LOG_LEVEL <= LogLevel.WARNING:
  244. print(f"[yellow]DeprecationWarning: {msg}[/yellow]", **kwargs)
  245. if should_use_log_file_console():
  246. print_to_log_file(f"[yellow]DeprecationWarning: {msg}[/yellow]", **kwargs)
  247. if dedupe:
  248. _EMITTED_DEPRECATION_WARNINGS.add(dedupe_key)
  249. def error(msg: str, dedupe: bool = False, **kwargs):
  250. """Print an error message.
  251. Args:
  252. msg: The error message.
  253. dedupe: If True, suppress multiple console logs of error message.
  254. kwargs: Keyword arguments to pass to the print function.
  255. """
  256. if _LOG_LEVEL <= LogLevel.ERROR:
  257. if dedupe:
  258. if msg in _EMITTED_ERRORS:
  259. return
  260. _EMITTED_ERRORS.add(msg)
  261. print(f"[red]{msg}[/red]", **kwargs)
  262. if should_use_log_file_console():
  263. print_to_log_file(f"[red]{msg}[/red]", **kwargs)
  264. def ask(
  265. question: str,
  266. choices: list[str] | None = None,
  267. default: str | None = None,
  268. show_choices: bool = True,
  269. ) -> str | None:
  270. """Takes a prompt question and optionally a list of choices
  271. and returns the user input.
  272. Args:
  273. question: The question to ask the user.
  274. choices: A list of choices to select from.
  275. default: The default option selected.
  276. show_choices: Whether to show the choices.
  277. Returns:
  278. A string with the user input.
  279. """
  280. return Prompt.ask(
  281. question, choices=choices, default=default, show_choices=show_choices
  282. )
  283. def progress():
  284. """Create a new progress bar.
  285. Returns:
  286. A new progress bar.
  287. """
  288. return Progress(
  289. *Progress.get_default_columns()[:-1],
  290. MofNCompleteColumn(),
  291. TimeElapsedColumn(),
  292. )
  293. def status(*args, **kwargs):
  294. """Create a status with a spinner.
  295. Args:
  296. *args: Args to pass to the status.
  297. **kwargs: Kwargs to pass to the status.
  298. Returns:
  299. A new status.
  300. """
  301. return _console.status(*args, **kwargs)
  302. @contextlib.contextmanager
  303. def timing(msg: str):
  304. """Create a context manager to time a block of code.
  305. Args:
  306. msg: The message to display.
  307. Yields:
  308. None.
  309. """
  310. start = time.time()
  311. try:
  312. yield
  313. finally:
  314. debug(f"[white]\\[timing] {msg}: {time.time() - start:.2f}s[/white]")