logger.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 STDLibLogObserver, globalLogBeginner
  22. import synapse
  23. from synapse.app import _base as appbase
  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. ## Logging ##
  71. # A yaml python logging config file
  72. #
  73. log_config: "%(log_config)s"
  74. """ % locals()
  75. def read_arguments(self, args):
  76. if args.verbose is not None:
  77. self.verbosity = args.verbose
  78. if args.no_redirect_stdio is not None:
  79. self.no_redirect_stdio = args.no_redirect_stdio
  80. if args.log_config is not None:
  81. self.log_config = args.log_config
  82. if args.log_file is not None:
  83. self.log_file = args.log_file
  84. def add_arguments(cls, parser):
  85. logging_group = parser.add_argument_group("logging")
  86. logging_group.add_argument(
  87. '-v', '--verbose', dest="verbose", action='count',
  88. help="The verbosity level. Specify multiple times to increase "
  89. "verbosity. (Ignored if --log-config is specified.)"
  90. )
  91. logging_group.add_argument(
  92. '-f', '--log-file', dest="log_file",
  93. help="File to log to. (Ignored if --log-config is specified.)"
  94. )
  95. logging_group.add_argument(
  96. '--log-config', dest="log_config", default=None,
  97. help="Python logging config file"
  98. )
  99. logging_group.add_argument(
  100. '-n', '--no-redirect-stdio',
  101. action='store_true', default=None,
  102. help="Do not redirect stdout/stderr to the log"
  103. )
  104. def generate_files(self, config):
  105. log_config = config.get("log_config")
  106. if log_config and not os.path.exists(log_config):
  107. log_file = self.abspath("homeserver.log")
  108. with open(log_config, "w") as log_config_file:
  109. log_config_file.write(
  110. DEFAULT_LOG_CONFIG.substitute(log_file=log_file)
  111. )
  112. def setup_logging(config, use_worker_options=False):
  113. """ Set up python logging
  114. Args:
  115. config (LoggingConfig | synapse.config.workers.WorkerConfig):
  116. configuration data
  117. use_worker_options (bool): True to use 'worker_log_config' and
  118. 'worker_log_file' options instead of 'log_config' and 'log_file'.
  119. register_sighup (func | None): Function to call to register a
  120. sighup handler.
  121. """
  122. log_config = (config.worker_log_config if use_worker_options
  123. else config.log_config)
  124. log_file = (config.worker_log_file if use_worker_options
  125. else config.log_file)
  126. log_format = (
  127. "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s"
  128. " - %(message)s"
  129. )
  130. if log_config is None:
  131. # We don't have a logfile, so fall back to the 'verbosity' param from
  132. # the config or cmdline. (Note that we generate a log config for new
  133. # installs, so this will be an unusual case)
  134. level = logging.INFO
  135. level_for_storage = logging.INFO
  136. if config.verbosity:
  137. level = logging.DEBUG
  138. if config.verbosity > 1:
  139. level_for_storage = logging.DEBUG
  140. logger = logging.getLogger('')
  141. logger.setLevel(level)
  142. logging.getLogger('synapse.storage.SQL').setLevel(level_for_storage)
  143. formatter = logging.Formatter(log_format)
  144. if log_file:
  145. # TODO: Customisable file size / backup count
  146. handler = logging.handlers.RotatingFileHandler(
  147. log_file, maxBytes=(1000 * 1000 * 100), backupCount=3,
  148. encoding='utf8'
  149. )
  150. def sighup(signum, stack):
  151. logger.info("Closing log file due to SIGHUP")
  152. handler.doRollover()
  153. logger.info("Opened new log file due to SIGHUP")
  154. else:
  155. handler = logging.StreamHandler()
  156. def sighup(*args):
  157. pass
  158. handler.setFormatter(formatter)
  159. handler.addFilter(LoggingContextFilter(request=""))
  160. logger.addHandler(handler)
  161. else:
  162. def load_log_config():
  163. with open(log_config, 'r') as f:
  164. logging.config.dictConfig(yaml.load(f))
  165. def sighup(*args):
  166. # it might be better to use a file watcher or something for this.
  167. load_log_config()
  168. logging.info("Reloaded log config from %s due to SIGHUP", log_config)
  169. load_log_config()
  170. appbase.register_sighup(sighup)
  171. # make sure that the first thing we log is a thing we can grep backwards
  172. # for
  173. logging.warn("***** STARTING SERVER *****")
  174. logging.warn(
  175. "Server %s version %s",
  176. sys.argv[0], get_version_string(synapse),
  177. )
  178. logging.info("Server hostname: %s", config.server_name)
  179. # It's critical to point twisted's internal logging somewhere, otherwise it
  180. # stacks up and leaks kup to 64K object;
  181. # see: https://twistedmatrix.com/trac/ticket/8164
  182. #
  183. # Routing to the python logging framework could be a performance problem if
  184. # the handlers blocked for a long time as python.logging is a blocking API
  185. # see https://twistedmatrix.com/documents/current/core/howto/logger.html
  186. # filed as https://github.com/matrix-org/synapse/issues/1727
  187. #
  188. # However this may not be too much of a problem if we are just writing to a file.
  189. observer = STDLibLogObserver()
  190. def _log(event):
  191. if "log_text" in event:
  192. if event["log_text"].startswith("DNSDatagramProtocol starting on "):
  193. return
  194. if event["log_text"].startswith("(UDP Port "):
  195. return
  196. if event["log_text"].startswith("Timing out client"):
  197. return
  198. return observer(event)
  199. globalLogBeginner.beginLoggingTo(
  200. [_log],
  201. redirectStandardIO=not config.no_redirect_stdio,
  202. )
  203. if not config.no_redirect_stdio:
  204. print("Redirected stdout/stderr to logs")