logger.py 11 KB

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