logger.py 6.9 KB

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