cppo-ng/blocksfree/logging.py
T. Joseph Carter d4d9cc8072 Use textwrap to dedent multi-line strings
This is kind of an expensive thing to do unconditionally, but it lets us make
multi-line strings fit into the code with less ugliness.  Basically, if you're
four levels in, you can do something like this:

                log.warn("""\
                There was a problem.
                It was probably wasn't fatal because this
                is only a warning, but it is enough to have
                a multiline string.
                """)

This will print without the indentation.  It's not quite as clean as how
docutils handles docstrings (allowing the first line to be unindented, hence
the line-continuation), but it's still an improvement.  If you can improve upon
this, please feel free to PR it!
2017-07-07 02:32:20 -07:00

36 lines
937 B
Python

import sys
import logging
import textwrap
### LOGGING
# *sigh* No clean/simple way to use str.format() type log strings without
# jumping through a few hoops
class Message(object):
def __init__(self, fmt, args):
self.fmt = fmt
self.args = args
def __str__(self):
return self.fmt.format(*self.args)
class StyleAdapter(logging.LoggerAdapter):
def __init__(self, logger, extra=None):
super(StyleAdapter, self).__init__(logger, extra or {})
def log(self, level, msg, *args, **kwargs):
if self.isEnabledFor(level):
msg, kwargs = self.process(textwrap.dedent(msg), kwargs)
self.logger._log(level, Message(str(msg), args), (), **kwargs)
log = StyleAdapter(logging.getLogger(__name__))
# Set up our logging facility
_handler = logging.StreamHandler(sys.stdout)
_formatter = logging.Formatter('%(levelname)s: %(message)s')
_handler.setFormatter(_formatter)
log.logger.addHandler(_handler)
log.setLevel(logging.DEBUG)