logger.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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.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. @implementer(ILogObserver)
  194. def _log(event: dict) -> None:
  195. if "log_text" in event:
  196. if event["log_text"].startswith("DNSDatagramProtocol starting on "):
  197. return
  198. if event["log_text"].startswith("(UDP Port "):
  199. return
  200. if event["log_text"].startswith("Timing out client"):
  201. return
  202. # this is a workaround to make sure we don't get stack overflows when the
  203. # logging system raises an error which is written to stderr which is redirected
  204. # to the logging system, etc.
  205. if getattr(threadlocal, "active", False):
  206. # write the text of the event, if any, to the *real* stderr (which may
  207. # be redirected to /dev/null, but there's not much we can do)
  208. try:
  209. event_text = eventAsText(event)
  210. print("logging during logging: %s" % event_text, file=sys.__stderr__)
  211. except Exception:
  212. # gah.
  213. pass
  214. return
  215. try:
  216. threadlocal.active = True
  217. return observer(event)
  218. finally:
  219. threadlocal.active = False
  220. logBeginner.beginLoggingTo([_log], redirectStandardIO=False)
  221. def _load_logging_config(log_config_path: str) -> None:
  222. """
  223. Configure logging from a log config path.
  224. """
  225. with open(log_config_path, "rb") as f:
  226. log_config = yaml.safe_load(f.read())
  227. if not log_config:
  228. logging.warning("Loaded a blank logging config?")
  229. # If the old structured logging configuration is being used, convert it to
  230. # the new style configuration.
  231. if "structured" in log_config and log_config.get("structured"):
  232. log_config = setup_structured_logging(log_config)
  233. logging.config.dictConfig(log_config)
  234. def _reload_logging_config(log_config_path):
  235. """
  236. Reload the log configuration from the file and apply it.
  237. """
  238. # If no log config path was given, it cannot be reloaded.
  239. if log_config_path is None:
  240. return
  241. _load_logging_config(log_config_path)
  242. logging.info("Reloaded log config from %s due to SIGHUP", log_config_path)
  243. def setup_logging(
  244. hs, config, use_worker_options=False, logBeginner: LogBeginner = globalLogBeginner
  245. ) -> None:
  246. """
  247. Set up the logging subsystem.
  248. Args:
  249. config (LoggingConfig | synapse.config.worker.WorkerConfig):
  250. configuration data
  251. use_worker_options (bool): True to use the 'worker_log_config' option
  252. instead of 'log_config'.
  253. logBeginner: The Twisted logBeginner to use.
  254. """
  255. log_config_path = (
  256. config.worker_log_config if use_worker_options else config.log_config
  257. )
  258. # Perform one-time logging configuration.
  259. _setup_stdlib_logging(config, log_config_path, logBeginner=logBeginner)
  260. # Add a SIGHUP handler to reload the logging configuration, if one is available.
  261. from synapse.app import _base as appbase
  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())