logger.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 signal
  19. import sys
  20. from string import Template
  21. import yaml
  22. from twisted.logger import STDLibLogObserver, globalLogBeginner
  23. import synapse
  24. from synapse.util.logcontext import LoggingContextFilter
  25. from synapse.util.versionstring import get_version_string
  26. from ._base import Config
  27. DEFAULT_LOG_CONFIG = Template("""
  28. version: 1
  29. formatters:
  30. precise:
  31. format: '%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - \
  32. %(request)s - %(message)s'
  33. filters:
  34. context:
  35. (): synapse.util.logcontext.LoggingContextFilter
  36. request: ""
  37. handlers:
  38. file:
  39. class: logging.handlers.RotatingFileHandler
  40. formatter: precise
  41. filename: ${log_file}
  42. maxBytes: 104857600
  43. backupCount: 10
  44. filters: [context]
  45. encoding: utf8
  46. console:
  47. class: logging.StreamHandler
  48. formatter: precise
  49. filters: [context]
  50. loggers:
  51. synapse:
  52. level: INFO
  53. synapse.storage.SQL:
  54. # beware: increasing this to DEBUG will make synapse log sensitive
  55. # information such as access tokens.
  56. level: INFO
  57. root:
  58. level: INFO
  59. handlers: [file, console]
  60. """)
  61. class LoggingConfig(Config):
  62. def read_config(self, config):
  63. self.verbosity = config.get("verbose", 0)
  64. self.no_redirect_stdio = config.get("no_redirect_stdio", False)
  65. self.log_config = self.abspath(config.get("log_config"))
  66. self.log_file = self.abspath(config.get("log_file"))
  67. def default_config(self, config_dir_path, server_name, **kwargs):
  68. log_config = os.path.join(config_dir_path, server_name + ".log.config")
  69. return """
  70. # A yaml python logging config file
  71. log_config: "%(log_config)s"
  72. """ % locals()
  73. def read_arguments(self, args):
  74. if args.verbose is not None:
  75. self.verbosity = args.verbose
  76. if args.no_redirect_stdio is not None:
  77. self.no_redirect_stdio = args.no_redirect_stdio
  78. if args.log_config is not None:
  79. self.log_config = args.log_config
  80. if args.log_file is not None:
  81. self.log_file = args.log_file
  82. def add_arguments(cls, parser):
  83. logging_group = parser.add_argument_group("logging")
  84. logging_group.add_argument(
  85. '-v', '--verbose', dest="verbose", action='count',
  86. help="The verbosity level. Specify multiple times to increase "
  87. "verbosity. (Ignored if --log-config is specified.)"
  88. )
  89. logging_group.add_argument(
  90. '-f', '--log-file', dest="log_file",
  91. help="File to log to. (Ignored if --log-config is specified.)"
  92. )
  93. logging_group.add_argument(
  94. '--log-config', dest="log_config", default=None,
  95. help="Python logging config file"
  96. )
  97. logging_group.add_argument(
  98. '-n', '--no-redirect-stdio',
  99. action='store_true', default=None,
  100. help="Do not redirect stdout/stderr to the log"
  101. )
  102. def generate_files(self, config):
  103. log_config = config.get("log_config")
  104. if log_config and not os.path.exists(log_config):
  105. log_file = self.abspath("homeserver.log")
  106. with open(log_config, "w") as log_config_file:
  107. log_config_file.write(
  108. DEFAULT_LOG_CONFIG.substitute(log_file=log_file)
  109. )
  110. def setup_logging(config, use_worker_options=False):
  111. """ Set up python logging
  112. Args:
  113. config (LoggingConfig | synapse.config.workers.WorkerConfig):
  114. configuration data
  115. use_worker_options (bool): True to use 'worker_log_config' and
  116. 'worker_log_file' options instead of 'log_config' and 'log_file'.
  117. """
  118. log_config = (config.worker_log_config if use_worker_options
  119. else config.log_config)
  120. log_file = (config.worker_log_file if use_worker_options
  121. else config.log_file)
  122. log_format = (
  123. "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s"
  124. " - %(message)s"
  125. )
  126. if log_config is None:
  127. # We don't have a logfile, so fall back to the 'verbosity' param from
  128. # the config or cmdline. (Note that we generate a log config for new
  129. # installs, so this will be an unusual case)
  130. level = logging.INFO
  131. level_for_storage = logging.INFO
  132. if config.verbosity:
  133. level = logging.DEBUG
  134. if config.verbosity > 1:
  135. level_for_storage = logging.DEBUG
  136. logger = logging.getLogger('')
  137. logger.setLevel(level)
  138. logging.getLogger('synapse.storage.SQL').setLevel(level_for_storage)
  139. formatter = logging.Formatter(log_format)
  140. if log_file:
  141. # TODO: Customisable file size / backup count
  142. handler = logging.handlers.RotatingFileHandler(
  143. log_file, maxBytes=(1000 * 1000 * 100), backupCount=3,
  144. encoding='utf8'
  145. )
  146. def sighup(signum, stack):
  147. logger.info("Closing log file due to SIGHUP")
  148. handler.doRollover()
  149. logger.info("Opened new log file due to SIGHUP")
  150. else:
  151. handler = logging.StreamHandler()
  152. def sighup(signum, stack):
  153. pass
  154. handler.setFormatter(formatter)
  155. handler.addFilter(LoggingContextFilter(request=""))
  156. logger.addHandler(handler)
  157. else:
  158. def load_log_config():
  159. with open(log_config, 'r') as f:
  160. logging.config.dictConfig(yaml.load(f))
  161. def sighup(signum, stack):
  162. # it might be better to use a file watcher or something for this.
  163. load_log_config()
  164. logging.info("Reloaded log config from %s due to SIGHUP", log_config)
  165. load_log_config()
  166. # TODO(paul): obviously this is a terrible mechanism for
  167. # stealing SIGHUP, because it means no other part of synapse
  168. # can use it instead. If we want to catch SIGHUP anywhere
  169. # else as well, I'd suggest we find a nicer way to broadcast
  170. # it around.
  171. if getattr(signal, "SIGHUP"):
  172. signal.signal(signal.SIGHUP, sighup)
  173. # make sure that the first thing we log is a thing we can grep backwards
  174. # for
  175. logging.warn("***** STARTING SERVER *****")
  176. logging.warn(
  177. "Server %s version %s",
  178. sys.argv[0], get_version_string(synapse),
  179. )
  180. logging.info("Server hostname: %s", config.server_name)
  181. # It's critical to point twisted's internal logging somewhere, otherwise it
  182. # stacks up and leaks kup to 64K object;
  183. # see: https://twistedmatrix.com/trac/ticket/8164
  184. #
  185. # Routing to the python logging framework could be a performance problem if
  186. # the handlers blocked for a long time as python.logging is a blocking API
  187. # see https://twistedmatrix.com/documents/current/core/howto/logger.html
  188. # filed as https://github.com/matrix-org/synapse/issues/1727
  189. #
  190. # However this may not be too much of a problem if we are just writing to a file.
  191. observer = STDLibLogObserver()
  192. def _log(event):
  193. if "log_text" in event:
  194. if event["log_text"].startswith("DNSDatagramProtocol starting on "):
  195. return
  196. if event["log_text"].startswith("(UDP Port "):
  197. return
  198. if event["log_text"].startswith("Timing out client"):
  199. return
  200. return observer(event)
  201. globalLogBeginner.beginLoggingTo(
  202. [_log],
  203. redirectStandardIO=not config.no_redirect_stdio,
  204. )