logging_ext.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. # -*- coding: utf-8 -*-
  2. # copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
  3. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
  4. #
  5. # This file is part of logilab-common.
  6. #
  7. # logilab-common is free software: you can redistribute it and/or modify it under
  8. # the terms of the GNU Lesser General Public License as published by the Free
  9. # Software Foundation, either version 2.1 of the License, or (at your option) any
  10. # later version.
  11. #
  12. # logilab-common is distributed in the hope that it will be useful, but WITHOUT
  13. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  14. # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  15. # details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public License along
  18. # with logilab-common. If not, see <http://www.gnu.org/licenses/>.
  19. """Extends the logging module from the standard library."""
  20. __docformat__ = "restructuredtext en"
  21. import os
  22. import sys
  23. import logging
  24. from logilab.common.textutils import colorize_ansi
  25. def set_log_methods(cls, logger):
  26. """bind standard logger's methods as methods on the class"""
  27. cls.__logger = logger
  28. for attr in ('debug', 'info', 'warning', 'error', 'critical', 'exception'):
  29. setattr(cls, attr, getattr(logger, attr))
  30. def xxx_cyan(record):
  31. if 'XXX' in record.message:
  32. return 'cyan'
  33. class ColorFormatter(logging.Formatter):
  34. """
  35. A color Formatter for the logging standard module.
  36. By default, colorize CRITICAL and ERROR in red, WARNING in orange, INFO in
  37. green and DEBUG in yellow.
  38. self.colors is customizable via the 'color' constructor argument (dictionary).
  39. self.colorfilters is a list of functions that get the LogRecord
  40. and return a color name or None.
  41. """
  42. def __init__(self, fmt=None, datefmt=None, colors=None):
  43. logging.Formatter.__init__(self, fmt, datefmt)
  44. self.colorfilters = []
  45. self.colors = {'CRITICAL': 'red',
  46. 'ERROR': 'red',
  47. 'WARNING': 'magenta',
  48. 'INFO': 'green',
  49. 'DEBUG': 'yellow',
  50. }
  51. if colors is not None:
  52. assert isinstance(colors, dict)
  53. self.colors.update(colors)
  54. def format(self, record):
  55. msg = logging.Formatter.format(self, record)
  56. if record.levelname in self.colors:
  57. color = self.colors[record.levelname]
  58. return colorize_ansi(msg, color)
  59. else:
  60. for cf in self.colorfilters:
  61. color = cf(record)
  62. if color:
  63. return colorize_ansi(msg, color)
  64. return msg
  65. def set_color_formatter(logger=None, **kw):
  66. """
  67. Install a color formatter on the 'logger'. If not given, it will
  68. defaults to the default logger.
  69. Any additional keyword will be passed as-is to the ColorFormatter
  70. constructor.
  71. """
  72. if logger is None:
  73. logger = logging.getLogger()
  74. if not logger.handlers:
  75. logging.basicConfig()
  76. format_msg = logger.handlers[0].formatter._fmt
  77. fmt = ColorFormatter(format_msg, **kw)
  78. fmt.colorfilters.append(xxx_cyan)
  79. logger.handlers[0].setFormatter(fmt)
  80. LOG_FORMAT = '%(asctime)s - (%(name)s) %(levelname)s: %(message)s'
  81. LOG_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
  82. def get_handler(debug=False, syslog=False, logfile=None, rotation_parameters=None):
  83. """get an apropriate handler according to given parameters"""
  84. if os.environ.get('APYCOT_ROOT'):
  85. handler = logging.StreamHandler(sys.stdout)
  86. if debug:
  87. handler = logging.StreamHandler()
  88. elif logfile is None:
  89. if syslog:
  90. from logging import handlers
  91. handler = handlers.SysLogHandler()
  92. else:
  93. handler = logging.StreamHandler()
  94. else:
  95. try:
  96. if rotation_parameters is None:
  97. handler = logging.FileHandler(logfile)
  98. else:
  99. from logging.handlers import TimedRotatingFileHandler
  100. handler = TimedRotatingFileHandler(
  101. logfile, **rotation_parameters)
  102. except IOError:
  103. handler = logging.StreamHandler()
  104. return handler
  105. def get_threshold(debug=False, logthreshold=None):
  106. if logthreshold is None:
  107. if debug:
  108. logthreshold = logging.DEBUG
  109. else:
  110. logthreshold = logging.ERROR
  111. elif isinstance(logthreshold, basestring):
  112. logthreshold = getattr(logging, THRESHOLD_MAP.get(logthreshold,
  113. logthreshold))
  114. return logthreshold
  115. def get_formatter(logformat=LOG_FORMAT, logdateformat=LOG_DATE_FORMAT):
  116. isatty = hasattr(sys.__stdout__, 'isatty') and sys.__stdout__.isatty()
  117. if isatty and sys.platform != 'win32':
  118. fmt = ColorFormatter(logformat, logdateformat)
  119. def col_fact(record):
  120. if 'XXX' in record.message:
  121. return 'cyan'
  122. if 'kick' in record.message:
  123. return 'red'
  124. fmt.colorfilters.append(col_fact)
  125. else:
  126. fmt = logging.Formatter(logformat, logdateformat)
  127. return fmt
  128. def init_log(debug=False, syslog=False, logthreshold=None, logfile=None,
  129. logformat=LOG_FORMAT, logdateformat=LOG_DATE_FORMAT, fmt=None,
  130. rotation_parameters=None, handler=None):
  131. """init the log service"""
  132. logger = logging.getLogger()
  133. if handler is None:
  134. handler = get_handler(debug, syslog, logfile, rotation_parameters)
  135. # only addHandler and removeHandler method while I would like a setHandler
  136. # method, so do it this way :$
  137. logger.handlers = [handler]
  138. logthreshold = get_threshold(debug, logthreshold)
  139. logger.setLevel(logthreshold)
  140. if fmt is None:
  141. if debug:
  142. fmt = get_formatter(logformat=logformat, logdateformat=logdateformat)
  143. else:
  144. fmt = logging.Formatter(logformat, logdateformat)
  145. handler.setFormatter(fmt)
  146. return handler
  147. # map logilab.common.logger thresholds to logging thresholds
  148. THRESHOLD_MAP = {'LOG_DEBUG': 'DEBUG',
  149. 'LOG_INFO': 'INFO',
  150. 'LOG_NOTICE': 'INFO',
  151. 'LOG_WARN': 'WARNING',
  152. 'LOG_WARNING': 'WARNING',
  153. 'LOG_ERR': 'ERROR',
  154. 'LOG_ERROR': 'ERROR',
  155. 'LOG_CRIT': 'CRITICAL',
  156. }