You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

351 regels
12 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2021 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import argparse
  16. import logging
  17. import logging.config
  18. import os
  19. import sys
  20. import threading
  21. from string import Template
  22. from typing import TYPE_CHECKING, Any, Dict, Optional
  23. import yaml
  24. from zope.interface import implementer
  25. from twisted.logger import (
  26. ILogObserver,
  27. LogBeginner,
  28. STDLibLogObserver,
  29. eventAsText,
  30. globalLogBeginner,
  31. )
  32. from synapse.logging.context import LoggingContextFilter
  33. from synapse.logging.filter import MetadataFilter
  34. from synapse.types import JsonDict
  35. from ..util import SYNAPSE_VERSION
  36. from ._base import Config, ConfigError
  37. if TYPE_CHECKING:
  38. from synapse.config.homeserver import HomeServerConfig
  39. from synapse.server import HomeServer
  40. DEFAULT_LOG_CONFIG = Template(
  41. """\
  42. # Log configuration for Synapse.
  43. #
  44. # This is a YAML file containing a standard Python logging configuration
  45. # dictionary. See [1] for details on the valid settings.
  46. #
  47. # Synapse also supports structured logging for machine readable logs which can
  48. # be ingested by ELK stacks. See [2] for details.
  49. #
  50. # [1]: https://docs.python.org/3.7/library/logging.config.html#configuration-dictionary-schema
  51. # [2]: https://matrix-org.github.io/synapse/latest/structured_logging.html
  52. version: 1
  53. formatters:
  54. precise:
  55. format: '%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - \
  56. %(request)s - %(message)s'
  57. handlers:
  58. file:
  59. class: logging.handlers.TimedRotatingFileHandler
  60. formatter: precise
  61. filename: ${log_file}
  62. when: midnight
  63. backupCount: 3 # Does not include the current log file.
  64. encoding: utf8
  65. # Default to buffering writes to log file for efficiency.
  66. # WARNING/ERROR logs will still be flushed immediately, but there will be a
  67. # delay (of up to `period` seconds, or until the buffer is full with
  68. # `capacity` messages) before INFO/DEBUG logs get written.
  69. buffer:
  70. class: synapse.logging.handlers.PeriodicallyFlushingMemoryHandler
  71. target: file
  72. # The capacity is the maximum number of log lines that are buffered
  73. # before being written to disk. Increasing this will lead to better
  74. # performance, at the expensive of it taking longer for log lines to
  75. # be written to disk.
  76. # This parameter is required.
  77. capacity: 10
  78. # Logs with a level at or above the flush level will cause the buffer to
  79. # be flushed immediately.
  80. # Default value: 40 (ERROR)
  81. # Other values: 50 (CRITICAL), 30 (WARNING), 20 (INFO), 10 (DEBUG)
  82. flushLevel: 30 # Flush immediately for WARNING logs and higher
  83. # The period of time, in seconds, between forced flushes.
  84. # Messages will not be delayed for longer than this time.
  85. # Default value: 5 seconds
  86. period: 5
  87. # A handler that writes logs to stderr. Unused by default, but can be used
  88. # instead of "buffer" and "file" in the logger handlers.
  89. console:
  90. class: logging.StreamHandler
  91. formatter: precise
  92. loggers:
  93. synapse.storage.SQL:
  94. # beware: increasing this to DEBUG will make synapse log sensitive
  95. # information such as access tokens.
  96. level: INFO
  97. root:
  98. level: INFO
  99. # Write logs to the `buffer` handler, which will buffer them together in memory,
  100. # then write them to a file.
  101. #
  102. # Replace "buffer" with "console" to log to stderr instead. (Note that you'll
  103. # also need to update the configuration for the `twisted` logger above, in
  104. # this case.)
  105. #
  106. handlers: [buffer]
  107. disable_existing_loggers: false
  108. """
  109. )
  110. LOG_FILE_ERROR = """\
  111. Support for the log_file configuration option and --log-file command-line option was
  112. removed in Synapse 1.3.0. You should instead set up a separate log configuration file.
  113. """
  114. STRUCTURED_ERROR = """\
  115. Support for the structured configuration option was removed in Synapse 1.54.0.
  116. You should instead use the standard logging configuration. See
  117. https://matrix-org.github.io/synapse/v1.54/structured_logging.html
  118. """
  119. class LoggingConfig(Config):
  120. section = "logging"
  121. def read_config(self, config: JsonDict, **kwargs: Any) -> None:
  122. if config.get("log_file"):
  123. raise ConfigError(LOG_FILE_ERROR)
  124. self.log_config = self.abspath(config.get("log_config"))
  125. self.no_redirect_stdio = config.get("no_redirect_stdio", False)
  126. def generate_config_section(
  127. self, config_dir_path: str, server_name: str, **kwargs: Any
  128. ) -> str:
  129. log_config = os.path.join(config_dir_path, server_name + ".log.config")
  130. return (
  131. """\
  132. log_config: "%(log_config)s"
  133. """
  134. % locals()
  135. )
  136. def read_arguments(self, args: argparse.Namespace) -> None:
  137. if args.no_redirect_stdio is not None:
  138. self.no_redirect_stdio = args.no_redirect_stdio
  139. if args.log_file is not None:
  140. raise ConfigError(LOG_FILE_ERROR)
  141. @staticmethod
  142. def add_arguments(parser: argparse.ArgumentParser) -> None:
  143. logging_group = parser.add_argument_group("logging")
  144. logging_group.add_argument(
  145. "-n",
  146. "--no-redirect-stdio",
  147. action="store_true",
  148. default=None,
  149. help="Do not redirect stdout/stderr to the log",
  150. )
  151. logging_group.add_argument(
  152. "-f",
  153. "--log-file",
  154. dest="log_file",
  155. help=argparse.SUPPRESS,
  156. )
  157. def generate_files(self, config: Dict[str, Any], config_dir_path: str) -> None:
  158. log_config = config.get("log_config")
  159. if log_config and not os.path.exists(log_config):
  160. log_file = self.abspath("homeserver.log")
  161. print(
  162. "Generating log config file %s which will log to %s"
  163. % (log_config, log_file)
  164. )
  165. with open(log_config, "w") as log_config_file:
  166. log_config_file.write(DEFAULT_LOG_CONFIG.substitute(log_file=log_file))
  167. def _setup_stdlib_logging(
  168. config: "HomeServerConfig", log_config_path: Optional[str], logBeginner: LogBeginner
  169. ) -> None:
  170. """
  171. Set up Python standard library logging.
  172. """
  173. if log_config_path is None:
  174. log_format = (
  175. "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s"
  176. " - %(message)s"
  177. )
  178. logger = logging.getLogger("")
  179. logger.setLevel(logging.INFO)
  180. logging.getLogger("synapse.storage.SQL").setLevel(logging.INFO)
  181. formatter = logging.Formatter(log_format)
  182. handler = logging.StreamHandler()
  183. handler.setFormatter(formatter)
  184. logger.addHandler(handler)
  185. else:
  186. # Load the logging configuration.
  187. _load_logging_config(log_config_path)
  188. # We add a log record factory that runs all messages through the
  189. # LoggingContextFilter so that we get the context *at the time we log*
  190. # rather than when we write to a handler. This can be done in config using
  191. # filter options, but care must when using e.g. MemoryHandler to buffer
  192. # writes.
  193. log_context_filter = LoggingContextFilter()
  194. log_metadata_filter = MetadataFilter({"server_name": config.server.server_name})
  195. old_factory = logging.getLogRecordFactory()
  196. def factory(*args: Any, **kwargs: Any) -> logging.LogRecord:
  197. record = old_factory(*args, **kwargs)
  198. log_context_filter.filter(record)
  199. log_metadata_filter.filter(record)
  200. return record
  201. logging.setLogRecordFactory(factory)
  202. # Route Twisted's native logging through to the standard library logging
  203. # system.
  204. observer = STDLibLogObserver()
  205. threadlocal = threading.local()
  206. @implementer(ILogObserver)
  207. def _log(event: dict) -> None:
  208. if "log_text" in event:
  209. if event["log_text"].startswith("DNSDatagramProtocol starting on "):
  210. return
  211. if event["log_text"].startswith("(UDP Port "):
  212. return
  213. if event["log_text"].startswith("Timing out client"):
  214. return
  215. # this is a workaround to make sure we don't get stack overflows when the
  216. # logging system raises an error which is written to stderr which is redirected
  217. # to the logging system, etc.
  218. if getattr(threadlocal, "active", False):
  219. # write the text of the event, if any, to the *real* stderr (which may
  220. # be redirected to /dev/null, but there's not much we can do)
  221. try:
  222. event_text = eventAsText(event)
  223. print("logging during logging: %s" % event_text, file=sys.__stderr__)
  224. except Exception:
  225. # gah.
  226. pass
  227. return
  228. try:
  229. threadlocal.active = True
  230. return observer(event)
  231. finally:
  232. threadlocal.active = False
  233. logBeginner.beginLoggingTo([_log], redirectStandardIO=False)
  234. def _load_logging_config(log_config_path: str) -> None:
  235. """
  236. Configure logging from a log config path.
  237. """
  238. with open(log_config_path, "rb") as f:
  239. log_config = yaml.safe_load(f.read())
  240. if not log_config:
  241. logging.warning("Loaded a blank logging config?")
  242. # If the old structured logging configuration is being used, raise an error.
  243. if "structured" in log_config and log_config.get("structured"):
  244. raise ConfigError(STRUCTURED_ERROR)
  245. logging.config.dictConfig(log_config)
  246. def _reload_logging_config(log_config_path: Optional[str]) -> None:
  247. """
  248. Reload the log configuration from the file and apply it.
  249. """
  250. # If no log config path was given, it cannot be reloaded.
  251. if log_config_path is None:
  252. return
  253. _load_logging_config(log_config_path)
  254. logging.info("Reloaded log config from %s due to SIGHUP", log_config_path)
  255. def setup_logging(
  256. hs: "HomeServer",
  257. config: "HomeServerConfig",
  258. use_worker_options: bool = False,
  259. logBeginner: LogBeginner = globalLogBeginner,
  260. ) -> None:
  261. """
  262. Set up the logging subsystem.
  263. Args:
  264. config (LoggingConfig | synapse.config.worker.WorkerConfig):
  265. configuration data
  266. use_worker_options (bool): True to use the 'worker_log_config' option
  267. instead of 'log_config'.
  268. logBeginner: The Twisted logBeginner to use.
  269. """
  270. log_config_path = (
  271. config.worker.worker_log_config
  272. if use_worker_options
  273. else config.logging.log_config
  274. )
  275. # Perform one-time logging configuration.
  276. _setup_stdlib_logging(config, log_config_path, logBeginner=logBeginner)
  277. # Add a SIGHUP handler to reload the logging configuration, if one is available.
  278. from synapse.app import _base as appbase
  279. appbase.register_sighup(_reload_logging_config, log_config_path)
  280. # Log immediately so we can grep backwards.
  281. logging.warning("***** STARTING SERVER *****")
  282. logging.warning(
  283. "Server %s version %s",
  284. sys.argv[0],
  285. SYNAPSE_VERSION,
  286. )
  287. logging.info("Server hostname: %s", config.server.server_name)
  288. logging.info("Instance name: %s", hs.get_instance_name())