# Path: tornado/log.py
# class LogFormatter(logging.Formatter):
#     """Log formatter used in Tornado.
# 
#     Key features of this formatter are:
# 
#     * Color support when logging to a terminal that supports it.
#     * Timestamps on every log line.
#     * Robust against str/bytes encoding problems.
# 
#     This formatter is enabled automatically by
#     `tornado.options.parse_command_line` (unless ``--logging=none`` is
#     used).
#     """
#     def __init__(self, color=True, *args, **kwargs):
#         logging.Formatter.__init__(self, *args, **kwargs)
#         self._color = color and _stderr_supports_color()
#         if self._color:
#             # The curses module has some str/bytes confusion in
#             # python3.  Until version 3.2.3, most methods return
#             # bytes, but only accept strings.  In addition, we want to
#             # output these strings with the logging module, which
#             # works with unicode strings.  The explicit calls to
#             # unicode() below are harmless in python2 but will do the
#             # right conversion in python 3.
#             fg_color = (curses.tigetstr("setaf") or
#                         curses.tigetstr("setf") or "")
#             if (3, 0) < sys.version_info < (3, 2, 3):
#                 fg_color = unicode(fg_color, "ascii")
#             self._colors = {
#                 logging.DEBUG: unicode(curses.tparm(fg_color, 4),  # Blue
#                                        "ascii"),
#                 logging.INFO: unicode(curses.tparm(fg_color, 2),  # Green
#                                       "ascii"),
#                 logging.WARNING: unicode(curses.tparm(fg_color, 3),  # Yellow
#                                          "ascii"),
#                 logging.ERROR: unicode(curses.tparm(fg_color, 1),  # Red
#                                        "ascii"),
#             }
#             self._normal = unicode(curses.tigetstr("sgr0"), "ascii")
# 
#     def format(self, record):
#         try:
#             record.message = record.getMessage()
#         except Exception, e:
#             record.message = "Bad message (%r): %r" % (e, record.__dict__)
#         assert isinstance(record.message, basestring)  # guaranteed by logging
#         record.asctime = time.strftime(
#             "%y%m%d %H:%M:%S", self.converter(record.created))
#         prefix = '[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]' % \
#             record.__dict__
#         if self._color:
#             prefix = (self._colors.get(record.levelno, self._normal) +
#                       prefix + self._normal)
# 
#         # Encoding notes:  The logging module prefers to work with character
#         # strings, but only enforces that log messages are instances of
#         # basestring.  In python 2, non-ascii bytestrings will make
#         # their way through the logging framework until they blow up with
#         # an unhelpful decoding error (with this formatter it happens
#         # when we attach the prefix, but there are other opportunities for
#         # exceptions further along in the framework).
#         #
#         # If a byte string makes it this far, convert it to unicode to
#         # ensure it will make it out to the logs.  Use repr() as a fallback
#         # to ensure that all byte strings can be converted successfully,
#         # but don't do it by default so we don't add extra quotes to ascii
#         # bytestrings.  This is a bit of a hacky place to do this, but
#         # it's worth it since the encoding errors that would otherwise
#         # result are so useless (and tornado is fond of using utf8-encoded
#         # byte strings whereever possible).
#         try:
#             message = _unicode(record.message)
#         except UnicodeDecodeError:
#             message = repr(record.message)
# 
#         formatted = prefix + " " + message
#         if record.exc_info:
#             if not record.exc_text:
#                 record.exc_text = self.formatException(record.exc_info)
#         if record.exc_text:
#             formatted = formatted.rstrip() + "\n" + record.exc_text
#         return formatted.replace("\n", "\n    ")
# 
# Path: tornado/test/util.py

# 
# Path: tornado/util.py
# class ObjectDict(dict):
# class GzipDecompressor(object):
# class Configurable(object):
#     def __getattr__(self, name):
#     def __setattr__(self, name, value):
#     def __init__(self):
#     def decompress(self, value):
#     def flush(self):
# def import_object(name):
#     def b(s):
#     def b(s):
# def raise_exc_info(exc_info):
#     def __new__(cls, **kwargs):
#     def configurable_base(cls):
#     def configurable_default(cls):
#     def initialize(self):
#     def configure(cls, impl, **kwargs):
#     def configured_class(cls):
#     def _save_configuration(cls):
#     def _restore_configuration(cls, saved):
# def doctests():


import contextlib
import logging
import os
import re
import tempfile
import warnings
from tornado.escape import utf8
from tornado.log import LogFormatter
from tornado.test.util import unittest
from tornado.util import b, bytes_type

    def tearDown(self):
        self.handler.close()
        os.unlink(self.filename)
        os.rmdir(self.tempdir)

    def make_handler(self, filename):
        # Base case: default setup without explicit encoding.
        # In python 2, supports arbitrary byte strings and unicode objects
        # that contain only ascii.  In python 3, supports ascii-only unicode
        # strings (but byte strings will be repr'd automatically).
        return logging.FileHandler(filename)

    def get_output(self):
        with open(self.filename, "rb") as f:
            line = f.read().strip()
            m = LogFormatterTest.LINE_RE.match(line)
            if m:
                return m.group(1)
            else:
                raise Exception("output didn't match regex: %r" % line)

    def test_basic_logging(self):
        self.logger.error("foo")
        self.assertEqual(self.get_output(), b("foo"))

    def test_bytes_logging(self):
        with ignore_bytes_warning():
            # This will be "\xe9" on python 2 or "b'\xe9'" on python 3
            self.logger.error(b("\xe9"))

