logger.py 11 KB

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