__init__.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=missing-module-docstring, cyclic-import
  3. import sys
  4. import os
  5. from os.path import dirname, abspath
  6. import logging
  7. import searx.unixthreadname
  8. import searx.settings_loader
  9. from searx.settings_defaults import SCHEMA, apply_schema
  10. # Debug
  11. LOG_FORMAT_DEBUG = '%(levelname)-7s %(name)-30.30s: %(message)s'
  12. # Production
  13. LOG_FORMAT_PROD = '%(asctime)-15s %(levelname)s:%(name)s: %(message)s'
  14. LOG_LEVEL_PROD = logging.WARNING
  15. searx_dir = abspath(dirname(__file__))
  16. searx_parent_dir = abspath(dirname(dirname(__file__)))
  17. settings = {}
  18. searx_debug = False
  19. logger = logging.getLogger('searx')
  20. _unset = object()
  21. def init_settings():
  22. """Initialize global ``settings`` and ``searx_debug`` variables and
  23. ``logger`` from ``SEARXNG_SETTINGS_PATH``.
  24. """
  25. global settings, searx_debug # pylint: disable=global-variable-not-assigned
  26. cfg, msg = searx.settings_loader.load_settings(load_user_settings=True)
  27. cfg = cfg or {}
  28. apply_schema(cfg, SCHEMA, [])
  29. settings.clear()
  30. settings.update(cfg)
  31. searx_debug = settings['general']['debug']
  32. if searx_debug:
  33. _logging_config_debug()
  34. else:
  35. logging.basicConfig(level=LOG_LEVEL_PROD, format=LOG_FORMAT_PROD)
  36. logging.root.setLevel(level=LOG_LEVEL_PROD)
  37. logging.getLogger('werkzeug').setLevel(level=LOG_LEVEL_PROD)
  38. logger.info(msg)
  39. # log max_request_timeout
  40. max_request_timeout = settings['outgoing']['max_request_timeout']
  41. if max_request_timeout is None:
  42. logger.info('max_request_timeout=%s', repr(max_request_timeout))
  43. else:
  44. logger.info('max_request_timeout=%i second(s)', max_request_timeout)
  45. if settings['server']['public_instance']:
  46. logger.warning(
  47. "Be aware you have activated features intended only for public instances. "
  48. "This force the usage of the limiter and link_token / "
  49. "see https://docs.searxng.org/admin/searx.limiter.html"
  50. )
  51. def get_setting(name, default=_unset):
  52. """Returns the value to which ``name`` point. If there is no such name in the
  53. settings and the ``default`` is unset, a :py:obj:`KeyError` is raised.
  54. """
  55. value = settings
  56. for a in name.split('.'):
  57. if isinstance(value, dict):
  58. value = value.get(a, _unset)
  59. else:
  60. value = _unset
  61. if value is _unset:
  62. if default is _unset:
  63. raise KeyError(name)
  64. value = default
  65. break
  66. return value
  67. def _is_color_terminal():
  68. if os.getenv('TERM') in ('dumb', 'unknown'):
  69. return False
  70. return sys.stdout.isatty()
  71. def _logging_config_debug():
  72. try:
  73. import coloredlogs # pylint: disable=import-outside-toplevel
  74. except ImportError:
  75. coloredlogs = None
  76. log_level = os.environ.get('SEARXNG_DEBUG_LOG_LEVEL', 'DEBUG')
  77. if coloredlogs and _is_color_terminal():
  78. level_styles = {
  79. 'spam': {'color': 'green', 'faint': True},
  80. 'debug': {},
  81. 'notice': {'color': 'magenta'},
  82. 'success': {'bold': True, 'color': 'green'},
  83. 'info': {'bold': True, 'color': 'cyan'},
  84. 'warning': {'color': 'yellow'},
  85. 'error': {'color': 'red'},
  86. 'critical': {'bold': True, 'color': 'red'},
  87. }
  88. field_styles = {
  89. 'asctime': {'color': 'green'},
  90. 'hostname': {'color': 'magenta'},
  91. 'levelname': {'color': 8},
  92. 'name': {'color': 8},
  93. 'programname': {'color': 'cyan'},
  94. 'username': {'color': 'yellow'},
  95. }
  96. coloredlogs.install(level=log_level, level_styles=level_styles, field_styles=field_styles, fmt=LOG_FORMAT_DEBUG)
  97. else:
  98. logging.basicConfig(level=logging.getLevelName(log_level), format=LOG_FORMAT_DEBUG)
  99. init_settings()