m2m模型翻译
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.

292 lines
12 KiB

6 months ago
  1. # Easy to use system logging for Python's logging module.
  2. #
  3. # Author: Peter Odding <peter@peterodding.com>
  4. # Last Change: December 10, 2020
  5. # URL: https://coloredlogs.readthedocs.io
  6. """
  7. Easy to use UNIX system logging for Python's :mod:`logging` module.
  8. Admittedly system logging has little to do with colored terminal output, however:
  9. - The `coloredlogs` package is my attempt to do Python logging right and system
  10. logging is an important part of that equation.
  11. - I've seen a surprising number of quirks and mistakes in system logging done
  12. in Python, for example including ``%(asctime)s`` in a format string (the
  13. system logging daemon is responsible for adding timestamps and thus you end
  14. up with duplicate timestamps that make the logs awful to read :-).
  15. - The ``%(programname)s`` filter originated in my system logging code and I
  16. wanted it in `coloredlogs` so the step to include this module wasn't that big.
  17. - As a bonus this Python module now has a test suite and proper documentation.
  18. So there :-P. Go take a look at :func:`enable_system_logging()`.
  19. """
  20. # Standard library modules.
  21. import logging
  22. import logging.handlers
  23. import os
  24. import socket
  25. import sys
  26. # External dependencies.
  27. from humanfriendly import coerce_boolean
  28. from humanfriendly.compat import on_macos, on_windows
  29. # Modules included in our package.
  30. from coloredlogs import (
  31. DEFAULT_LOG_LEVEL,
  32. ProgramNameFilter,
  33. adjust_level,
  34. find_program_name,
  35. level_to_number,
  36. replace_handler,
  37. )
  38. LOG_DEVICE_MACOSX = '/var/run/syslog'
  39. """The pathname of the log device on Mac OS X (a string)."""
  40. LOG_DEVICE_UNIX = '/dev/log'
  41. """The pathname of the log device on Linux and most other UNIX systems (a string)."""
  42. DEFAULT_LOG_FORMAT = '%(programname)s[%(process)d]: %(levelname)s %(message)s'
  43. """
  44. The default format for log messages sent to the system log (a string).
  45. The ``%(programname)s`` format requires :class:`~coloredlogs.ProgramNameFilter`
  46. but :func:`enable_system_logging()` takes care of this for you.
  47. The ``name[pid]:`` construct (specifically the colon) in the format allows
  48. rsyslogd_ to extract the ``$programname`` from each log message, which in turn
  49. allows configuration files in ``/etc/rsyslog.d/*.conf`` to filter these log
  50. messages to a separate log file (if the need arises).
  51. .. _rsyslogd: https://en.wikipedia.org/wiki/Rsyslog
  52. """
  53. # Initialize a logger for this module.
  54. logger = logging.getLogger(__name__)
  55. class SystemLogging(object):
  56. """Context manager to enable system logging."""
  57. def __init__(self, *args, **kw):
  58. """
  59. Initialize a :class:`SystemLogging` object.
  60. :param args: Positional arguments to :func:`enable_system_logging()`.
  61. :param kw: Keyword arguments to :func:`enable_system_logging()`.
  62. """
  63. self.args = args
  64. self.kw = kw
  65. self.handler = None
  66. def __enter__(self):
  67. """Enable system logging when entering the context."""
  68. if self.handler is None:
  69. self.handler = enable_system_logging(*self.args, **self.kw)
  70. return self.handler
  71. def __exit__(self, exc_type=None, exc_value=None, traceback=None):
  72. """
  73. Disable system logging when leaving the context.
  74. .. note:: If an exception is being handled when we leave the context a
  75. warning message including traceback is logged *before* system
  76. logging is disabled.
  77. """
  78. if self.handler is not None:
  79. if exc_type is not None:
  80. logger.warning("Disabling system logging due to unhandled exception!", exc_info=True)
  81. (self.kw.get('logger') or logging.getLogger()).removeHandler(self.handler)
  82. self.handler = None
  83. def enable_system_logging(programname=None, fmt=None, logger=None, reconfigure=True, **kw):
  84. """
  85. Redirect :mod:`logging` messages to the system log (e.g. ``/var/log/syslog``).
  86. :param programname: The program name to embed in log messages (a string, defaults
  87. to the result of :func:`~coloredlogs.find_program_name()`).
  88. :param fmt: The log format for system log messages (a string, defaults to
  89. :data:`DEFAULT_LOG_FORMAT`).
  90. :param logger: The logger to which the :class:`~logging.handlers.SysLogHandler`
  91. should be connected (defaults to the root logger).
  92. :param level: The logging level for the :class:`~logging.handlers.SysLogHandler`
  93. (defaults to :data:`.DEFAULT_LOG_LEVEL`). This value is coerced
  94. using :func:`~coloredlogs.level_to_number()`.
  95. :param reconfigure: If :data:`True` (the default) multiple calls to
  96. :func:`enable_system_logging()` will each override
  97. the previous configuration.
  98. :param kw: Refer to :func:`connect_to_syslog()`.
  99. :returns: A :class:`~logging.handlers.SysLogHandler` object or
  100. :data:`None`. If an existing handler is found and `reconfigure`
  101. is :data:`False` the existing handler object is returned. If the
  102. connection to the system logging daemon fails :data:`None` is
  103. returned.
  104. As of release 15.0 this function uses :func:`is_syslog_supported()` to
  105. check whether system logging is supported and appropriate before it's
  106. enabled.
  107. .. note:: When the logger's effective level is too restrictive it is
  108. relaxed (refer to `notes about log levels`_ for details).
  109. """
  110. # Check whether system logging is supported / appropriate.
  111. if not is_syslog_supported():
  112. return None
  113. # Provide defaults for omitted arguments.
  114. programname = programname or find_program_name()
  115. logger = logger or logging.getLogger()
  116. fmt = fmt or DEFAULT_LOG_FORMAT
  117. level = level_to_number(kw.get('level', DEFAULT_LOG_LEVEL))
  118. # Check whether system logging is already enabled.
  119. handler, logger = replace_handler(logger, match_syslog_handler, reconfigure)
  120. # Make sure reconfiguration is allowed or not relevant.
  121. if not (handler and not reconfigure):
  122. # Create a system logging handler.
  123. handler = connect_to_syslog(**kw)
  124. # Make sure the handler was successfully created.
  125. if handler:
  126. # Enable the use of %(programname)s.
  127. ProgramNameFilter.install(handler=handler, fmt=fmt, programname=programname)
  128. # Connect the formatter, handler and logger.
  129. handler.setFormatter(logging.Formatter(fmt))
  130. logger.addHandler(handler)
  131. # Adjust the level of the selected logger.
  132. adjust_level(logger, level)
  133. return handler
  134. def connect_to_syslog(address=None, facility=None, level=None):
  135. """
  136. Create a :class:`~logging.handlers.SysLogHandler`.
  137. :param address: The device file or network address of the system logging
  138. daemon (a string or tuple, defaults to the result of
  139. :func:`find_syslog_address()`).
  140. :param facility: Refer to :class:`~logging.handlers.SysLogHandler`.
  141. Defaults to ``LOG_USER``.
  142. :param level: The logging level for the :class:`~logging.handlers.SysLogHandler`
  143. (defaults to :data:`.DEFAULT_LOG_LEVEL`). This value is coerced
  144. using :func:`~coloredlogs.level_to_number()`.
  145. :returns: A :class:`~logging.handlers.SysLogHandler` object or :data:`None` (if the
  146. system logging daemon is unavailable).
  147. The process of connecting to the system logging daemon goes as follows:
  148. - The following two socket types are tried (in decreasing preference):
  149. 1. :data:`~socket.SOCK_RAW` avoids truncation of log messages but may
  150. not be supported.
  151. 2. :data:`~socket.SOCK_STREAM` (TCP) supports longer messages than the
  152. default (which is UDP).
  153. """
  154. if not address:
  155. address = find_syslog_address()
  156. if facility is None:
  157. facility = logging.handlers.SysLogHandler.LOG_USER
  158. if level is None:
  159. level = DEFAULT_LOG_LEVEL
  160. for socktype in socket.SOCK_RAW, socket.SOCK_STREAM, None:
  161. kw = dict(facility=facility, address=address)
  162. if socktype is not None:
  163. kw['socktype'] = socktype
  164. try:
  165. handler = logging.handlers.SysLogHandler(**kw)
  166. except IOError:
  167. # IOError is a superclass of socket.error which can be raised if the system
  168. # logging daemon is unavailable.
  169. pass
  170. else:
  171. handler.setLevel(level_to_number(level))
  172. return handler
  173. def find_syslog_address():
  174. """
  175. Find the most suitable destination for system log messages.
  176. :returns: The pathname of a log device (a string) or an address/port tuple as
  177. supported by :class:`~logging.handlers.SysLogHandler`.
  178. On Mac OS X this prefers :data:`LOG_DEVICE_MACOSX`, after that :data:`LOG_DEVICE_UNIX`
  179. is checked for existence. If both of these device files don't exist the default used
  180. by :class:`~logging.handlers.SysLogHandler` is returned.
  181. """
  182. if sys.platform == 'darwin' and os.path.exists(LOG_DEVICE_MACOSX):
  183. return LOG_DEVICE_MACOSX
  184. elif os.path.exists(LOG_DEVICE_UNIX):
  185. return LOG_DEVICE_UNIX
  186. else:
  187. return 'localhost', logging.handlers.SYSLOG_UDP_PORT
  188. def is_syslog_supported():
  189. """
  190. Determine whether system logging is supported.
  191. :returns:
  192. :data:`True` if system logging is supported and can be enabled,
  193. :data:`False` if system logging is not supported or there are good
  194. reasons for not enabling it.
  195. The decision making process here is as follows:
  196. Override
  197. If the environment variable ``$COLOREDLOGS_SYSLOG`` is set it is evaluated
  198. using :func:`~humanfriendly.coerce_boolean()` and the resulting value
  199. overrides the platform detection discussed below, this allows users to
  200. override the decision making process if they disagree / know better.
  201. Linux / UNIX
  202. On systems that are not Windows or MacOS (see below) we assume UNIX which
  203. means either syslog is available or sending a bunch of UDP packets to
  204. nowhere won't hurt anyone...
  205. Microsoft Windows
  206. Over the years I've had multiple reports of :pypi:`coloredlogs` spewing
  207. extremely verbose errno 10057 warning messages to the console (once for
  208. each log message I suppose) so I now assume it a default that
  209. "syslog-style system logging" is not generally available on Windows.
  210. Apple MacOS
  211. There's cPython issue `#38780`_ which seems to result in a fatal exception
  212. when the Python interpreter shuts down. This is (way) worse than not
  213. having system logging enabled. The error message mentioned in `#38780`_
  214. has actually been following me around for years now, see for example:
  215. - https://github.com/xolox/python-rotate-backups/issues/9 mentions Docker
  216. images implying Linux, so not strictly the same as `#38780`_.
  217. - https://github.com/xolox/python-npm-accel/issues/4 is definitely related
  218. to `#38780`_ and is what eventually prompted me to add the
  219. :func:`is_syslog_supported()` logic.
  220. .. _#38780: https://bugs.python.org/issue38780
  221. """
  222. override = os.environ.get("COLOREDLOGS_SYSLOG")
  223. if override is not None:
  224. return coerce_boolean(override)
  225. else:
  226. return not (on_windows() or on_macos())
  227. def match_syslog_handler(handler):
  228. """
  229. Identify system logging handlers.
  230. :param handler: The :class:`~logging.Handler` class to check.
  231. :returns: :data:`True` if the handler is a
  232. :class:`~logging.handlers.SysLogHandler`,
  233. :data:`False` otherwise.
  234. This function can be used as a callback for :func:`.find_handler()`.
  235. """
  236. return isinstance(handler, logging.handlers.SysLogHandler)