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.
 
 
 
 
 
 

262 lines
7.7 KiB

  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. from string import Template
  21. import yaml
  22. from twisted.logger import (
  23. ILogObserver,
  24. LogBeginner,
  25. STDLibLogObserver,
  26. globalLogBeginner,
  27. )
  28. import synapse
  29. from synapse.app import _base as appbase
  30. from synapse.logging._structured import (
  31. reload_structured_logging,
  32. setup_structured_logging,
  33. )
  34. from synapse.logging.context import LoggingContextFilter
  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. # [1]: https://docs.python.org/3.7/library/logging.config.html#configuration-dictionary-schema
  45. version: 1
  46. formatters:
  47. precise:
  48. format: '%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - \
  49. %(request)s - %(message)s'
  50. filters:
  51. context:
  52. (): synapse.logging.context.LoggingContextFilter
  53. request: ""
  54. handlers:
  55. file:
  56. class: logging.handlers.RotatingFileHandler
  57. formatter: precise
  58. filename: ${log_file}
  59. maxBytes: 104857600
  60. backupCount: 10
  61. filters: [context]
  62. encoding: utf8
  63. console:
  64. class: logging.StreamHandler
  65. formatter: precise
  66. filters: [context]
  67. loggers:
  68. synapse.storage.SQL:
  69. # beware: increasing this to DEBUG will make synapse log sensitive
  70. # information such as access tokens.
  71. level: INFO
  72. root:
  73. level: INFO
  74. handlers: [file, console]
  75. disable_existing_loggers: false
  76. """
  77. )
  78. LOG_FILE_ERROR = """\
  79. Support for the log_file configuration option and --log-file command-line option was
  80. removed in Synapse 1.3.0. You should instead set up a separate log configuration file.
  81. """
  82. class LoggingConfig(Config):
  83. section = "logging"
  84. def read_config(self, config, **kwargs):
  85. if config.get("log_file"):
  86. raise ConfigError(LOG_FILE_ERROR)
  87. self.log_config = self.abspath(config.get("log_config"))
  88. self.no_redirect_stdio = config.get("no_redirect_stdio", False)
  89. def generate_config_section(self, config_dir_path, server_name, **kwargs):
  90. log_config = os.path.join(config_dir_path, server_name + ".log.config")
  91. return (
  92. """\
  93. ## Logging ##
  94. # A yaml python logging config file as described by
  95. # https://docs.python.org/3.7/library/logging.config.html#configuration-dictionary-schema
  96. #
  97. log_config: "%(log_config)s"
  98. """
  99. % locals()
  100. )
  101. def read_arguments(self, args):
  102. if args.no_redirect_stdio is not None:
  103. self.no_redirect_stdio = args.no_redirect_stdio
  104. if args.log_file is not None:
  105. raise ConfigError(LOG_FILE_ERROR)
  106. @staticmethod
  107. def add_arguments(parser):
  108. logging_group = parser.add_argument_group("logging")
  109. logging_group.add_argument(
  110. "-n",
  111. "--no-redirect-stdio",
  112. action="store_true",
  113. default=None,
  114. help="Do not redirect stdout/stderr to the log",
  115. )
  116. logging_group.add_argument(
  117. "-f", "--log-file", dest="log_file", help=argparse.SUPPRESS,
  118. )
  119. def generate_files(self, config, config_dir_path):
  120. log_config = config.get("log_config")
  121. if log_config and not os.path.exists(log_config):
  122. log_file = self.abspath("homeserver.log")
  123. print(
  124. "Generating log config file %s which will log to %s"
  125. % (log_config, log_file)
  126. )
  127. with open(log_config, "w") as log_config_file:
  128. log_config_file.write(DEFAULT_LOG_CONFIG.substitute(log_file=log_file))
  129. def _setup_stdlib_logging(config, log_config, logBeginner: LogBeginner):
  130. """
  131. Set up Python stdlib logging.
  132. """
  133. if log_config is None:
  134. log_format = (
  135. "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s"
  136. " - %(message)s"
  137. )
  138. logger = logging.getLogger("")
  139. logger.setLevel(logging.INFO)
  140. logging.getLogger("synapse.storage.SQL").setLevel(logging.INFO)
  141. formatter = logging.Formatter(log_format)
  142. handler = logging.StreamHandler()
  143. handler.setFormatter(formatter)
  144. handler.addFilter(LoggingContextFilter(request=""))
  145. logger.addHandler(handler)
  146. else:
  147. logging.config.dictConfig(log_config)
  148. # Route Twisted's native logging through to the standard library logging
  149. # system.
  150. observer = STDLibLogObserver()
  151. def _log(event):
  152. if "log_text" in event:
  153. if event["log_text"].startswith("DNSDatagramProtocol starting on "):
  154. return
  155. if event["log_text"].startswith("(UDP Port "):
  156. return
  157. if event["log_text"].startswith("Timing out client"):
  158. return
  159. return observer(event)
  160. logBeginner.beginLoggingTo([_log], redirectStandardIO=not config.no_redirect_stdio)
  161. if not config.no_redirect_stdio:
  162. print("Redirected stdout/stderr to logs")
  163. return observer
  164. def _reload_stdlib_logging(*args, log_config=None):
  165. logger = logging.getLogger("")
  166. if not log_config:
  167. logger.warning("Reloaded a blank config?")
  168. logging.config.dictConfig(log_config)
  169. def setup_logging(
  170. hs, config, use_worker_options=False, logBeginner: LogBeginner = globalLogBeginner
  171. ) -> ILogObserver:
  172. """
  173. Set up the logging subsystem.
  174. Args:
  175. config (LoggingConfig | synapse.config.workers.WorkerConfig):
  176. configuration data
  177. use_worker_options (bool): True to use the 'worker_log_config' option
  178. instead of 'log_config'.
  179. logBeginner: The Twisted logBeginner to use.
  180. Returns:
  181. The "root" Twisted Logger observer, suitable for sending logs to from a
  182. Logger instance.
  183. """
  184. log_config = config.worker_log_config if use_worker_options else config.log_config
  185. def read_config(*args, callback=None):
  186. if log_config is None:
  187. return None
  188. with open(log_config, "rb") as f:
  189. log_config_body = yaml.safe_load(f.read())
  190. if callback:
  191. callback(log_config=log_config_body)
  192. logging.info("Reloaded log config from %s due to SIGHUP", log_config)
  193. return log_config_body
  194. log_config_body = read_config()
  195. if log_config_body and log_config_body.get("structured") is True:
  196. logger = setup_structured_logging(
  197. hs, config, log_config_body, logBeginner=logBeginner
  198. )
  199. appbase.register_sighup(read_config, callback=reload_structured_logging)
  200. else:
  201. logger = _setup_stdlib_logging(config, log_config_body, logBeginner=logBeginner)
  202. appbase.register_sighup(read_config, callback=_reload_stdlib_logging)
  203. # make sure that the first thing we log is a thing we can grep backwards
  204. # for
  205. logging.warning("***** STARTING SERVER *****")
  206. logging.warning("Server %s version %s", sys.argv[0], get_version_string(synapse))
  207. logging.info("Server hostname: %s", config.server_name)
  208. return logger