0001"""Logging related functionality"""
0002import logging
0003import types
0004
0005import pylons
0006
0007__all__ = ['WSGIErrorsHandler']
0008
0009class WSGIErrorsHandler(logging.Handler):
0010 """A handler class that writes logging records to environ['wsgi.errors'].
0011
0012 This code is derived from CherryPy's cherrypy._cplogging.WSGIErrorHandler.
0013 """
0014
0015 def __init__(self, cache=True, *args, **kwargs):
0016 """
0017 ``cache``
0018 Whether or not the wsgi.errors stream is cached (instead of looked
0019 up via pylons.request.environ for logged message)
0020 """
0021 logging.Handler.__init__(self, *args, **kwargs)
0022 self.cache = cache
0023 self.cached_stream = None
0024
0025 def get_wsgierrors(self):
0026 """Return the wsgi.errors stream
0027
0028 Raises a TypeError when outside of a web request (pylons.request is not
0029 setup)
0030 """
0031 if not self.cache:
0032 return pylons.request.environ.get('wsgi.errors')
0033 elif not self.cached_stream:
0034 self.cached_stream = pylons.request.environ.get('wsgi.errors')
0035 return self.cached_stream
0036 return self.cached_stream
0037
0038 def flush(self):
0039 """Flushes the stream"""
0040 try:
0041 stream = self.get_wsgierrors()
0042 except TypeError:
0043 pass
0044 else:
0045 if stream:
0046 stream.flush()
0047
0048 def emit(self, record):
0049 """Emit a record"""
0050 try:
0051 stream = self.get_wsgierrors()
0052 except TypeError:
0053 pass
0054 else:
0055 if not stream:
0056 return
0057 try:
0058 msg = self.format(record)
0059 fs = "%s\n"
0060 if not hasattr(types, "UnicodeType"): #if no unicode support...
0061 stream.write(fs % msg)
0062 else:
0063 try:
0064 stream.write(fs % msg)
0065 except UnicodeError:
0066 stream.write(fs % msg.encode("UTF-8"))
0067 self.flush()
0068 except (KeyboardInterrupt, SystemExit):
0069 raise
0070 except:
0071 self.handleError(record)