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.
 
 
 
 
 
 

328 lines
11 KiB

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