# Path: tornado/log.py
# class LogFormatter(logging.Formatter):
#     """Log formatter used in Tornado.
# 
#     Key features of this formatter are:
# 
#     * Color support when logging to a terminal that supports it.
#     * Timestamps on every log line.
#     * Robust against str/bytes encoding problems.
# 
#     This formatter is enabled automatically by
#     `tornado.options.parse_command_line` (unless ``--logging=none`` is
#     used).
#     """
#     def __init__(self, color=True, *args, **kwargs):
#         logging.Formatter.__init__(self, *args, **kwargs)
#         self._color = color and _stderr_supports_color()
#         if self._color:
#             # The curses module has some str/bytes confusion in
#             # python3.  Until version 3.2.3, most methods return
#             # bytes, but only accept strings.  In addition, we want to
#             # output these strings with the logging module, which
#             # works with unicode strings.  The explicit calls to
#             # unicode() below are harmless in python2 but will do the
#             # right conversion in python 3.
#             fg_color = (curses.tigetstr("setaf") or
#                         curses.tigetstr("setf") or "")
#             if (3, 0) < sys.version_info < (3, 2, 3):
#                 fg_color = unicode(fg_color, "ascii")
#             self._colors = {
#                 logging.DEBUG: unicode(curses.tparm(fg_color, 4),  # Blue
#                                        "ascii"),
#                 logging.INFO: unicode(curses.tparm(fg_color, 2),  # Green
#                                       "ascii"),
#                 logging.WARNING: unicode(curses.tparm(fg_color, 3),  # Yellow
#                                          "ascii"),
#                 logging.ERROR: unicode(curses.tparm(fg_color, 1),  # Red
#                                        "ascii"),
#             }
#             self._normal = unicode(curses.tigetstr("sgr0"), "ascii")
# 
#     def format(self, record):
#         try:
#             record.message = record.getMessage()
#         except Exception, e:
#             record.message = "Bad message (%r): %r" % (e, record.__dict__)
#         assert isinstance(record.message, basestring)  # guaranteed by logging
#         record.asctime = time.strftime(
#             "%y%m%d %H:%M:%S", self.converter(record.created))
#         prefix = '[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]' % \
#             record.__dict__
#         if self._color:
#             prefix = (self._colors.get(record.levelno, self._normal) +
#                       prefix + self._normal)
# 
#         # Encoding notes:  The logging module prefers to work with character
#         # strings, but only enforces that log messages are instances of
#         # basestring.  In python 2, non-ascii bytestrings will make
#         # their way through the logging framework until they blow up with
#         # an unhelpful decoding error (with this formatter it happens
#         # when we attach the prefix, but there are other opportunities for
#         # exceptions further along in the framework).
#         #
#         # If a byte string makes it this far, convert it to unicode to
#         # ensure it will make it out to the logs.  Use repr() as a fallback
#         # to ensure that all byte strings can be converted successfully,
#         # but don't do it by default so we don't add extra quotes to ascii
#         # bytestrings.  This is a bit of a hacky place to do this, but
#         # it's worth it since the encoding errors that would otherwise
#         # result are so useless (and tornado is fond of using utf8-encoded
#         # byte strings whereever possible).
#         try:
#             message = _unicode(record.message)
#         except UnicodeDecodeError:
#             message = repr(record.message)
# 
#         formatted = prefix + " " + message
#         if record.exc_info:
#             if not record.exc_text:
#                 record.exc_text = self.formatException(record.exc_info)
#         if record.exc_text:
#             formatted = formatted.rstrip() + "\n" + record.exc_text
#         return formatted.replace("\n", "\n    ")
# 
# Path: tornado/test/util.py

# 
# Path: tornado/util.py
# class ObjectDict(dict):
# class GzipDecompressor(object):
# class Configurable(object):
#     def __getattr__(self, name):
#     def __setattr__(self, name, value):
#     def __init__(self):
#     def decompress(self, value):
#     def flush(self):
# def import_object(name):
#     def b(s):
#     def b(s):
# def raise_exc_info(exc_info):
#     def __new__(cls, **kwargs):
#     def configurable_base(cls):
#     def configurable_default(cls):
#     def initialize(self):
#     def configure(cls, impl, **kwargs):
#     def configured_class(cls):
#     def _save_configuration(cls):
#     def _restore_configuration(cls, saved):
# def doctests():


# Path: tornado/test/log_test.py
import contextlib
import logging
import os
import re
import tempfile
import warnings
from tornado.escape import utf8
from tornado.log import LogFormatter
from tornado.test.util import unittest
from tornado.util import b, bytes_type


    def tearDown(self):
        self.handler.close()
        os.unlink(self.filename)
        os.rmdir(self.tempdir)

    def make_handler(self, filename):
        # Base case: default setup without explicit encoding.
        # In python 2, supports arbitrary byte strings and unicode objects
        # that contain only ascii.  In python 3, supports ascii-only unicode
        # strings (but byte strings will be repr'd automatically).
        return logging.FileHandler(filename)

    def get_output(self):
        with open(self.filename, "rb") as f:
            line = f.read().strip()
            m = LogFormatterTest.LINE_RE.match(line)
            if m:
                return m.group(1)
            else:
                raise Exception("output didn't match regex: %r" % line)

    def test_basic_logging(self):
        self.logger.error("foo")
        self.assertEqual(self.get_output(), b("foo"))

    def test_bytes_logging(self):
        with ignore_bytes_warning():
            # This will be "\xe9" on python 2 or "b'\xe9'" on python 3
            self.logger.error(b("\xe9"))

            self.assertEqual(self.get_output(), utf8(repr(b("\xe9"))))